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
|
<repo_name>mulflar/Ongawa_app<file_sep>/Ongawa/Pantallas/introAct.cs
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Locations;
using Android.OS;
using Android.Views;
using Android.Widget;
using Newtonsoft.Json;
using Ongawa.Clases;
using Ongawa.Servicios;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Ongawa.Pantallas
{
[Activity(Icon = "@drawable/icon", ScreenOrientation = ScreenOrientation.Portrait)]
public class introAct : Activity, ILocationListener
{
Location _currentLocation;
LocationManager _locationManager;
string _locationProvider;
TextView estadoLoc;
TextView ubicacion;
encuesta_raw datos;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
RequestWindowFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Inicio);
FindViewById<ImageButton>(Resource.Id.botGetLoc).Click += AddressButton_OnClick;
estadoLoc = FindViewById<TextView>(Resource.Id.LocStatus);
ubicacion = FindViewById<TextView>(Resource.Id.address);
datos = new encuesta_raw();
InitializeLocationManager();
}
void InitializeLocationManager()
{
_locationManager = (LocationManager)GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Fine,
PowerRequirement = Power.High
};
IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
if (acceptableLocationProviders.Any())
{
_locationProvider = acceptableLocationProviders.First();
_locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
}
else
{
_locationProvider = string.Empty;
estadoLoc.Text = GetString(Resource.String.errorLoc);
}
}
async void AddressButton_OnClick(object sender, EventArgs eventArgs)
{
if (_currentLocation == null)
{
estadoLoc.Text = GetString(Resource.String.awaitLoc);
return;
}
Address address = await ReverseGeocodeCurrentLocation();
estadoLoc.Text = address.CountryName + ", " + address.Locality + ", " + address.GetAddressLine(0);
estadoLoc.Text = "Ubicado";
ubicacion.Text = "Centro, Alicante, Alicante, Espaņa";
ProgressBar prog = FindViewById<ProgressBar>(Resource.Id.progBar);
prog.Visibility = ViewStates.Invisible;
}
async Task<Address> ReverseGeocodeCurrentLocation()
{
Geocoder geocoder = new Geocoder(this);
IList<Address> addressList =
await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10);
Address address = addressList.FirstOrDefault();
return address;
}
protected override void OnResume()
{
base.OnResume();
_locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
}
protected override void OnPause()
{
base.OnPause();
_locationManager.RemoveUpdates(this);
}
public async void OnLocationChanged(Location location)
{
_currentLocation = location;
if (_currentLocation == null)
{
estadoLoc.Text = GetString(Resource.String.awaitLoc);
}
else
{
Address address = await ReverseGeocodeCurrentLocation();
estadoLoc.Text = address.CountryName + ", " + address.Locality + ", " + address.GetAddressLine(0);
ProgressBar prog = FindViewById<ProgressBar>(Resource.Id.progBar);
prog.Visibility = ViewStates.Invisible;
}
}
public void OnProviderDisabled(string provider) { }
public void OnProviderEnabled(string provider) { }
public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
[Java.Interop.Export("nuevo")]
public void nuevo(View view)
{
datos.direccion = ubicacion.Text;
datos.lat = (long)_currentLocation.Latitude;
datos.lon = (long)_currentLocation.Longitude;
datos.fam = FindViewById<TextView>(Resource.Id.refFam).Text;
var activity = new Intent(this, typeof(sanitAct));
activity.PutExtra("encuesta", JsonConvert.SerializeObject(datos));
StartActivity(activity);
}
[Java.Interop.Export("logout")]
public void logout(View view)
{
Persistencia storer = new Persistencia(this);
storer.clearKey();
StartActivity(typeof(loginAct));
Finish();
}
}
}<file_sep>/Ongawa/Servicios/Auxiliar.cs
using Android.App;
using Android.Content;
namespace Ongawa.Servicios
{
public static class Auxiliar
{
public static AlertDialog.Builder AlertBox(string errorMsg, Context context)
{
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.SetTitle("ERROR");
dialog.SetMessage(errorMsg);
dialog.SetNeutralButton("ACEPTAR", (s, EventArgs) => { });
return dialog;
}
}
}<file_sep>/Ongawa/Pantallas/resumAct.cs
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Newtonsoft.Json;
using Ongawa.Clases;
using Ongawa.Servicios;
namespace Ongawa.Pantallas
{
[Activity(Icon = "@drawable/icon", ScreenOrientation = ScreenOrientation.Portrait)]
public class resumAct : Activity
{
encuesta_raw datos;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Resumen);
datos = JsonConvert.DeserializeObject<encuesta_raw>(Intent.GetStringExtra("encuesta"));
FindViewById<TextView>(Resource.Id.refText).Text = datos.fam;
FindViewById<TextView>(Resource.Id.locationtext).Text = datos.direccion;
if (datos.agu == 1)
FindViewById<TextView>(Resource.Id.agu).Text = "SI";
else
FindViewById<TextView>(Resource.Id.agu).Text = "NO";
if (datos.ven == 1)
FindViewById<TextView>(Resource.Id.vent).Text = "SI";
else
FindViewById<TextView>(Resource.Id.vent).Text = "NO";
if (datos.mos == 1)
FindViewById<TextView>(Resource.Id.mos).Text = "SI";
else
FindViewById<TextView>(Resource.Id.mos).Text = "NO";
if (datos.olo == 1)
FindViewById<TextView>(Resource.Id.olo).Text = "SI";
else
FindViewById<TextView>(Resource.Id.olo).Text = "NO";
if (datos.pri == 1)
FindViewById<TextView>(Resource.Id.pri).Text = "SI";
else
FindViewById<TextView>(Resource.Id.pri).Text = "NO";
switch (datos.mat)
{
case 1:
FindViewById<ImageView>(Resource.Id.imageLosa).SetImageResource(Resource.Drawable.madera);
break;
case 2:
FindViewById<ImageView>(Resource.Id.imageLosa).SetImageResource(Resource.Drawable.ceramica1);
break;
case 3:
FindViewById<ImageView>(Resource.Id.imageLosa).SetImageResource(Resource.Drawable.hormigon);
break;
case 4:
FindViewById<ImageView>(Resource.Id.imageLosa).SetImageResource(Resource.Drawable.piedra);
break;
}
switch (datos.cie)
{
case 1:
FindViewById<ImageView>(Resource.Id.imageCierre).SetImageResource(Resource.Drawable.cemento);
break;
case 2:
FindViewById<ImageView>(Resource.Id.imageCierre).SetImageResource(Resource.Drawable.ladrillo);
break;
case 3:
FindViewById<ImageView>(Resource.Id.imageCierre).SetImageResource(Resource.Drawable.madera);
break;
case 4:
FindViewById<ImageView>(Resource.Id.imageCierre).SetImageResource(Resource.Drawable.candado);
break;
}
}
[Java.Interop.Export("atras")]
public void atras(View view)
{
var activity = new Intent(this, typeof(sanitAct));
activity.PutExtra("encuesta", JsonConvert.SerializeObject(datos));
StartActivity(activity);
}
[Java.Interop.Export("aceptar")]
public void aceptar(View view)
{
new Thread(() =>
{
WebReference.encuesta webservice = new WebReference.encuesta();
webservice.insertreg(JsonConvert.SerializeObject(datos), "jkdgnnjbgjk34564534");
}).Start();
Persistencia storer = new Persistencia(this);
storer.store(datos);
StartActivity(typeof(introAct));
Finish();
}
}
}<file_sep>/Ongawa/Pantallas/loginAct.cs
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using Android.Widget;
using Ongawa.Servicios;
namespace Ongawa.Pantallas
{
[Activity(MainLauncher = true, Icon = "@drawable/icon", NoHistory = true, ScreenOrientation = ScreenOrientation.Portrait)]
public class loginAct : Activity
{
Persistencia storer;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
RequestWindowFeature(WindowFeatures.NoTitle);
storer = new Persistencia(this);
if(storer.checkKey())
{
StartActivity(typeof(introAct));
Finish();
}
else
SetContentView(Resource.Layout.Login);
}
/// <summary>
/// Logins the click.
/// </summary>
/// <param name="view">View.</param>
[Java.Interop.Export("loginClick")]
public void loginClick(View view)
{
WebReference.encuesta webservice = new WebReference.encuesta();
string user = FindViewById<EditText>(Resource.Id.usrBox).Text;
string password = FindViewById<EditText>(Resource.Id.passBox).Text;
if (user != "" && password != "")
{
int id = webservice.comprobaruser(user, password, "<PASSWORD>");
if(id>0)
{
storer.storeKey("1");
StartActivity(typeof(introAct));
Finish();
}
else
{
//usuario erroneo
AlertDialog.Builder dialog = Auxiliar.AlertBox(GetString(Resource.String.errorWrongUser), this);
dialog.Show();
}
}
else {
//campo vacio
AlertDialog.Builder dialog = Auxiliar.AlertBox(GetString(Resource.String.errorEmptyForm), this);
dialog.Show();
}
}
}
}<file_sep>/Ongawa/Clases/encuesta_raw.cs
using Android.Locations;
using Newtonsoft.Json;
using System;
namespace Ongawa.Clases
{
public class encuesta_raw
{
public DateTime fecha;
public string direccion;
public long lat;
public long lon;
public string fam;
public int ven;
public int pri;
public int cie;
public int mos;
public int olo;
public int agu;
public int mat;
public encuesta_raw()
{
fecha = DateTime.Now;
}
}
}<file_sep>/Ongawa/Adapters/ItemsAdapter.cs
using Android.App;
using Android.Views;
using Android.Widget;
using Ongawa.Clases;
using System.Collections.Generic;
namespace Ongawa.Adapters
{
class ItemsAdapter : BaseAdapter<encuesta_raw>
{
readonly List<encuesta_raw> listado;
readonly Activity context;
/// <summary>
/// Initializes a new instance of the <see cref="InformaticaRos.VisitasAdapter"/> class.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="items">Items.</param>
public ItemsAdapter(Activity context, List<encuesta_raw> items)
: base()
{
this.context = context;
this.listado = items;
}
/// <param name="position">The position of the item within the adapter's data set whose row id we want.</param>
/// <summary>
/// Get the row id associated with the specified position in the list.
/// </summary>
/// <returns>To be added.</returns>
public override long GetItemId(int position)
{
return position;
}
/// <summary>
/// Gets the <see cref="InformaticaRos.VisitasAdapter"/> at the specified index.
/// </summary>
/// <param name="index">Index.</param>
public override encuesta_raw this[int index]
{
get { return listado[index]; }
}
/// <summary>
/// How many items are in the data set represented by this Adapter.
/// </summary>
/// <value>To be added.</value>
public override int Count
{
get { return listado.Count; }
}
/// <param name="position">The position of the item within the adapter's data set of the item whose view
/// we want.</param>
/// <summary>
/// Gets the view.
/// </summary>
/// <returns>The view.</returns>
/// <param name="convertView">Convert view.</param>
/// <param name="parent">Parent.</param>
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = listado[position];
View view = convertView;
/*if (view == null) // no view to re-use, create new
view = context.LayoutInflater.Inflate(Resource.Layout.filaListados, null);
view.FindViewById<TextView>(Resource.Id.).Text = item.fecha.ToString();
view.FindViewById<TextView>(Resource.Id.cantBox).Text = item.fam.ToString();
view.FindViewById<TextView>(Resource.Id.cantBox).Text = item.direccion.ToString();*/
return view;
}
}
}
<file_sep>/Ongawa/Pantallas/sanitAct.cs
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.OS;
using Android.Views;
using Android.Widget;
using Newtonsoft.Json;
using Ongawa.Clases;
using System;
namespace Ongawa.Pantallas
{
[Activity(Icon = "@drawable/icon", ScreenOrientation = ScreenOrientation.Portrait)]
public class sanitAct : Activity
{
ImageButton losa_m;
ImageButton losa_c;
ImageButton losa_h;
ImageButton losa_p;
ImageButton cierre_cem;
ImageButton cierre_can;
ImageButton cierre_mad;
ImageButton cierra_lad;
encuesta_raw datos;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Sanitario);
datos = JsonConvert.DeserializeObject<encuesta_raw>(Intent.GetStringExtra("encuesta"));
losa_m = FindViewById<ImageButton>(Resource.Id.losa_madera);
losa_m.Click += losa_m_OnClick;
losa_c = FindViewById<ImageButton>(Resource.Id.losa_ceramica);
losa_c.Click += losa_c_OnClick;
losa_h = FindViewById<ImageButton>(Resource.Id.losa_hormigon);
losa_h.Click += losa_h_OnClick;
losa_p = FindViewById<ImageButton>(Resource.Id.losa_piedra);
losa_p.Click += losa_p_OnClick;
cierre_cem = FindViewById<ImageButton>(Resource.Id.cierre_cemento);
cierre_cem.Click += cierre_cem_OnClick;
cierre_can = FindViewById<ImageButton>(Resource.Id.cierre_candado);
cierre_can.Click += cierre_can_OnClick;
cierre_mad = FindViewById<ImageButton>(Resource.Id.cierre_madera);
cierre_mad.Click += cierre_mad_OnClick;
cierra_lad = FindViewById<ImageButton>(Resource.Id.cierre_ladrillo);
cierra_lad.Click += cierra_lad_OnClick;
}
#region cierres
void cierre_cem_OnClick(object sender, EventArgs eventArgs)
{
datos.cie = 1;
cierre_cem.SetColorFilter(Color.Argb(255, 255, 255, 255));
cierre_can.ClearColorFilter();
cierre_mad.ClearColorFilter();
cierra_lad.ClearColorFilter();
}
void cierre_can_OnClick(object sender, EventArgs eventArgs)
{
datos.cie = 4;
cierre_cem.ClearColorFilter();
cierre_can.SetColorFilter(Color.Argb(255, 255, 255, 255));
cierre_mad.ClearColorFilter();
cierra_lad.ClearColorFilter();
}
void cierre_mad_OnClick(object sender, EventArgs eventArgs)
{
datos.cie = 3;
cierre_cem.ClearColorFilter();
cierre_can.ClearColorFilter();
cierre_mad.SetColorFilter(Color.Argb(255, 255, 255, 255));
cierra_lad.ClearColorFilter();
}
void cierra_lad_OnClick(object sender, EventArgs eventArgs)
{
datos.cie = 2;
cierre_cem.ClearColorFilter();
cierre_can.ClearColorFilter();
cierre_mad.ClearColorFilter();
cierra_lad.SetColorFilter(Color.Argb(255, 255, 255, 255));
}
#endregion
#region losas
void losa_m_OnClick(object sender, EventArgs eventArgs)
{
datos.mat = 1;
losa_m.SetColorFilter(Color.Argb(255, 255, 255, 255));
losa_c.ClearColorFilter();
losa_h.ClearColorFilter();
losa_p.ClearColorFilter();
}
void losa_c_OnClick(object sender, EventArgs eventArgs)
{
datos.mat = 2;
losa_m.ClearColorFilter();
losa_c.SetColorFilter(Color.Argb(255, 255, 255, 255));
losa_h.ClearColorFilter();
losa_p.ClearColorFilter();
}
void losa_h_OnClick(object sender, EventArgs eventArgs)
{
datos.mat = 3;
losa_m.ClearColorFilter();
losa_c.ClearColorFilter();
losa_h.SetColorFilter(Color.Argb(255, 255, 255, 255));
losa_p.ClearColorFilter();
}
void losa_p_OnClick(object sender, EventArgs eventArgs)
{
datos.mat = 4;
losa_m.ClearColorFilter();
losa_c.ClearColorFilter();
losa_h.ClearColorFilter();
losa_p.SetColorFilter(Color.Argb(255, 255, 255, 255));
}
#endregion
[Java.Interop.Export("atras")]
public void atras(View view)
{
StartActivity(typeof(introAct));
Finish();
}
[Java.Interop.Export("siguiente")]
public void siguiente(View view)
{
if (FindViewById<ToggleButton>(Resource.Id.toggleAgua).Checked)
datos.agu = 0;
else
datos.agu = 1;
if (FindViewById<ToggleButton>(Resource.Id.toggleMosc).Checked)
datos.mos = 0;
else
datos.mos = 1;
if (FindViewById<ToggleButton>(Resource.Id.toggleOlor).Checked)
datos.mos = 0;
else
datos.mos = 1;
if (FindViewById<ToggleButton>(Resource.Id.toggleOlor).Checked)
datos.olo = 0;
else
datos.olo = 1;
if (FindViewById<ToggleButton>(Resource.Id.togglePriv).Checked)
datos.pri = 0;
else
datos.pri = 1;
if (FindViewById<ToggleButton>(Resource.Id.toggleVent).Checked)
datos.ven = 0;
else
datos.ven = 1;
var activity = new Intent(this, typeof(resumAct));
activity.PutExtra("encuesta", JsonConvert.SerializeObject(datos));
StartActivity(activity);
}
}
}<file_sep>/Ongawa/Servicios/Persistencia.cs
using Android.Content;
using Android.Preferences;
using Newtonsoft.Json;
using Ongawa.Clases;
using System.Collections.Generic;
namespace Ongawa.Servicios
{
class Persistencia
{
ISharedPreferences prefs;
ISharedPreferencesEditor editor;
public Persistencia(Context cont)
{
prefs = PreferenceManager.GetDefaultSharedPreferences(cont);
editor = prefs.Edit();
}
public void store(encuesta_raw datos)
{
string raw = prefs.GetString("datos", null);
List<encuesta_raw> lista;
if (raw != null)
{
lista = JsonConvert.DeserializeObject<List<encuesta_raw>>(raw);
lista.Add(datos);
}
else
{
lista = new List<encuesta_raw>();
lista.Add(datos);
}
string raw2 = JsonConvert.SerializeObject(lista);
editor.PutString("datos", raw2);
editor.Commit();
}
public List<encuesta_raw> recover()
{
string raw = prefs.GetString("datos", null);
List<encuesta_raw> lista;
if (raw == null)
lista = new List<encuesta_raw>();
else
lista = JsonConvert.DeserializeObject<List<encuesta_raw>>(raw);
return lista;
}
public void storeKey(string key)
{
editor.PutString("login", key);
editor.Commit();
}
public bool checkKey()
{
string raw = prefs.GetString("login", null);
if (raw == null)
return false;
else
return true;
}
public void clearKey()
{
editor.PutString("login", null);
editor.Commit();
}
}
}<file_sep>/Ongawa/Pantallas/histoAct.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Ongawa.Clases;
using Ongawa.Servicios;
namespace Ongawa.Pantallas
{
[Activity(Label = "histoAct")]
public class histoAct : Activity
{
List<encuesta_raw> datos;
ListView lista;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Historico);
Persistencia servicio = new Persistencia(this);
datos = servicio.recover();
if (datos.Count == 0)
{
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.SetTitle("ERROR");
dialog.SetMessage("No hay datos almacenados");
dialog.SetNeutralButton("ACEPTAR", (s, EventArgs) => { Finish(); });
dialog.Show();
}
else
{
lista = FindViewById<ListView>(Resource.Id.listHist);
lista.ItemClick += OnListItemClick;
//lista.Adapter = new ItemsAdapterList(this, datos);
}
}
void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
var activity = new Intent(this, typeof(resumAct));
//activity.PutExtra("lista", datos[e.Position].getList());
StartActivity(activity);
}
}
}
|
3e5a155ab8d250c1baa32c8900e2485b0bff9f30
|
[
"C#"
] | 9
|
C#
|
mulflar/Ongawa_app
|
02183ead406c5c7ae2460fdc83f5548c0372f25b
|
ac6918b4d7397ac3acb1bde4b54f9cef158d982b
|
refs/heads/main
|
<repo_name>theagoliveira/java-beginners-guide<file_sep>/chapter10/c10_st7/src/CopyFileConv.java
/*
* 7. Write a program that copies a text file. In the process, have it convert all spaces into
* hyphens. Use the byte stream file classes. Use the traditional approach to closing a file by
* explicitly calling close().
*/
import java.io.*;
public class CopyFileConv {
public static void main(String[] args) {
int i;
FileInputStream fin = null;
FileOutputStream fout = null;
// First, make sure that both files have been specified.
if (args.length != 2) {
System.out.println("Usage: CopyFileConv from to");
return;
}
// Copy a File.
try {
// Attempt to open the files.
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
do {
i = fin.read();
if (i != -1) {
if (i == (int) ' ')
fout.write((int) '-');
else
fout.write(i);
}
} while (i != -1);
} catch (IOException e) {
System.out.println("I/O Error: " + e);
} finally {
try {
if (fin != null)
fin.close();
} catch (IOException e) {
System.out.println("Error Closing Input File");
}
try {
if (fout != null)
fout.close();
} catch (IOException e) {
System.out.println("Error Closing Output File");
}
}
}
}
<file_sep>/chapter14/c14_st9/src/LambdaArgumentDemo.java
interface StringFunc {
String func(String str);
}
public class LambdaArgumentDemo {
// This method has a functional interface as the type of its
// first parameter. Thus, it can be passed a reference to any
// instance of that interface, including an instance created
// by a lambda expression. The second parameter specifies the
// string to operate on.
static String changeStr(StringFunc sf, String s) {
return sf.func(s);
}
public static void main(String[] args) {
String inStr = "Lambda Expressions Expand Java";
String outStr;
System.out.println("Here is input string: " + inStr);
// Define a lambda expression that reverses the contents
// of a string and assign it to a String Func reference variable.
StringFunc removeSpaces = (str) -> {
String result = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ' ')
result += str.charAt(i);
}
return result;
};
outStr = changeStr(removeSpaces, inStr);
System.out.println("The string with spaces removed: " + outStr);
}
}
<file_sep>/chapter6/c6_st13/src/VarArgsSum.java
/*
* 13. Create a varargs method called sum( ) that sums the int values passed to it. Have it return
* the result. Demonstrate its use.
*/
class ArrayUtils {
private ArrayUtils() {
throw new IllegalStateException("Utility class");
}
static int sum(int... arr) {
int result = 0;
for (int i : arr) {
result += i;
}
return result;
}
}
class VarArgsSum {
public static void main(String[] args) {
System.out.println("ArrayUtils.sum() = " + ArrayUtils.sum());
System.out.println("ArrayUtils.sum(1) = " + ArrayUtils.sum(1));
System.out.println("ArrayUtils.sum(1, 2) = " + ArrayUtils.sum(1, 2));
System.out.println("ArrayUtils.sum(1, 2, 3) = " + ArrayUtils.sum(1, 2, 3));
System.out.println("ArrayUtils.sum(1, 2, 3, 4) = " + ArrayUtils.sum(1, 2, 3, 4));
}
}
<file_sep>/chapter6/c6_st6/src/RecBackPrint.java
/*
* 6. Write a recursive method that displays the contents of a string backwards.
*/
class Backwards {
String s;
int length;
Backwards(String str) {
s = str;
length = str.length();
}
void printBackwards(int end) {
if (end == -1) {
System.out.println();
return;
}
System.out.print(s.charAt(end));
printBackwards(end - 1);
}
}
class RecBackPrint {
public static void main(String[] args) {
var str1 = "thiago";
var str2 = new Backwards("oliveira");
printBackwards(str1, str1.length() - 1);
str2.printBackwards(str2.length - 1);
}
static void printBackwards(String s, int end) {
if (end == -1) {
System.out.println();
return;
}
System.out.print(s.charAt(end));
printBackwards(s, end - 1);
}
}
<file_sep>/chapter15/c15_p2/src/mymodapp/appsrc/userfuncs/userfuncs/binaryfuncs/BinFuncProvider.java
// This interface defines the form of a service provider that
// obtains BinaryFunc instances.
package userfuncs.binaryfuncs;
import userfuncs.binaryfuncs.BinaryFunc;
public interface BinFuncProvider {
// Obtain a BinaryFunc.
public BinaryFunc get();
}
<file_sep>/chapter15/tt151/src/mymodapp/appsrc/appfuncs/module-info.java
// Module definion for appfuncs.
module appfuncs {
// Exports the package appfuncs.simplefuncs.
exports appfuncs.simplefuncs;
// Requires appsupport and makes it transitive.
requires transitive appsupport;
}
<file_sep>/chapter12/c12_st3/src/ShowValues.java
/*
* 3. Given the following enumeration, write a program that uses values( ) to show a list of the
* constants and their ordinal values.
*/
enum Tools {
SCREWDRIVER, WRENCH, HAMMER, PLIERS
}
public class ShowValues {
public static void main(String[] args) {
for (Tools t : Tools.values()) {
System.out.println(t.ordinal() + " - " + t);
}
}
}
<file_sep>/chapter14/c14_st6/src/MyTestDemo.java
/*
* 6. Create a functional interface that can support the lambda expression you created in question
* 5. Call the interface MyTest and its abstract method testing().
*/
interface MyTest {
boolean testing(int n);
}
public class MyTestDemo {
public static void main(String[] args) {
MyTest between10and20 = (n) -> (n >= 10) && (n <= 20);
int x = 14;
if (between10and20.testing(x))
System.out.printf("%d is between 10 and 20%n", x);
x = 24;
if (!between10and20.testing(x))
System.out.printf("%d is not between 10 and 20%n", x);
}
}
<file_sep>/chapter10/tt101/src/CompFiles.java
/*
* Try This 10-1
*
* Compare two files.
*
* To use this program, specify the names of the files to be compared on the command line.
*
* java CompFile FIRST.TXT SECOND.TXT
*/
import java.io.*;
public class CompFiles {
public static void main(String[] args) {
int i = 0;
int j = 0;
int ln = 1;
int col = 1;
// First make sure that both files have been specified.
if (args.length != 2) {
System.out.println("Usage: CompFiles f1 f2");
return;
}
// Compare the files.
try (var f1 = new FileInputStream(args[0]); var f2 = new FileInputStream(args[1])) {
do {
i = f1.read();
j = f2.read();
if ((i >= 65) && (i <= 90))
i += 32;
if ((j >= 65) && (j <= 90))
j += 32;
if (i != j)
break;
col++;
if (i == 10) {
ln++;
col = 1;
}
} while (i != -1 && j != -1);
if (i != j)
System.out.printf("Files differ in line %d, column %d.%n", ln, col);
else
System.out.println("Files are the same.");
} catch (IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
<file_sep>/chapter5/c5_st13/src/MinMaxForEach.java
/*
* 13. Rewrite the MinMax class shown earlier in this chapter so that it uses a for-each style for
* loop.
*
*/
class MinMaxForEach {
public static void main(String[] args) {
int nums[] = new int[10];
int min, max;
nums[0] = 99;
nums[1] = -10;
nums[2] = 100123;
nums[3] = 18;
nums[4] = -978;
nums[5] = 5623;
nums[6] = 463;
nums[7] = -9;
nums[8] = 287;
nums[9] = 49;
min = max = nums[0];
for (int i : nums) {
if (i < min)
min = i;
if (i > max)
max = i;
}
System.out.println("min and max: " + min + " " + max);
}
}
<file_sep>/chapter15/c15_p2/src/mymodapp/appsrc/appstart/module-info.java
// Module definition for the main application module.
// It now uses BinFuncProvider.
module appstart {
// Requires the modules appfuncs and userfuncs.
requires appfuncs;
requires userfuncs;
// appstart now uses BinFuncProvider.
uses userfuncs.binaryfuncs.BinFuncProvider;
}
<file_sep>/chapter15/c15_p2/src/mymodapp/appsrc/userfuncs/userfuncs/binaryfuncs/BinaryFunc.java
// This interface defines a function that takes two int
// arguments and return an int result. Thus, it can
// describe any binary operation on two ints that
// returns an int.
package userfuncs.binaryfuncs;
public interface BinaryFunc {
// Obtain the name of the function.
public String getName();
// This is de function to perform. It will be
// provided by specific implementations.
public int func(int a, int b);
}
<file_sep>/chapter9/c9_p5/src/ExcDemo3.java
// Handle error gracefully and continue.
class ExcDemo3 {
public static void main(String[] args) {
int[] numer = {4, 8, 16, 32, 64, 128};
int[] denom = {2, 0, 4, 4, 0, 8};
for (int i = 0; i < numer.length; i++) {
try {
System.out.printf("%d / %d is %d%n", numer[i], denom[i], numer[i] / denom[i]);
} catch (ArithmeticException e) {
// catch the exception
System.out.println("Can't divide by Zero!");
}
}
}
}
<file_sep>/chapter1/c1_st10/src/InchesToMeters.java
/*
* Chapter 1 Self Test 10
*
* Adapt Try This 1-2 so that it prints a conversion table of inches to meters. Display 12 feet of
* conversions, inch by inch. Output a blank line every 12 inches. (One meter equals approximately
* 39.37 inches.)
*
*/
public class InchesToMeters {
public static void main(String[] args) {
double inches, meters;
int counter;
counter = 0;
for (inches = 1; inches <= 144; inches++) {
meters = inches / 39.37; // convert to meters
System.out.println(inches + " inches is " + meters + " meters.");
counter++;
// every 12th inch, print a blank line
if (counter == 12) {
System.out.println();
counter = 0; // reset the line counter
}
}
}
}
<file_sep>/chapter16/c16_st16/src/ListDemo.java
// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ListDemo implements ListSelectionListener {
JList<String> jlst;
JLabel jlab;
JScrollPane jscrlp;
// Create an array of names.
String[] names = {"Sherry", "Jon", "Rachel", "Sasha", "Josselyn", "Randy", "Tom", "Mary", "Ken",
"Andrew", "Matt", "Todd"};
ListDemo() {
// Create a new JFrame container.
var jfrm = new JFrame("JList Demo");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());
// Give the frame an initial size.
jfrm.setSize(260, 300);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a JList.
jlst = new JList<String>(names);
// Set the list selection mode to single-selection.
jlst.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// Add list to a scroll pane.
jscrlp = new JScrollPane(jlst);
// Set the preferred size of the scroll pane.
jscrlp.setPreferredSize(new Dimension(120, 90));
// Make a label that displays the selection.
jlab = new JLabel("Please choose one or more names");
// Add list selection handler.
jlst.addListSelectionListener(this);
// Add the components to the content pane.
jfrm.add(jscrlp);
jfrm.add(jlab);
// Display the frame
jfrm.setVisible(true);
}
// Handle list selection events.
public void valueChanged(ListSelectionEvent le) {
// Get the index of the changed item.
int[] indices = jlst.getSelectedIndices();
// Display selection, if item was selected.
if (indices.length != 0) {
String result = "<html>Current selection:<ul>";
for (int i = 0; i < indices.length; i++) {
result += ("<li>" + names[indices[i]] + "</li>");
}
result += "</ul></html>";
jlab.setText(result);
} else // Otherwise, reprompt.
jlab.setText("Please choose one or more names");
}
public static void main(String[] args) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ListDemo();
}
});
}
}
<file_sep>/chapter14/c14_st8/src/GenericFunctionalInterface.java
/*
* 8. Create a generic functional interface called MyFunc<T>. Call its abstract method func(). Have
* func() return a reference of type T. Have it take a parameter of type T. (Thus, MyFunc will be a
* generic version of NumericFunc shown in the chapter.) Demonstrate its use by rewriting your
* answer to question 7 so it uses MyFunc<T> rather than NumericFunc.
*/
interface MyFunc<T> {
T func(T n);
}
public class GenericFunctionalInterface {
public static void main(String[] args) {
MyFunc<Integer> factorial = n -> {
int result = 1;
for (int i = 2; i <= n; result *= i++);
return result;
};
for (int i = 1; i <= 10; i++) {
System.out.printf("The factorial of %d is %d%n", i, factorial.func(i));
}
}
}
<file_sep>/chapter13/tt131/src/GenQDemo.java
import java.util.*;
/*
* Try This 13-1
*
* Demonstrate a generic queue class.
*/
class GenQDemo {
public static void main(String[] args) {
// Create an integer queue.
Integer[] iStore = new Integer[10];
var q = new GenQueue<Integer>(iStore);
Integer iVal;
System.out.println("Demonstrate a queue of Integers. (1)");
try {
for (int i = 0; i < 5; i++) {
System.out.println("Adding " + i + " to q.");
q.put(i); // add integer value to q
}
} catch (QueueFullException e) {
System.out.println(e);
}
System.out.println();
try {
for (int i = 0; i < 5; i++) {
System.out.print("Getting next Integer from q: ");
iVal = q.get();
System.out.println(iVal);
}
} catch (QueueEmptyException e) {
System.out.println(e);
}
System.out.println();
// Create an double queue.
Double[] dStore = new Double[10];
var q2 = new GenQueue<Double>(dStore);
Double dVal;
System.out.println("Demonstrate a queue of Doubles.");
try {
for (int i = 0; i < 5; i++) {
System.out.println("Adding " + ((double) i / 2) + " to q2.");
q2.put((double) i / 2); // add integer value to q2
}
} catch (QueueFullException e) {
System.out.println(e);
}
System.out.println();
try {
for (int i = 0; i < 5; i++) {
System.out.print("Getting next Double from q2: ");
dVal = q2.get();
System.out.println(dVal);
}
} catch (QueueEmptyException e) {
System.out.println(e);
}
System.out.println();
}
}
<file_sep>/chapter3/c3_st9/src/ForProgression.java
/*
* 9. The iteration expression in a for loop need not always alter the loop control variable by a
* fixed amount. Instead, the loop control variable can change in any arbitrary way. Using this
* concept, write a program that uses a for loop to generate and display the progression 1, 2, 4, 8,
* 16, 32, and so on.
*/
public class ForProgression {
public static void main(String[] args) {
int i;
for (i = 1; i < 32; i *= 2) {
System.out.print(i + ", ");
}
System.out.print(i);
System.out.println();
}
}
<file_sep>/chapter15/tt151/src/mymodapp/appsrc/appsupport/module-info.java
// Module definition for appsupport.
module appsupport {
exports appsupport.supportfuncs;
}
<file_sep>/chapter9/c9_st10/src/StackDemo.java
/*
* 3. The complement of a queue is a stack. It uses first-in, last-out accessing and is often
* likened to a stack of plates. The first plate push on the table is the last plate used. Create a
* stack class called Stack that can hold characters. Call the methods that access the stack push()
* and pop(). Allow the user to specify the size of the stack when it is created. Keep all other
* members of the Stack class private. (Hint: You can use the Stack class as a model; just change
* the way the data is accessed.)
*
*/
// A queue class for characters.
class Stack {
private char[] s; // this array holds the queue
private int top; // the top index
// Construct an empty Stack given its size.
Stack(int size) {
s = new char[size];
top = 0;
}
// Construct a Stack from a Stack.
Stack(Stack ob) {
top = ob.top;
s = new char[ob.s.length];
// copy elements
for (int i = 0; i < top; i++)
s[i] = ob.s[i];
}
// Construct a Stack with initial values.
Stack(char[] a) throws StackFullException {
top = 0;
s = new char[a.length];
for (int i = 0; i < a.length; i++)
push(a[i]);
}
// Put a character into the stack.
void push(char ch) throws StackFullException {
if (top == s.length) {
throw new StackFullException(s.length);
}
s[top++] = ch;
}
// Get a character from the stack.
char pop() throws StackEmptyException {
if (top == 0) {
throw new StackEmptyException();
}
return s[--top];
}
void contents() {
for (int i = top - 1; i >= 0; i--) {
System.out.println(s[i]);
}
}
}
// Demonstrate the Stack class.
class StackDemo {
public static void main(String[] args) {
// construct 10-element empty queue
var s1 = new Stack(10);
try {
// push some characters into s1
for (int i = 0; i < 11; i++) {
System.out.printf("Pushing %c into Stack q1... ", (char) ('A' + i));
s1.push((char) ('A' + i));
System.out.println("OK!");
}
} catch (StackFullException e) {
System.out.println(e);
}
try {
// push some characters into s1
for (int i = 0; i < 11; i++) {
System.out.printf("Getting a character from Stack q1: ");
char c = s1.pop();
System.out.printf("%c ...", c);
System.out.println("OK!");
}
} catch (StackEmptyException e) {
System.out.println(e);
}
}
}
<file_sep>/README.md
# Java: A Beginner's Guide
Exercises from the book **Java: A Beginner's Guide, Eighth Edition** by <NAME>
<file_sep>/chapter13/tt131/src/GenCircQDemo.java
/*
* Try This 13-1
*
* Demonstrate a generic circular queue class.
*/
class GenCircQDemo {
public static void main(String[] args) {
// Create an integer queue.
Integer[] iStore = new Integer[11];
var q = new GenCircularQueue<Integer>(iStore);
Integer iVal;
System.out.println("Demonstrate a queue of Integers. (1)");
try {
for (int i = 0; i < 5; i++) {
System.out.println("Adding " + i + " to q.");
q.put(i); // add integer value to q
}
} catch (QueueFullException e) {
System.out.println(e);
}
System.out.println();
try {
for (int i = 0; i < 5; i++) {
System.out.print("Getting next Integer from q: ");
iVal = q.get();
System.out.println(iVal);
}
} catch (QueueEmptyException e) {
System.out.println(e);
}
System.out.println();
System.out.println("Demonstrate a queue of Integers. (2)");
try {
for (int i = 0; i < 5; i++) {
System.out.println("Adding " + (2 * i) + " to q.");
q.put(2 * i); // add integer value to q
}
} catch (QueueFullException e) {
System.out.println(e);
}
System.out.println();
try {
for (int i = 0; i < 5; i++) {
System.out.print("Getting next Integer from q: ");
iVal = q.get();
System.out.println(iVal);
}
} catch (QueueEmptyException e) {
System.out.println(e);
}
System.out.println();
System.out.println("Demonstrate a queue of Integers. (3)");
try {
for (int i = 0; i < 5; i++) {
System.out.println("Adding " + (3 * i) + " to q.");
q.put(3 * i); // add integer value to q
}
} catch (QueueFullException e) {
System.out.println(e);
}
System.out.println();
try {
for (int i = 0; i < 5; i++) {
System.out.print("Getting next Integer from q: ");
iVal = q.get();
System.out.println(iVal);
}
} catch (QueueEmptyException e) {
System.out.println(e);
}
System.out.println();
}
}
|
d295f598ad9cf3e3b0f478c09bc2461865fd7799
|
[
"Markdown",
"Java"
] | 22
|
Java
|
theagoliveira/java-beginners-guide
|
eec45916fd2d5261c76bec13ffaa004451f80049
|
71286d2d5ea32991e35adc172b03694ac16c1695
|
refs/heads/main
|
<file_sep>import React from 'react';
import './Sidebar.css';
function Sidebar() {
return(
<div class="sidebar">
<center class="profile">
<img alt='profile pic' src="https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png" />
<p>Your Name</p>
</center>
<li class="item">
<a href="#" class="menu-btn">
<i class="fas fa-desktop"></i><span>Wall Of Fame</span>
</a>
</li>
<li class="item" id="profile">
<a href="#profile" class="menu-btn">
<i class="fas fa-user"></i><span>Profile</span>
</a>
</li>
<li class="item" id="setting">
<a href="#setting" class="menu-btn">
<i class="fas fa-cog"></i
><span>Setting<i class="fas fa-chevron-down drop-down"></i></span>
</a>
<div class="sub-menu">
<a href="#"><i class="fas fa-lock"></i> <span>Password</span></a>
</div>
</li>
<li class="item">
<a href="#" class="menu-btn">
<i class="fas fa-info-circle"></i><span>About</span>
</a>
</li>
</div>
);
}
export default Sidebar;<file_sep>import React from 'react';
import '../App.css';
export const Navbardata=[
{
title:'Wall of Fame',
icon:<i class="fas fa-desktop"></i>,
link: '/WoF'
},
{
title:'Profile',
icon:<i class="fas fa-user"></i>,
link: '/Profile'
},
{
title:'Change Password',
icon:<i class="fas fa-lock"></i>,
link: '/ChngPWd'
},
{
title:'About',
icon:<i class="fas fa-info-circle"></i>,
link: '/About'
},
]<file_sep>import { render } from '@testing-library/react';
import React from 'react';
import './Header.css';
function Header() {
return(
<div class="header">
<div class="header-menu">
<div class="title">Rewards and Recognition</div>
<button className='btn1'><i class="fas fa-bars"></i></button>
<ul>
<li>
<a href="Logo"> <i class="fas fa-power-off"></i></a>
</li>
</ul>
</div>
</div>
);
}
export default Header;<file_sep>import { render } from '@testing-library/react';
import React,{useState} from 'react';
import '../App.css';
import {Navbardata} from './Navbardata';
function Navbar(){
return( <div className="sidebarr">
<img id="image" alt="profilepic" src="https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png"></img>
<p id="empname"><NAME></p>
<ul className="navbarlist" >
{Navbardata.map((val,key)=>{
return(
<li className="row" key={key}
id={window.location.pathname==val.link? "active":""}
onClick={()=>{
window.location.pathname=val.link
}} >
{""}
<div id='icon'>{val.icon}</div>{""}
<div id='title'>{val.title}</div></li>
);
})}
</ul>
</div>
);}
export default Navbar
|
349f2030403b531f43d5a6d6a8eefab7b4661abb
|
[
"JavaScript"
] | 4
|
JavaScript
|
nineleaps709/9leaps
|
cbbcd4979213b77482ec0617d9f7d00a0ce9f00d
|
027554ff6499f91ae1a8ee9b8e508a93e0d07cd1
|
refs/heads/master
|
<repo_name>Lybecker/ServiceFabricEndpointLoadBalancing<file_sep>/WebService/Controllers/ServiceHealthProbeController.cs
using Microsoft.AspNetCore.Mvc;
namespace WebService.Controllers
{
[Route("api/[controller]")]
public class ServiceHealthProbeController : Controller
{
private readonly Model.ServiceHealthStatus _serviceHealthProbe;
public ServiceHealthProbeController(Model.ServiceHealthStatus serviceHealthProbe)
{
_serviceHealthProbe = serviceHealthProbe;
}
[HttpGet]
public IActionResult Get()
{
if (_serviceHealthProbe.IsShuttingDown == false)
return Ok("Everything is running smooth");
else
return StatusCode(503, "Service terminating - stop sending requests");
}
}
}<file_sep>/WebService/Model/ServiceHealthProbe.cs
namespace WebService.Model
{
public class ServiceHealthStatus
{
public ServiceHealthStatus()
{
IsShuttingDown = false;
}
/// <summary>
/// The service is shutting down and will soon stop service requests.
/// </summary>
public bool IsShuttingDown { get; set; }
}
}
|
fba0dac750da884515bcb3f622e1b40f79d85b20
|
[
"C#"
] | 2
|
C#
|
Lybecker/ServiceFabricEndpointLoadBalancing
|
a373ef3812ccf89dfb347f5959150bbd86af56d9
|
1cb315571fb2d8e333a746a197deeb34a6aae3ba
|
refs/heads/main
|
<file_sep><?php
include("db.php");
$db=$conn;
$name = $_POST['user'];
$id = $_POST['id'];
$query="UPDATE names SET names = '$name' WHERE idnames ='$id'";
mysqli_query($db, $query);
header('Location: /');
?><file_sep><?php include 'db.php';?>
<?php
// Get the connection and store it in a variable
include("db.php");
$db=$conn;
// FIRST FUNCTION ( To get the Data from the database and make it available)
function fetch_data(){
//create a global variable to import the connection in the function
global $db;
//create your query string
$query="SELECT * from names ORDER BY idnames DESC";
//mix your your dabase variable with your query string
$mixage=mysqli_query($db, $query);
// Specifies what type of array that should be produced as output from the mixage.
$row= mysqli_fetch_all($mixage, MYSQLI_BOTH);
// Return the result so it can be use in other function.
return $row;
}
/*CONNECT 2 FUNCTIONS */
// Store the first function in a variable.
$fetchData= fetch_data();
//Pass the first function in the second function as argument using the variable where it store.
show_data($fetchData);
// SECOND FUNCTION ( To create the html code using loop)
function show_data($fetchData){
// html for the table header
echo '<table class="table">
<thead>
<tr>
<th scope="col">S.N</th>
<th scope="col">Name</th>
<th scope="col">Delete</th>
<th scope="col">Update</th>
</tr>
</thead>';
// html for the table body
foreach($fetchData as $data){
echo "<tr>
<td scope='row'>".$data['idnames']."</td>
<td>".$data['names']."</td>
<td><button><a href='php/deleted.php?del=".$data['idnames']."'>Delete</a></button></td>
<td><button onclick='pickup(".$data['idnames'].")'>Update</button></td>
</tr>";
}
}
?><file_sep><?php
include("db.php");
$db=$conn;
$id = $_POST['id'];
$query="SELECT * from names WHERE idnames=$id";
$mixage=mysqli_query($db, $query);
$row= mysqli_fetch_all($mixage, MYSQLI_ASSOC);
foreach($row as $data){
echo '
<div class="pickBox">
<form action="php/update.php" method="post">
<input style="width: 300px" type="text" name="user" value="'.$data['names'].'" >
<input type="hidden" name="id" value='.$data['idnames'].' >
<button type="submit">Change</button>
</form>
</div>
';
}
?><file_sep># PHP-CRUD
Simple database manupilations
<file_sep><?php
include("db.php");
$db=$conn;
$del = $_GET['del'];
$query="DELETE FROM names WHERE idnames =$del";
mysqli_query($db, $query);
header('Location: /');
?><file_sep><?php
include("db.php");
$db=$conn;
$name = $_POST['user'];
$query="INSERT INTO names (names) VALUES('$name')";
mysqli_query($db, $query);
header('Location: /');
?>
|
2774d348dd21e7d12bc624911e3d703e23f1f7b5
|
[
"Markdown",
"PHP"
] | 6
|
PHP
|
roberson509/PHP-CRUD-
|
c5ca6e30e3e0f9e44a575cab2f5ae394260e3245
|
40a305046266a677111f29ba42f9d508d8994560
|
refs/heads/master
|
<file_sep>package com.evry.SpringBoot.dao;
import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.evry.SpringBoot.entity.Book;
@Repository
public class BookDAOHibernateImpl implements BookDAO {
// define field for entitymanager
private EntityManager entityManager;
// set up constructor injection
@Autowired
public BookDAOHibernateImpl(EntityManager theEntityManager) {
entityManager = theEntityManager;
}
@Override
public List<Book> findAll() {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// create a query
Query<Book> theQuery =
currentSession.createQuery("from Book", Book.class);
// execute query and get result list
List<Book> books = theQuery.getResultList();
// return the results
return books;
}
@Override
public Book findById(int theId) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// get the book
Book theBook =
currentSession.get(Book.class, theId);
// return the employee
return theBook;
}
@Override
public void save(Book theBook) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// save Book
currentSession.saveOrUpdate(theBook);
}
@Override
public void deleteById(int theId) {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// delete object with primary key
Query theQuery =
currentSession.createQuery(
"delete from Book where id=:BookId");
theQuery.setParameter("BookId", theId);
theQuery.executeUpdate();
}
}
|
d93351c38ed91c10f3ffdaeb27062c35f7611ac1
|
[
"Java"
] | 1
|
Java
|
evrytrainingbatch01/RenukaPrasadaBooksAPI
|
0ed8eabef1ff05e46f41c6ba68c5b224f4b512e0
|
68f5f64bad063f99c008118fe63a0afb2da8a416
|
refs/heads/master
|
<file_sep># uTweetdeck
### A Chrome Extension to remove profile picutres and decluster the Tweetdeck UI called [uTweetdeck](https://chrome.google.com/webstore/detail/utweetdeck/mamdemofgfmcdefkmolnnenmhmecpgbo).
The actual code can be found in [this repo](https://github.com/DeBraid/js-snippets/blob/master/cleaner-tweetdeck.js). <file_sep>(function initCleanerTweetdeckIIFE () {
var s_ajaxListener = new Object();
s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;
s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;
// runs each XHR events
s_ajaxListener.callback = function() {
var tweet = $('.tweet');
if (tweet.length > 0) {
console.log('uTweetdeck: Swabbing the decks!');
removeProfilePics();
shrinkImages();
makeHomeColumnWider();
} else {
console.log('uTweetdeck: Wait for it...');
return;
};
}
function makeHomeColumnWider () {
var homeInput = $('#home-column-width');
var newHtml = '<input type="text" placeholder="400" id="home-column-width" style="width: 45px; float: right; margin-top: 1em;">' +
'<span class="attribution txt-mute txt-sub-antialiased pull-right" style="margin-right: 0.5em;">Width</span>';
if (homeInput.length == 0) {
$('.column-type-home h1').append(newHtml);
};
var newWidth = homeInput.val() || '400',
width = newWidth + 'px';
$('.column-type-home').css({
width : width
});
}
function shrinkImages () {
var pics = $('.js-column .tweet .js-media-preview-container');
pics.css({
'max-height' : '25px',
overflow : 'hidden'
});
}
function removeProfilePics () {
$('.tweet-avatar.avatar.pull-right').remove();
$('.tweet').css({ 'padding-left': '5px' });
}
XMLHttpRequest.prototype.open = function(a, b) {
if (!a) var a = '';
if (!b) var b = '';
s_ajaxListener.tempOpen.apply(this, arguments);
s_ajaxListener.method = a;
s_ajaxListener.url = b;
if (a.toLowerCase() == 'get') {
s_ajaxListener.data = b.split('?');
s_ajaxListener.data = s_ajaxListener.data[1];
}
}
XMLHttpRequest.prototype.send = function(a, b) {
if (!a) var a = '';
if (!b) var b = '';
s_ajaxListener.tempSend.apply(this, arguments);
if (s_ajaxListener.method.toLowerCase() == 'post') s_ajaxListener.data = a;
s_ajaxListener.callback();
}
})();
|
3022a1c0bf20b3883ef91847943e88ec131ace66
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
DeBraid/uTweetdeck
|
647b798c11d873736f1b991c4ce5c35539b70127
|
25e3584579e8d01788dc505d8485e046e9501996
|
refs/heads/master
|
<file_sep># A collection of random munin plugins.
<file_sep>#!/usr/bin/python
# Munin plugin to monitor values of all smarthome items following a naming pattern.
# Items to be monitored must have "sqlite = yes" in their item definition.
# The first level item name is used for munin.
import os
import sqlite3
from munin import MuninPlugin
# Path to the smarthome sqlite db file.
PATH = '/opt/smarthome/var/db/smarthome.db'
# Temperature ranges for Warning and critical messages.
WARNING = '10:30'
CRITICAL = '5:40'
# SQL "like" pattern to select the items to monitor.
ITEM_PATTERN = '%temperatur_ist'
class TemperaturesPlugin(MuninPlugin):
title = "Temperatures"
args = "--base 1000 -l 0"
scale = False
category = "environment"
@property
def fields(self):
conf = []
for row in TemperaturesPlugin.dbfetch_('SELECT DISTINCT item from history WHERE item LIKE \'' + ITEM_PATTERN + '\';'):
room = row[0].split('.')[0]
conf.append([room, dict(
label = room.capitalize(),
info = 'Temperature in room \"' + room + '\".',
warning = str(WARNING),
critical = str(CRITICAL))])
return conf
def execute(self):
for row in TemperaturesPlugin.dbfetch_('SELECT max(time), item, avg from history WHERE item LIKE \'' + ITEM_PATTERN + '\' GROUP BY item;'):
print '{room}.value {temperature:.1f}'.format(room = row[1].split('.')[0], temperature = row[2])
@staticmethod
def dbfetch_(query):
db_connection = sqlite3.connect(PATH)
db_cursor = db_connection.cursor()
return db_cursor.execute(query).fetchall()
if __name__ == "__main__":
TemperaturesPlugin().run()
|
421f163ed79da97cbd852b8d62e5b96f763cc2c9
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
michos-conradt/munin-plugins
|
b29c440c03dcd8f3c0d0677fcf7aacfaa39dea38
|
0f704d1a465c43d2019de43ba3a0b5e0eb32b7c8
|
refs/heads/master
|
<repo_name>glespinosa/react-task-tracker<file_sep>/src/reducer/TaskReducer.js
export const ACTIONS = {
DELETE_TASK: 'DELETE_TASK',
TOGGLE_REMINDER: 'TOGGLE_REMINDER',
ADD_TASK: 'ADD_TASK',
RETRIEVE_TASKS: 'RETRIEVE_TASKS',
ALL_TASKS: 'ALL_TASKS',
}
export const reducer = (tasks, { type, payload }) => {
switch (type) {
case ACTIONS.DELETE_TASK:
return tasks.filter((task) => task.id !== payload.id)
case ACTIONS.ADD_TASK:
return [...tasks, payload]
case ACTIONS.TOGGLE_REMINDER:
const updTasks = tasks.map((task) =>
task.id === payload.id
? { ...task, reminder: !task.reminder }
: task
)
return updTasks
case ACTIONS.RETRIEVE_TASKS:
return payload
case ACTIONS.ALL_TASKS:
return tasks
default:
return tasks
}
}
<file_sep>/src/components/Example.js
import React from 'react'
function Example({ dispatch }) {
return <button onClick={dispatch}>ADD</button>
}
export default Example
<file_sep>/src/App.js
import { useState, useEffect, useContext, useReducer } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Header from './components/Header'
import Tasks from './components/Tasks'
import AddTask from './components/AddTask'
import About from './components/About'
import Footer from './components/Footer'
import { TaskContext } from './context/TaskContext'
function App() {
const [tasks, { addTask, retrieveTasks }] = useContext(TaskContext)
const [showAddTask, setShowAddTask] = useState(false)
useEffect(() => {
retrieveTasks()
}, [])
return (
<Router>
<div className='container'>
<Header
isShow={showAddTask}
onClick={() => setShowAddTask(!showAddTask)}
title='Task Tracker'
/>
<Route
path='/'
exact
render={(props) => (
<>
{showAddTask && <AddTask addTask={addTask} />}
{tasks.length > 0 ? (
<Tasks tasks={tasks} />
) : (
'No tasks to show'
)}
</>
)}
/>
<Route path='/about' component={About} />
<Footer />
</div>
</Router>
)
}
export default App
<file_sep>/src/components/Button.js
import React from 'react'
import PropTypes from 'prop-types'
function Button({ children, color, onClick }) {
return (
<button onClick={onClick} className='btn' style={{ background: color }}>
{children}
</button>
)
}
Button.defaultProps = {
color: 'steelblue',
}
Button.propTypes = {
color: PropTypes.string,
}
export default Button
<file_sep>/src/context/TaskContext.js
import React, { createContext, useReducer } from 'react'
import { ACTIONS, reducer } from '../reducer/TaskReducer'
export const TaskContext = createContext()
export const TaskProvider = ({ children }) => {
const initialState = []
const apiEndpoint = 'http://localhost:5000/tasks'
const [tasks, dispatch] = useReducer(reducer, initialState)
const retrieveTasks = async () => {
const res = await fetch(apiEndpoint)
const tasks = await res.json()
dispatch({ type: ACTIONS.RETRIEVE_TASKS, payload: tasks })
}
const deleteTask = async (id) => {
await fetch(`${apiEndpoint}/${id}`, {
method: 'DELETE',
})
dispatch({
type: ACTIONS.DELETE_TASK,
payload: { id },
})
}
const addTask = async (payload) => {
const response = await fetch(`${apiEndpoint}`, {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(payload),
})
const data = await response.json()
console.log(payload)
dispatch({ type: ACTIONS.ADD_TASK, payload: data })
}
const toggleReminder = async (id) => {
const taskToToggle = await fetchTask(id)
const updTask = {
...taskToToggle,
reminder: !taskToToggle.reminder,
}
const res = await fetch(apiEndpoint + `/${id}`, {
method: 'PUT',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(updTask),
})
const data = await res.json()
console.log(data)
dispatch({
type: ACTIONS.TOGGLE_REMINDER,
payload: { id },
})
}
const fetchTask = async (id) => {
const res = await fetch(apiEndpoint + `/${id}`)
const data = await res.json()
return data
}
return (
<TaskContext.Provider
value={[
tasks,
{
retrieveTasks,
deleteTask,
addTask,
toggleReminder,
},
]}
>
{children}
</TaskContext.Provider>
)
}
<file_sep>/src/components/Tasks.js
import React, { useState } from 'react'
import Task from './Task'
function Tasks({ tasks }) {
return (
<>
{tasks.map((task, index) => (
<Task key={task.id} task={task} />
))}
</>
)
}
export default Tasks
|
b72ec9e305aaf02f5ff869ee885bc6ce47db39ff
|
[
"JavaScript"
] | 6
|
JavaScript
|
glespinosa/react-task-tracker
|
9757a5ab3085cbea0f36c2a3fb95cd5663635c9e
|
ab3fd44cfdc47bbc9541f4eb68f6e88e89228118
|
refs/heads/master
|
<file_sep># Avalia-o-POO<file_sep>package avaliacao;
import java.util.LinkedList;
public class Musico extends Pessoa {
private String estiloMusical;
private LinkedList<Filme> filmes = new LinkedList<Filme>();
public String getEstiloMusical() {
return estiloMusical;
}
public void setEstiloMusical(String estiloMusical) {
this.estiloMusical = estiloMusical;
}
public LinkedList<Filme> getFilmes() {
return filmes;
}
public void setResponsaveis(LinkedList<Filme> filmes) {
this.filmes = filmes;
}
public void imprimir() {
System.out.println("Musico: " + nome + " | Data de Nascimento: " + dataNascimento + " | Estilo musical: " + estiloMusical);
}
}
|
3d9ccf58ef02a697ab3030a68b48918691c26fe1
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
carvalhojp/Avalia-o-POO
|
13d6edc2f3bd73d3182867b2cf89d014c0dce94e
|
ac21446857f068b0e7712da8e589efa92b0122b3
|
refs/heads/master
|
<file_sep># Keep Drives Alive
A little Python program to keep your external drives awake instead of falling to sleep. Wake up lazy bones!
To run the program you'll need Python installed. If you don't have it, download from http://www.python.org.
When ready add your drive letters to the "drives" array. By default there are two drives. Add a third like so:
drives = ['D', 'E', 'F']
Or just a single drive like so:
drives = ['D']
The program works by writing a file to each drive and changing the files contents at a set interval. The interval is set to 30 seconds by default. To make the interval longer or shorter, change the "sleepInterval" variable to the number of seconds you'd like to wait before writing to the drive again.
The program writes to a file titled ___kda___. It is unlikely you have this file on your drive but, if you do, you may want to update the filename to something else. Do this by changing the "fileToWrite" variable to anything you'd like.
When you're ready to go, double click on the file and a console window will pop up to run the program. When you're done, close the window.
## Please Note
This program has not been tested on a Mac. If you try it and have issues, let me know and I'll adjust to make it Mac friendly.<file_sep># NOTE - has not been tested on a Mac
# add your drive letters in this array
drives = ['D', 'E']
# the number of seconds you'd like to wait before calling the drive
sleepInterval = 30
# this is the file the program will write at ever interval
# make sure you don't have a file of the same name on your drive and,
# if you do, rename this file below. you can delete the file when
# you're done using the program
fileToWrite = '___kda___'
# ----------------------------------------------------------------------------
# All the boring stuff happens below here. Just edit the drives and
# sleepInterval values above unless you want to tweak the program.
# ----------------------------------------------------------------------------
# import modules
from time import sleep, gmtime, strftime
# this function writes the current time to a file titled ___kda___.txt
# to each drive in the drives array at the interval you select
def writeFile(drives, writeFile):
filename = fileToWrite
strToWrite = strftime('%Y-%m-%d %H:%M:%S', gmtime())
print('------------------------')
for d in drives:
filepath = d + ':/' + filename
try:
_file = open(filepath, 'w+')
_file.write(strToWrite)
_file.close()
print(d + ' | ' + strToWrite)
except:
print(d + ' | ' + strToWrite + ' UNAVAILABLE')
# run the program and keep it alive to end, press ctrl+x (PC) or
# cmd+x (Mac), or just close the console window.
if __name__=="__main__":
while True:
writeFile(drives, fileToWrite)
sleep(sleepInterval)
|
f70798c6c0f6c07ebfb392e6569383a153b27a15
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
filljoyner/Python-KeepDriveAlive
|
f3a21f8e272ca640f6ccaa467012168da5650355
|
a78a51aa8013e9f0570bd53015a02069b4c408b2
|
refs/heads/main
|
<repo_name>haon16/windows-network-programming<file_sep>/1.基本服务器客户端模型/server.c
//时间:2019年7月27日16:55:47
//server
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <WinSock2.h> //打开该文档可看到版本信息
#pragma comment(lib, "ws2_32.lib") //windows socket第二版32位,lib是源文件编译好的二进制文件
//#include <WinSock.h> 对应库 wsock32.lib
int main(void)
{
//1.打开网络库
WORD wdVersion = MAKEWORD(2, 2); //创建版本关键字,高字节放副版本号,低字节放主版本号
//int a = *((char *)&wdVersion); //结果2,取wdVersion的低地址位
//int b = *((char *)&wdVersion + 1); //结果1,取wdVersion的高地址位
WSADATA wdSockMsg; //第一种写法,创建变量直接取地址
//LPWSADATA lpw = malloc(sizeof(WSADATA)); //第二种写法,创建指针变量指向动态分配WSADATA,要free,LPWSADATA类型是WSADATA*
int nRes = WSAStartup(wdVersion, &wdSockMsg); //网络库启动函数,第一个参数是输入的版本关键字,第二个参数是指向WSADATA结构体的地址,启动后把相关信息保存在这个结构体上
/*
MAKEWORD(2, 2),当输入的版本不存在:
(1)输入1.3,2.3 有主版本,没有副版本 得到该主版本的最大副版本1.1,2.2并使用
(2)输入3.1,3.3 超过最大版本号 使用系统能提供的最大的版本2.2
(3)输入0.0 0.1 0.1 主版本是0 网络库打开失败,不支持请求的套接字版本
typedef struct WSAData {
WORD wVersion; 我们要使用的版本
WORD wHighVersion; 系统提供给我们的最高版本
#ifdef _WIN64
unsigned short iMaxSockets; 返回可用的socket的数量,2版本之后就没用了
unsigned short iMaxUdpDg; UDP数据报信息的大小,2版本之后就没用了
char FAR * lpVendorInfo; 供应商特定的信息,2版本之后就没用了
char szDescription[WSADESCRIPTION_LEN+1]; 当前版本库的描述信息
char szSystemStatus[WSASYS_STATUS_LEN+1]; 当前状态
#else
......
} WSADATA, FAR * LPWSADATA;
*/
//if (WSAStarup(wdVerison, &wdSockMsg) != 0)
if (0 != nRes) //如果网络库打开成功,返回值是0
{
switch (nRes)
{
case WSASYSNOTREADY:
printf("重启下电脑试试,或者检查网络库");
break;
case WSAVERNOTSUPPORTED:
printf("请更新网络库");
break;
case WSAEINPROGRESS:
printf("请重新启动软件");
break;
case WSAEPROCLIM:
printf("请尝试关掉不必要的软件,以为当前网络运行提供充足资源");
break;
//case WSAEFAULT : //WSAStartup第二个参数:指针参数写错了,程序员检查
// break;
}
return 0;
}
//printf("%s %s\n", wdSockMsg.szDescription, wdSockMsg.szSystemStatus);
//2.校验版本
if (2 != HIBYTE(wdSockMsg.wVersion) || 2 != LOBYTE(wdSockMsg.wVersion))
{
//说明版本不对,不是2.2版本
//清理网络库,有可能清理失败
if (SOCKET_ERROR == WSACleanup()) //正常返回0
{
int a = WSAGetLastError(); //清理失败可用该函数获取错误码,利用错误码可查找错误信息
}
return 0;
}
//3.创建SOCKET
SOCKET socketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //SOCKET是一种数据类型,一个整数,但是是唯一的,标识着当前的应用程序,协议特点等信息,ID,门牌号 SOCKET构成=IP地址+端口
//每一个客户端有一个SOCKET,服务器有一个SOCKET,通信时,就需要这个SOCKET做参数,给谁通信就传递谁的SOCKET
//socket():参数1:地址的类型,参数2:套接字的类型,参数3:协议的类型
int a = WSAGetLastError(); //正常为0,错误会返回错误码
if (INVALID_SOCKET == socketServer) //创建失败
{
//获取错误码,
int a = WSAGetLastError(); //WSAGetLastError获取最近的函数的错误码
//清理网络库
WSACleanup();
return 0;
}
//4.绑定地址与端口
struct sockaddr_in si;
si.sin_family = AF_INET; //跟创建socket时的地址类型对应 ipv4:AF_INET ipv6:AF_INET6
si.sin_port = htons(12345); //输入的整数转换成unsigned short 本地字节序转成网络字节序 (理论范围0-65535) (0-1023为系统保留占用端口号 ) //netstat -ano查看端口使用情况 //netstat -aon|findstr "12345"查看端口是否被使用
si.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //127.0.0.1本地回环地址,回送地址 //ipconfig
/*si.sin_addr.S_un.S_un_b.s_b1 = 192;
si.sin_addr.S_un.S_un_b.s_b2 = 168;
si.sin_addr.S_un.S_un_b.s_b3 = 0;
si.sin_addr.S_un.S_un_b.s_b4 = 1;*/
if (SOCKET_ERROR == bind(socketServer, (const struct sockaddr*)&si, sizeof(si))) //参数2类型是指向const struct sockaddr结构体的指针,sockaddr不好写入地址端口 ->写入sockaddr_in结构体再强转,内存结构是一样的
{ //sockaddr : u_short sa_family; CHAR sa_data[14];
//出错了 //sockaddr_in :short sin_family; USHORT sin_port; IN_ADDR sin_addr; CHAR sin_zero[8];
int a = WSAGetLastError();
//释放
closesocket(socketServer); //先释放socket再关闭网络库,否则会报错
//清理网络库
WSACleanup();
return 0;
}
//5.开始监听, 监听客户端来的链接 将套接字置于正在侦听传入连接的状态
if (SOCKET_ERROR == listen(socketServer, SOMAXCONN)) //参数2是挂起连接队列的最大长度,比如有100个用户链接请求,但是系统一次只能处理20个,剩下80个不能不理人家,所以系统就创建个队列记录这些暂时不能处理,一会处理的链接请求,依先后顺序处理
{ //SOMAXCONN是让系统自动选择最合适的个数
//出错了
int a = WSAGetLastError();
//释放
closesocket(socketServer);
//清理网络库
WSACleanup();
return 0;
}
//6.创建客户端socket listen监听客户端来的链接,将客户端的信息绑定到一个socket上,也就是给客户端创建一个socket,通过返回值返回给我们客户端的socket
struct sockaddr_in clientMsg; //这个我们不用填写,系统会帮我们填写,也即传址调用
int len = sizeof(clientMsg);
SOCKET socketClient = accept(socketServer, (struct sockaddr *)&clientMsg, &len); //一次只能创建一个,有几个客户端链接,就要调用几次, 这个函数如果没有客户端链接会一直卡在这,阻塞
/*
参数2:系统帮我们监视着客户端的动态,肯定会记录客户端的信息,也就是IP地址和端口号,并通过这个结构体记录
参数3:参数2的大小,
参数2,3也能置成NULL,accept函数不直接得到客户端的地址,端口号,接受下一个客户端信息就会覆盖掉当前的信息
如果此时不接受,也可在接下来调用getpeername函数获得客户端信息
SOCKET socketClient = accept(socketServer, NULL, NULL);
getpeername(socketClient, (struct sockaddr *)&clientMsg, &len);
得到本地服务器信息:getsockname()
getsockname(socketServer, (struct sockaddr *)&clientMsg, &len); //即使此处填的客户端信息,获取的也是本地服务器的信息
*/
if (INVALID_SOCKET == socketClient)
{
printf("客户端链接失败");
//出错了
int a = WSAGetLastError();
//释放
closesocket(socketServer);
//清理网络库
WSACleanup();
return 0;
}
printf("客户端链接成功\n");
if (SOCKET_ERROR == send(socketClient, "我是服务器,我收到了你的消息", sizeof("我是服务器,我收到了你的消息"), 0))
{
//出错了
int a = WSAGetLastError();
//根据实际情况处理, 根据错误码信息做相应处理:重启/等待/不用理会
}
while(1)
{
//7.服务端接收客户端信息:得到指定客户端(参数1)发来的消息
//原理:本质是复制:1.数据的接受都是有协议本身做的,也就是socket的底层做的,系统有一段缓冲区,存储着接受到的数据 2.咱们外边调用recv的作用,就是通过socket找到这个缓冲区,并把数据复制进参数2,复制参数3个
char buf[1500] = { 0 };
int res = recv(socketClient, buf, 1499, 0);
/*
参数1:客户端的socket,每个客户端对应唯一的socket
参数2:客户端消息的存储空间,也就是字符数组 一般1500字节,网络传输的最大单元是1500字节,也就是客户端发过来的数据,一次最大就是1500字节,这个协议规定,总结的最优值,所以客户端一组最多来1500字节,服务器这端1500读一次就够了
参数3:想要读取的字节数,一般是参数2的字节数-1,把\0字符串结尾留出来, %s可直接输出
参数4:数据的读取方式:一般填0 正常逻辑来说(这种逻辑填0):1.我们从系统缓冲区把数据读到buf后,系统缓冲区的被读的就应该被删除掉了,不然也是浪费空间,毕竟通信时间长的话,那就爆炸了。
2.我们从系统缓冲区把数据读到buf,根据需要处理相应的数据,这是我们可控的,系统缓冲区的数据则操作不了
3.读出来就删的话,有很多好处 1.系统缓冲区读到的数据,比我们的buf多,那么我们读出来的,系统删掉,从而我们就可以依次把所有的数据读完,如果不删,每次都是从头读,则循环里就是每次都是某个字符数组比如“abcd”只读到这四个 2.可以计数收到了多少字节, 因为返回值就是本次读出来的数据
参数4:MSG_PEEK 1.窥视传入的数据,数据将复制到缓冲区中,但从不会从输入队列中删除 2.不建议使用:读数据不行/无法计数
参数4:MSG_OOB 带外数据 意义:就是传输一段数据,在外带一个额外的特殊数据,相当于小声BB 实际:不建议使用 1.TPC协议规范(RFC793)中OOB的原始描述被“主机要求”规范取代(RFC1122),但仍有许多机器具有RFC793 OOB实现 2.既然两种数据,完全可以send两次,另一方recv两次,不然还要特殊处理外带数据
参数4:MSG_WAITALL 直到系统缓冲区字节数满足参数3所请求的字节数,才开始读取
返回值是读出来的字节数大小 读没了?在recv函数卡着,等着客户端发来数据,即阻塞,同步
*/
if (0 == res) //客户端下线,会释放客户端socket,这端返回0,
{
printf("链接中断,客户端下线\n");
}
else if (SOCKET_ERROR == res) //执行失败,返回SOCKET_ERROR
{
//出错了
int a = WSAGetLastError();
//根据实际情况处理, 根据错误码信息做相应处理:重启/等待/不用理会
}
else
{
printf("%d %s\n", res, buf);
}
//7.服务端给客户端发送数据
//作用:向目标发送数据 本质:send函数将我们得数据复制粘贴进系统的协议发送缓冲区,计算机伺机发送出去,最大传输单元是1500字节
scanf("%s", buf);
int b = send(socketClient, buf, strlen(buf), 0);
/*
参数1:目标的socket,每个客户端对应唯一的socket
参数2:给目标发送字节串
(1)这个不要超过1500字节:
1).发送时候,协议要进行包装,加上协议信息,也叫协议头,或者叫包头。
2).这个大小不同的协议不一样,链路层14字节,ip头20字节,tcp头20字节,数据结尾还要有状态确认,加起来也几十个字节,所以实际咱们的数据位不能写1500个,要留出来,那就1024或者最多1400就差不多了
(2)超过1500个字节系统会分片处理
1).比如2000个字节,系统会分成两个包,假设包头100字节 第一次1400+包头 ==1500, 第二次600+包头==700,分两次发送出去
2).结果:1.系统要给咱们分包再打包,再发送,客户端接收到了还得拆包,组合数据,从而增加了系统得工作,降低效率 2.有的协议,就把分片后得二包直接丢了
参数3. 字节个数
参数4. 发送规则,一般写0 1.MSG_OOB同recv, 2.MSG_DONTROUTE 指定数据不应受路由限制,windows套接字服务提供程序可以忽略此标志
返回值:成功返回写入的字节数,执行失败返回SOCKET_ERROR
*/
if (SOCKET_ERROR == b)
{
//出错了
int a = WSAGetLastError();
//根据实际情况处理, 根据错误码信息做相应处理:重启/等待/不用理会
}
}
closesocket(socketClient);
closesocket(socketServer); //WSAGetLastError获取最近的函数的错误码
//清理网络库
WSACleanup();
system("pause");
return 0;
}
/*
int WSAAPI WSAStartup(_In_ WORD wVersionRequested, _Out_ LPWSADATA lpWSAData)
SOCKET WSAAPI socket(_In_ int af, _In_ int type, _In_ int protocol)
int WSAAPI bind(_In_ SOCKET s, _In_reads_bytes_(namelen) const struct sockaddr FAR * name, _In_ int namelen)
int WSAAPI listen(_In_ SOCKET s, _In_ int backlog)
SOCKET WSAAPI accept(_In_ SOCKET s, _Out_writes_bytes_opt_(*addrlen) struct sockaddr FAR * addr, _Inout_opt_ int FAR * addrlen)
int WSAAPI recv(_In_ SOCKET s, _Out_writes_bytes_to_(len, return) __out_data_source(NETWORK) char FAR * buf, _In_ int len, _In_ int flags)
int WSAAPI send(_In_ SOCKET s, _In_reads_bytes_(len) const char FAR * buf, _In_ int len, _In_ int flags)
WSAAPI 调用约定 可以忽略给系统看的,跟咱们无关
调用约定决定了:1.函数名字的编译方式 2.参数的入栈顺序 3.函数的调用时间
*/
/*
在C/C++写网络程序的时候,往往会遇到字节的网络顺序和主机顺序的问题。这是就可能用到htons(), ntohl(), ntohs(),htons()这4个函数。
网络字节顺序与本地字节顺序之间的转换函数:
htonl()--"Host to Network Long"
ntohl()--"Network to Host Long"
htons()--"Host to Network Short"
ntohs()--"Network to Host Short"
之所以需要这些函数是因为计算机数据表示存在两种字节顺序:NBO与HBO
网络字节顺序NBO(Network Byte Order): 按从高到低的顺序存储,在网络上使用统一的网络字节顺序,可以避免兼容性问题。
主机字节顺序(HBO,Host Byte Order): 不同的机器HBO不相同,与CPU设计有关,数据的顺序是由cpu决定的,而与操作系统无关。
如 Intel x86结构下, short型数0x1234表示为34 12, int型数0x12345678表示为78 56 34 12
如 IBM power PC结构下, short型数0x1234表示为12 34, int型数0x12345678表示为12 34 56 78
*/<file_sep>/1.基本服务器客户端模型/client.c
//时间:2019年7月30日12:59:01
//client
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <WinSock2.h> //打开该文档可看到版本信息
#pragma comment(lib, "ws2_32.lib") //windows socket第二版32位,lib是源文件编译好的二进制文件
//#include <WinSock.h> 对应库 wsock32.lib
int main(void)
{
//1.打开网络库
WORD wdVersion = MAKEWORD(2, 2); //创建版本关键字,高字节放副版本号,低字节放主版本号
//int a = *((char *)&wdVersion); //结果2,取wdVersion的低地址位
//int b = *((char *)&wdVersion + 1); //结果1,取wdVersion的高地址位
WSADATA wdSockMsg; //第一种写法,创建变量直接取地址
//LPWSADATA lpw = malloc(sizeof(WSADATA)); //第二种写法,创建指针变量指向动态分配WSADATA,要free,LPWSADATA类型是WSADATA*
int nRes = WSAStartup(wdVersion, &wdSockMsg); //网络库启动函数,第一个参数是输入的版本关键字,第二个参数是指向WSADATA结构体的地址,启动后把相关信息保存在这个结构体上
//if (WSAStarup(wdVerison, &wdSockMsg) != 0)
if (0 != nRes) //如果网络库打开成功,返回值是0
{
switch (nRes)
{
case WSASYSNOTREADY:
printf("重启下电脑试试,或者检查网络库");
break;
case WSAVERNOTSUPPORTED:
printf("请更新网络库");
break;
case WSAEINPROGRESS:
printf("请重新启动软件");
break;
case WSAEPROCLIM:
printf("请尝试关掉不必要的软件,以为当前网络运行提供充足资源");
break;
//case WSAEFAULT : //WSAStartup第二个参数:指针参数写错了,程序员检查
// break;
}
return 0;
}
//printf("%s %s\n", wdSockMsg.szDescription, wdSockMsg.szSystemStatus);
//2.校验版本
if (2 != HIBYTE(wdSockMsg.wVersion) || 2 != LOBYTE(wdSockMsg.wVersion))
{
//说明版本不对,不是2.2版本
//清理网络库,有可能清理失败
if (SOCKET_ERROR == WSACleanup()) //正常返回0
{
int a = WSAGetLastError(); //清理失败可用该函数获取错误码,利用错误码可查找错误信息
}
return 0;
}
//3.创建SOCKET,服务器的socket,客户端主动去连接服务器,无别的地方来连接客户端
SOCKET socketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //SOCKET是一种数据类型,一个整数,但是是唯一的,标识着当前的应用程序,协议特点等信息,ID,门牌号
//socket():参数1:地址的类型,参数2:套接字的类型,参数3:协议的类型
int a = WSAGetLastError(); //正常为0,错误会返回错误码
if (INVALID_SOCKET == socketServer) //创建失败
{
//获取错误码,
int a = WSAGetLastError(); //WSAGetLastError获取最近的函数的错误码
//清理网络库
WSACleanup();
return 0;
}
//4.链接服务器
//作用:链接服务器并把服务器信息与服务器socket绑定到一起
struct sockaddr_in serverMsg;
serverMsg.sin_family = AF_INET;
serverMsg.sin_port = htons(12345); //要连接服务器,端口号要跟服务器的一样
serverMsg.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //服务器的ip地址
if (SOCKET_ERROR == connect(socketServer, (struct sockaddr*)&serverMsg, sizeof(serverMsg)))
{
int a = WSAGetLastError();
closesocket(socketServer);
//清理网络库
WSACleanup();
return 0;
}
while (1)
{
//5.与服务器收发消息
char buf[1500] = { 0 };
//int res = recv(socketServer, buf, 1499, 0);
//if (0 == res) //客户端下线,会释放客户端socket,这端返回0,
//{
// printf("链接中断,客户端下线\n");
//}
//else if (SOCKET_ERROR == res) //执行失败,返回SOCKET_ERROR
//{
// //出错了
// int a = WSAGetLastError();
// //根据实际情况处理, 根据错误码信息做相应处理:重启/等待/不用理会
//}
//else
//{
// printf("%d %s\n", res, buf);
//}
//5.与服务器收发消息
scanf("%s", buf);
if (0 == strcmp(buf, "0"))
break;
if (SOCKET_ERROR == send(socketServer, buf, strlen(buf), 0))
{
//出错了
int a = WSAGetLastError();
//根据实际情况处理, 根据错误码信息做相应处理:重启/等待/不用理会
}
}
//清理网络库
closesocket(socketServer);
WSACleanup();
system("pause");
return 0;
}<file_sep>/4.异步选择模型/asyncSelect.c
//时间:2019年8月6日21:38:03
//异步选择模型
/*
核心:消息队列 操作系统为每个窗口创建一个消息队列并且维护,所以我们要使用消息队列,那就要创建一个窗口
第一步:将我们的socket操作绑定在一个消息上,并投递给操作系统 WSAAsyncSelect
第二部:取消息分类处理 如果有操作了,就会得到指定的消息
该模型只能用于windows,主要学这种处理思想
*/
//#include <windows.h>
#include <TCHAR.H> //_T头文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define UM_ASYNCSELECTMSG WM_USER+1 //WM_USER以下是系统定义使用的数,WM_USER之后的数是给程序员使用的
LRESULT CALLBACK WinBackProc(HWND hWnd, UINT msgID, WPARAM wparam, LPARAM lparam);
#define MAX_SOCK_COUNT 1024
SOCKET g_sockall[MAX_SOCK_COUNT]; //保存消息处理时创建的socket
int g_count = 0; //数组有效个数
/*
参数一:当前运行在系统上的应用程序的实例句柄,或者说ID或编号
参数二:前一个实例句柄,应用程序可打开多个,会把前一个实例句柄传过来,不过现在已经无效了,功能已取消
参数三:传递命令行参数,与main主程序一样
参数四:窗口的默认显示方式
*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE HPreInstance, LPSTR lpCmdLine, int nShowCmd)
{
//第一步,创建窗口结构体
WNDCLASSEX wc; //WNDCLASS和WNDCLASSEX两种结构体 ex表示额外的,多几个变量
wc.cbClsExtra = 0; //额外空间
wc.cbSize = sizeof(WNDCLASSEX);
wc.cbWndExtra = 0; //额外空间
wc.hbrBackground = NULL; //NULL窗口默认白色
wc.hCursor = NULL; //鼠标的形态,
wc.hIcon = NULL; //左上角的图标
wc.hIconSm = NULL; //缩小化的图标,底下一栏
wc.hInstance = hInstance;
wc.lpfnWndProc = WinBackProc;
wc.lpszClassName = _T("mywindow"); //窗口名字 //字符集四种解决办法,除了这三种(L, _T, TEXT("mywindow"))还有一种修改字符集,不推荐,从代码角度修改
wc.lpszMenuName = NULL; //菜单栏
wc.style = CS_HREDRAW | CS_VREDRAW; //风格
//第二步,注册结构体 把上述类型的窗口投递给系统
RegisterClassEx(&wc);
//第三步,创建窗口
HWND hWnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, TEXT("mywindow"), _T("我的窗口"), WS_OVERLAPPEDWINDOW, 200, 200, 600, 400, NULL, NULL, hInstance, NULL);
if (NULL == hWnd)
{
return 0;
}
//第四步,显示窗口
ShowWindow(hWnd, nShowCmd);
//更新窗口 重新绘制窗口 非必要的
UpdateWindow(hWnd);
//socket初始化
//打开网络库
WSADATA wsadata;
if (0 != WSAStartup(MAKEWORD(2, 2), &wsadata))
{
printf("网络库打开失败");
return 0;
}
//检验版本
if (2 != HIBYTE(wsadata.wVersion) || 2 != LOBYTE(wsadata.wVersion))
{
printf("版本错误\n");
WSACleanup();
return 0;
}
//创建服务器socket
SOCKET socketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == socketServer)
{
printf("创建服务器socket失败,错误码:%d\n", WSAGetLastError());
WSACleanup();
return 0;
}
//绑定IP和端口
struct sockaddr_in socketMsg;
socketMsg.sin_family = AF_INET;
socketMsg.sin_port = htons(12345);
socketMsg.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (SOCKET_ERROR == bind(socketServer, (const struct sockaddr *)&socketMsg, sizeof(socketMsg)))
{
printf("绑定IP和端口失败,错误码:%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//监听客户端来的链接
if (SOCKET_ERROR == listen(socketServer, SOMAXCONN))
{
printf("监听失败,错误码:%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//消息处理:绑定消息与socket并且投递出去
//作用:将socket与消息绑定在一起,并投递给操作系统
//参数一:socket
//参数二:窗口句柄:绑定到哪个窗口上 本质就是窗口的ID,编号
//参数三:消息编号:自定义消息 本质就是一个数
//参数四:消息类型,与事件选择一样
if (SOCKET_ERROR == WSAAsyncSelect(socketServer, hWnd, UM_ASYNCSELECTMSG, FD_ACCEPT))
{
printf("消息队列投递失败,错误码:%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//装服务器socket
g_sockall[g_count] = socketServer;
g_count++;
//第五步,消息循环:socket绑定消息投递给系统后,当socket发生事件或客户端有请求,这些请求以消息的形式进入消息队列,循环从消息队列中依次往外拿消息,然后分发消息
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) //只有关闭窗口才会结束循环 //一次只取一个
{
TranslateMessage(&msg); //翻译消息
DispatchMessage(&msg); //分发消息
}
//释放socket
for (int i = 0; i < g_count; i++)
{
closesocket(g_sockall[i]);
}
//关闭网络库
WSACleanup();
return 0;
}
int x = 0;
//第六步,回调函数,一次只处理一个
LRESULT CALLBACK WinBackProc(HWND hWnd, UINT msgID, WPARAM wparam, LPARAM lparam) //分发到这个函数 参数一:窗口句柄;参数二:消息ID;参数三:socket;参数四:传输的消息
{
HDC hdc = GetDC(hWnd); //获取当前窗口的设备环境句柄
switch (msgID) //根据消息进行相应处理
{
case UM_ASYNCSELECTMSG:
{ //case内部不能直接定义变量,加花括号可解决
//测试用MessageBox(NULL, L"有信号了", L"提示", MB_OK); //参数一:填写NULL代表弹出的窗口是独立窗口,填写hWnd代表弹出的窗口是hWnd窗口的子窗口;参数二:弹出窗口的内容;参数三:弹出窗口的标题;参数四:弹出窗口中按钮的类型
//获取socket
SOCKET sock = (SOCKET)wparam; //wparam存的是socket
//获取消息
if (0 != HIWORD(lparam)) //lparam高位存的是产生的错误码,如果客户端发送消息,发送过程中出错了,会得到错误码,不为0就代表有错,等于0才能处理消息
{
if (WSAECONNABORTED == HIWORD(lparam)) //关闭客户端会执行到这
{
TextOut(hdc, 0, x, _T("close"), strlen("close"));
x += 15;
//关闭该socket上的消息
WSAAsyncSelect(sock, hWnd, 0, 0);
//关闭socket
closesocket(sock);
//记录数组中删除该socket
for (int i = 0; i < g_count; i++)
{
if (sock == g_sockall[i])
{
g_sockall[i] = g_sockall[g_count - 1];
g_count--;
break;
}
}
}
break;
}
//具体消息
switch (LOWORD(lparam)) //lparam低位存的是具体的消息种类
{
case FD_ACCEPT:
{
//窗口打印消息
TextOut(hdc, 0, x, _T("accept"), strlen("accept")); //参数一:窗口里的一部分,非客户区,设备环境句柄; 参数二三:坐标; 参数四:窗口打印的消息; 参数五:消息字节大小,不带'\0'可以刚好输出
x += 15;
//创建客户端socket
SOCKET socketClient = accept(sock, NULL, NULL);
if (INVALID_SOCKET == socketClient)
{
printf("创建客户端socket出错,错误码:%d\n", WSAGetLastError());
break;
}
//将客户端socket投递给消息队列
if (SOCKET_ERROR == WSAAsyncSelect(socketClient, hWnd, UM_ASYNCSELECTMSG, FD_READ|FD_WRITE|FD_CLOSE))
{
printf("消息队列投递失败,错误码:%d\n", WSAGetLastError());
closesocket(socketClient);
break;
}
//记录客户端socket,为了后续释放掉
g_sockall[g_count] = socketClient;
g_count++;
}
break;
case FD_READ:
{
//read
TextOut(hdc, 0, x, _T("read"), strlen("read"));
char str[1024] = { 0 };
if (SOCKET_ERROR == recv(sock, str, 1023, 0))
{
printf("获取消息失败,错误码:%d\n", WSAGetLastError());
break;
}
TextOut(hdc, 50, x, str, strlen(str)); //此处输出字符串要改成多字节形式,因为比较复杂直接在字符集修改成多字节形式,L不能使用了,都改成通用的_L("")
x += 15;
}
break;
case FD_WRITE:
//send
TextOut(hdc, 0, x, _T("write"), strlen("write"));
x += 15;
break;
case FD_CLOSE:
TextOut(hdc, 0, x, _T("close"), strlen("close"));
x += 15;
//关闭该socket上的消息
WSAAsyncSelect(sock, hWnd, 0, 0);
//关闭socket
closesocket(sock);
//记录数组中删除该socket
for (int i = 0; i < g_count; i++)
{
if (sock == g_sockall[i])
{
g_sockall[i] = g_sockall[g_count - 1];
g_count--;
break;
}
}
}
}
break;
case WM_CREATE: //只在窗口创建的时候执行一次,初始化,网络初始化也可放在此处
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
ReleaseDC(hWnd, hdc); //释放hdc
return DefWindowProc(hWnd, msgID, wparam, lparam);
}
/*
优化:每个窗口维护一定的,然后创建多个线程,每个线程一个窗口,每个窗口投递一定数量的客户端
问题:在一次处理过程中,客户端产生多次send,服务器会产生多次接收消息,第一次接收消息会收完所有信息 调试:在消息循环前while加断点,客户端发送多个消息,取消断点继续,服务器只有一次read,但是把所有消息数据都打印了
*/
<file_sep>/3.事件选择模型/增大处理事件的数量之一个一个询问.c
//时间:2019年8月5日15:46:15
//事件选择模型
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
//定义事件集合以及socket集合的结构体
struct fd_es_set
{
unsigned short count;
SOCKET sockall[1024]; //一个个询问事件时数组长度可以不受约束,可大于64
WSAEVENT eventall[1024];
};
struct fd_es_set esSet;
//回调函数
BOOL WINAPI fun(DWORD dwCtrlType)
{
switch (dwCtrlType)
{
case CTRL_CLOSE_EVENT:
for (int i = 0; i < esSet.count; i++)
{
closesocket(esSet.sockall[i]);
WSACloseEvent(esSet.eventall[i]);
}
break;
}
return TRUE;
}
int main()
{
//控制台退出 主函数投递一个监视
SetConsoleCtrlHandler(fun, TRUE);
//打开网络库
WSADATA wsadata;
int nRes = WSAStartup(MAKEWORD(2, 2), &wsadata);
if (0 != nRes)
{
printf("创建失败,错误码为%d\n", WSAGetLastError());
return 0;
}
//校验版本
if (2 != HIBYTE(wsadata.wVersion) || 2 != LOBYTE(wsadata.wVersion))
{
printf("版本错误\n");
WSACleanup();
return 0;
}
//创建服务器Socket
SOCKET socketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == socketServer)
{
printf("创建服务器Socket失败\n");
WSACleanup();
return 0;
}
//绑定IP地址和端口
struct sockaddr_in socketMsg;
socketMsg.sin_family = AF_INET;
socketMsg.sin_port = htons(12345);
socketMsg.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (SOCKET_ERROR == bind(socketServer, (const struct sockaddr*)&socketMsg, sizeof(socketMsg)))
{
printf("绑定IP地址和端口出现错误,错误码为%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//监听
if (SOCKET_ERROR == listen(socketServer, SOMAXCONN))
{
printf("监听失败,错误码为%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//创建事件
WSAEVENT eventServer = WSACreateEvent();
if (WSA_INVALID_EVENT == eventServer)
{
printf("创建事件失败,错误码为%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//绑定并投递 WSAEventSelect
if (SOCKET_ERROR == WSAEventSelect(socketServer, eventServer, FD_ACCEPT))
{
printf("绑定事件失败,错误码为%d\n", WSAGetLastError());
WSACloseEvent(eventServer);
closesocket(socketServer);
WSACleanup();
}
//装进去
esSet.eventall[esSet.count] = eventServer;
esSet.sockall[esSet.count] = socketServer;
esSet.count++;
while (1)
{
//询问事件
for (int i = 0; i < esSet.count; i++) //一个一个询问 可结合线程池
{
DWORD nRes = WSAWaitForMultipleEvents(1, &esSet.eventall[i], FALSE, 0, FALSE); //最多询问64个,但是如果一个个询问的话就不受限制了
if (WSA_WAIT_FAILED == nRes)
{
printf("询问事件失败,错误码为%d\n", WSAGetLastError());
continue;
}
//如果参数4写具体超时间隔,此时事件要加上超时判断
if (WSA_WAIT_TIMEOUT == nRes)
{
continue;
}
//列举事件,得到下标对应的具体操作
WSANETWORKEVENTS NetworkEvents;
if (SOCKET_ERROR == WSAEnumNetworkEvents(esSet.sockall[i], esSet.eventall[i], &NetworkEvents))
{
printf("得到下标对应的具体操作失败,错误码:%d\n", WSAGetLastError());
break;
}
if (NetworkEvents.lNetworkEvents & FD_ACCEPT)
{
if (0 == NetworkEvents.iErrorCode[FD_ACCEPT_BIT])
{
//正常处理
SOCKET socketClient = accept(esSet.sockall[i], NULL, NULL);
if (INVALID_SOCKET == socketClient)
{
continue;
}
//创建事件对象
WSAEVENT wsaClientEvent = WSACreateEvent();
if (WSA_INVALID_EVENT == wsaClientEvent)
{
closesocket(socketClient);
continue;
}
//投递给系统
if (SOCKET_ERROR == WSAEventSelect(socketClient, wsaClientEvent, FD_READ | FD_CLOSE | FD_WRITE))
{
closesocket(socketClient);
WSACloseEvent(wsaClientEvent);
continue;
}
//装进结构体
esSet.sockall[esSet.count] = socketClient;
esSet.eventall[esSet.count] = wsaClientEvent;
esSet.count++;
printf("accept event\n");
}
else
{
continue;
}
}
if (NetworkEvents.lNetworkEvents & FD_WRITE)
{
if (0 == NetworkEvents.iErrorCode[FD_WRITE_BIT])
{
if (SOCKET_ERROR == send(esSet.sockall[i], "connect success", strlen("connect success"), 0))
{
printf("send失败,错误码为:%d\n", WSAGetLastError());
continue;
}
printf("write event\n");
}
else
{
printf("socket error套接字错误,错误码为:%d\n", NetworkEvents.iErrorCode[FD_WRITE_BIT]);
}
}
if (NetworkEvents.lNetworkEvents & FD_READ)
{
if (0 == NetworkEvents.iErrorCode[FD_READ_BIT])
{
char strRecv[1500] = { 0 };
if (SOCKET_ERROR == recv(esSet.sockall[i], strRecv, 1499, 0))
{
printf("recv失败,错误码为:%d\n", WSAGetLastError());
continue;
}
printf("接收的数据:%s\n", strRecv);
}
else
{
printf("socket error套接字错误,错误码为:%d\n", NetworkEvents.iErrorCode[FD_READ_BIT]);
continue;
}
}
if (NetworkEvents.lNetworkEvents & FD_CLOSE)
{
//打印
printf("client close\n");
printf("client force out客户端强制退出,错误码:%d\n", NetworkEvents.iErrorCode[FD_CLOSE_BIT]);
//清理下线的客户端 套接字 事件
closesocket(esSet.sockall[i]);
esSet.sockall[i] = esSet.sockall[esSet.count - 1];
WSACloseEvent(esSet.eventall[i]);
esSet.eventall[i] = esSet.eventall[esSet.count - 1];
esSet.count--;
}
}
}
//释放事件句柄//释放socket
for (int i = 0; i < esSet.count; i++)
{
closesocket(esSet.sockall[i]);
WSACloseEvent(esSet.eventall[i]);
}
//清理网络库
WSACleanup();
system("pause");
return 0;
}
/*
->事件机制 事件选择模型 ->重叠I/O模型
C/S -> select
->消息机制 异步选择模型 ->完成端口模型
*/
<file_sep>/5.重叠IO模型/完成例程.c
//时间:2019年8月10日13:32:39
//完成例程
/*
本质: 1.为我们的socket,重叠结构绑定一个函数。当异步操作完成时,系统异步自动调用这个函数,send绑一个,recv绑一个,完成就调用各自的函数,自动分类 (1)然后我们再函数内部做相应的操作 (2)注意:异步完成之后才有的通知
2.事件通知 需要咱们调用WSAGetOverlappedResult得到结果,然后根据逻辑,自己分类,分类的逻辑太多,大家自己思考
3.所以区别 分类方式上,完成例程性能更好,系统自动调用
代码逻辑: 1.创建事件数组,socket数组,重叠结构体数组 下标相同的绑定成一组
2.创建重叠IO模型使用的socket WSASocket
3.投递AcceptEx (1)立即完成: 1)对客户端套接字投递WSARecv
1.立即完成
2.回调函数: 处理信息 对客户端套接字投递WSARecv
2)根据需求对客户端套接字投递WSASend
1.立即完成
2.回调函数
3)对服务器套接字继续投递AcceptEx 重复上述
(2)延迟完成 那就去循环等信号
4.循环等信号 (1)等信号 WSAWaitForMultipleEvents
(2)有信号 接收链接 投递AcceptEx
(3)根据需求对客户端套接字投递WSASend 回调函数
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <mswsock.h> //要放在winsock2.h后面,不然会报错
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "Mswsock.lib")
#define MAX_COUNT 1024
#define MAX_RECV_COUNT 1024
SOCKET g_allSock[MAX_COUNT]; //创建socket数组 (创建事件数组可省略,重叠结构体里包含了事件)
OVERLAPPED g_allOlp[MAX_COUNT]; //创建重叠结构体数组 下标相同的绑定成一组,调用函数时会自动绑定到一起
int g_count;
//接收缓冲区
char g_strRecv[MAX_RECV_COUNT] = { 0 };
int PostAccept();
int PostRecv(int index);
int PostSend(int index);
void Clear()
{
for (int i = 0; i < g_count; i++)
{
closesocket(g_allSock[i]);
WSACloseEvent(g_allOlp[i].hEvent);
}
}
//回调函数 (点控制台退出)
BOOL WINAPI fun(DWORD dwCtrlType)
{
switch (dwCtrlType)
{
case CTRL_CLOSE_EVENT:
Clear();
break;
}
return TRUE;
}
int main()
{
//控制台退出 主函数投递一个监视
SetConsoleCtrlHandler(fun, TRUE);
//打开网络库
WSADATA wsadata;
if (0 != WSAStartup(MAKEWORD(2, 2), &wsadata))
{
printf("网络库打开失败\n");
return 0;
}
//校验版本
if (2 != HIBYTE(wsadata.wVersion) || 2 != LOBYTE(wsadata.wVersion))
{
printf("版本有误\n");
WSACleanup();
return 0;
}
//创建重叠IO模型使用的socket
SOCKET socketServer = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
if (INVALID_SOCKET == socketServer)
{
printf("服务器socket创建失败,错误码:%d\n", WSAGetLastError());
WSACleanup();
return 0;
}
//绑定IP和端口
struct sockaddr_in socketServerMsg;
socketServerMsg.sin_family = AF_INET;
socketServerMsg.sin_port = htons(12345);
socketServerMsg.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (SOCKET_ERROR == bind(socketServer, (const struct sockaddr *)&socketServerMsg, sizeof(socketServerMsg)))
{
printf("绑定IP和端口失败,错误码:%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//监听
if (SOCKET_ERROR == listen(socketServer, SOMAXCONN))
{
printf("监听失败,错误码:%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
g_allSock[g_count] = socketServer;
g_allOlp[g_count].hEvent = WSACreateEvent();
g_count++;
//投递AcceptEx
if (0 != PostAccept())
{
Clear();
WSACleanup();
return 0;
}
//循环等待事件
while (1)
{
DWORD nRes = WSAWaitForMultipleEvents(1, &g_allOlp[0].hEvent, FALSE, WSA_INFINITE, TRUE); //参数5: WSA_INFINITE 咱就等一个,所以等有信号再走就行
//参数6:设置TRUE 意义:1.将等待事件函数与完成例程机制结合在一起
//2.实现等待事件函数与完成例程函数的异步执行,执行完并给等待事件函数信号 等待事件函数返回WSA_WAIT_IO_COMPLETION(一个完成例程执行完了,就会返回这个值)
//3.即WSAWaitForMultipleEvents不仅能获取事件的信号通知,还能获取完成例程的执行通知
if (WSA_WAIT_FAILED == nRes || WSA_WAIT_IO_COMPLETION == nRes)
{
continue;
}
//有信号了
//信号置空
WSAResetEvent(g_allOlp[0].hEvent);
//接收链接完成了
//PostSend(g_count);
printf("accept\n");
//投递Recv
PostRecv(g_count);
//根据情况投递send
//客户端适量++
g_count++;
//投递accept
PostAccept();
}
Clear();
//清理网络库
WSACleanup();
system("pause");
return 0;
}
//投递AcceptEx
int PostAccept()
{
//投递异步接收链接请求
while (1) //循环方法
{
//创建客户端socket和相应的事件 (参数2需要)
g_allSock[g_count] = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
g_allOlp[g_count].hEvent = WSACreateEvent();
//创建字符数组 (参数3需要)
char str[1024] = { 0 };
DWORD dwRecvcount; //参数7需要
//投递AcceptEx
BOOL bRes = AcceptEx(g_allSock[0], g_allSock[g_count], str, 0, sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16, &dwRecvcount, &g_allOlp[0]);
if (TRUE == bRes)
{
//立即完成了
//投递Recv
PostRecv(g_count);
//根据情况投递send
//客户端适量++
g_count++;
//投递accept,递归方法, 递归层数多会爆栈
//PostAccept();
continue;
}
else
{
int a = WSAGetLastError();
if (ERROR_IO_PENDING == a)
{
//延迟处理
break;
}
else
{
break;
}
}
}
return 0;
}
//回调函数
/*
返回值void
调用约定 CALLBACK
函数名字 随意
参数1:错误码
参数2:发送或接收到的字节数
参数3:重叠结构
参数4:函数执行的方式 对照WSARecv参数5
处理流程 1.dwError == 10054 强行退出 (1)先判断 (2)删除客户端
2.cbTransferred == 0 正常退出
3. else 处理数据
对应WSAGetOverlapperResult函数
*/
void CALLBACK RecvCall(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD dwFlags)
{
//方法一:这种获取下标的方法效率太低
//int i = 0;
//for (i; i < g_count; i++)
//{
// if (lpOverlapped->hEvent == g_allOlp[i].hEvent)
// {
// break;
// }
//}
//方法二:
int i = lpOverlapped - &g_allOlp[0];
if (10054 == dwError || 0 == cbTransferred)
{
//删除客户端
printf("close\n");
//关闭
closesocket(g_allSock[i]);
WSACloseEvent(g_allOlp[i].hEvent);
//从数组中删掉
g_allSock[i] = g_allSock[g_count - 1];
g_allOlp[i] = g_allOlp[g_count - 1];
//个数减1
g_count--;
}
else
{
printf("%s\n", g_strRecv);
memset(g_strRecv, 0, MAX_RECV_COUNT);
//根据情况投递send
//对自己投递接收
PostRecv(i);
}
}
int PostRecv(int index)
{
//投递异步接收信息
WSABUF wsabuf;
wsabuf.buf = g_strRecv;
wsabuf.len = MAX_RECV_COUNT;
DWORD dwRecvCount;
DWORD dwflag = 0;
int nRes = WSARecv(g_allSock[index], &wsabuf, 1, &dwRecvCount, &dwflag, &g_allOlp[index], RecvCall);
if (0 == nRes)
{
//立即完成
//打印信息
printf("%s\n", wsabuf.buf);
memset(g_strRecv, 0, MAX_RECV_COUNT);
//根据情况投递send
//对自己投递接收
PostRecv(index);
return 0;
}
else
{
int a = WSAGetLastError();
if (ERROR_IO_PENDING == a)
{
//延迟处理
return 0;
}
else
{
return a;
}
}
return 0;
}
void CALLBACK SendCall(DWORD dwError, DWORD cbTransferred, LPWSAOVERLAPPED lpOverlapped, DWORD dwFlags)
{
printf("send over\n");
}
int PostSend(int index)
{
WSABUF wsabuf;
wsabuf.buf = "你好";
wsabuf.len = MAX_RECV_COUNT;
DWORD dwSendCount;
DWORD dwflag = 0;
int nRes = WSASend(g_allSock[index], &wsabuf, 1, &dwSendCount, dwflag, &g_allOlp[index], SendCall);
if (0 == nRes)
{
//立即完成
//打印信息
printf("send成功\n");
return 0;
}
else
{
int a = WSAGetLastError();
if (ERROR_IO_PENDING == a)
{
//延迟处理
return 0;
}
else
{
return a;
}
}
return 0;
}
/*
对比事件通知: 1.事件通知是咱们自己分配任务 (1)我们waitfor,所以顺序不能保证
(2)循环次数多,下标越大的客户端延迟会越大
2.完成例程是咱们写好任务处理代码 系统根据具体事件自动调用咱们的代码,自动分类
3.所以完成例程比事件通知的性能稍好一些
问题:调试下断点时,在一次处理过程中,客户端产生多次send,服务器会产生多次接收消息,第一次接收消息会收完所有信息
*/<file_sep>/5.重叠IO模型/事件通知.c
//时间:2019年8月8日17:18:52
//重叠I/O
/*
重叠IO介绍:
意义:重叠IO是windows提供的一种异步读写文件的机制
作用: 1.正常读写文件(socket本质就是文件操作),如recv,是阻塞的,等协议缓冲区中的数据全部复制进buffer里,函数才结束并返回复制的个数,写也一样,同一时间只能读写一个,其他的全都靠边等
2.重叠IO机制读写,将读的指令以及咱们的buffer投给操作系统,然后函数直接返回,操作系统独立开个线程,将数据复制进咱们的Buffer,数据复制期间,咱们就去做其他事儿,两不耽误,即读写过程变成了异步,可以同时投递多个读写操作
3.即:将accept, recv, send优化成了异步过程,被AcceptEx WSARecv WSASend函数代替 所以说这个是对基本c/s模型的直接优化
本质: 1.结构体:WSAOVERLAPPED struct _WSAOVERLAPPED
{ 前四个成员系统使用,咱们不需要直接使用
DWORD Internal; 成员1:保留,供服务提供商定义使用 (函数设计者)
DWORD InternalHigh; 成员2:保留,供服务提供商定义使用 接收或者发送的字节数
DWORD Offset; 成员3:保留,供服务提供商定义使用
DWORD OffsetHigh; 成员4:保留,供服务提供商定义使用 一般是错误码
WSAEVENT hEvent; 成员5:事件对象 我们唯一关注的 操作完成他就会被置成有信号
}
2.定义一个该结构体的变量与socket绑定
使用: 1.异步选择模型把消息与socket绑一起,然后系统以消息机制处理反馈
2.事件选择模型把事件与socket绑一起,然后系统以事件机制处理反馈
3.重叠IO模型把重叠结构与socket绑一起,然后系统以重叠IO机制处理反馈
重叠IO反馈两种方式:1.事件通知
2.完成例程 回调函数
重叠IO逻辑:1.事件通知:(1)调用AcceptEx WSARecv WSASend投递
(2)被完成的操作,事件信号置成有信号
(3)调用WSAWaitForMultipleEvents获取事件信号
2.回调函数/完成例程 (1)调用AcceptEx WSARecv WSASend投递
(2)完成后自动调用回调函数
性能:1.网上有测试结果的 20000个客户端同时请求链接以及发送信息 (1)系统CPU使用率上升40%左右 (2)完成端口只有2%左右 极品
2.其他模型也能处理这么多 但是同步(阻塞)的原因,导致延迟太高
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <mswsock.h> //要放在winsock2.h后面,不然会报错
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "Mswsock.lib")
#define MAX_COUNT 1024
#define MAX_RECV_COUNT 1024
//第一步,创建事件数组,socket数组,重叠结构体数组 下标相同的绑定成一组
SOCKET g_allSock[MAX_COUNT]; //创建socket数组 (创建事件数组可省略,重叠结构体里包含了事件)
OVERLAPPED g_allOlp[MAX_COUNT]; //创建重叠结构体数组 下标相同的绑定成一组,调用函数时会自动绑定到一起
int g_count;
//接收缓冲区
char g_strRecv[MAX_RECV_COUNT] = { 0 };
int PostAccept();
int PostRecv(int index);
int PostSend(int index);
void Clear()
{
for (int i = 0; i < g_count; i++)
{
closesocket(g_allSock[i]);
WSACloseEvent(g_allOlp[i].hEvent);
}
}
//回调函数 (点控制台退出)
BOOL WINAPI fun(DWORD dwCtrlType)
{
switch (dwCtrlType)
{
case CTRL_CLOSE_EVENT:
Clear();
break;
}
return TRUE;
}
int main()
{
//控制台退出 主函数投递一个监视
SetConsoleCtrlHandler(fun, TRUE);
//打开网络库
WSADATA wsadata;
if (0 != WSAStartup(MAKEWORD(2, 2), &wsadata))
{
printf("网络库打开失败\n");
return 0;
}
//校验版本
if (2 != HIBYTE(wsadata.wVersion) || 2 != LOBYTE(wsadata.wVersion))
{
printf("版本有误\n");
WSACleanup();
return 0;
}
//第二步,创建重叠IO模型使用的socket
/*
作用: 1.创建一个用于异步操作的socket
2.WSASocket windows专用 (1)WSA的函数都是windows专用的 (2)windows socket async 都是用于支持异步操作
参数1:地址的类型 AF_INET
参数2:套接字的类型 TCP是SOCK_STREAM
参数3:协议的类型
参数4: 1.设置套接字详细的属性 (1)指向WSAPROTOCOL_INFO结构的指针
(2)比如:发送数据是否需要链接(accept connect);是否保证数据完整到达(如果数据丢失是否允许);参数3填0,那么匹配哪个协议;设置传输接收字节数;设置套接字权限;还有很多保留字段,供以后拓展使用
2.不使用 NULL
参数5: 1.一组socket的组ID,大概是想一次操作多个socket
2.保留的,暂时无用,填0
参数6: 1.指定套接字属性
2.填写WSA_FLAG_OVERLAPPED 创建一个供重叠IO模型使用的socket
3.其他的(1)WSA_FLAG_MULTIPOINT_C_ROOT; WSA_FLAG_MULTIPOINT_C_LEAF; WSA_FLAG_MULTIPOINT_D_ROOT; WSA_FLAG_MULTIPOINT_D_LEAF 这几种用于多播协议
(2)WSA_FLAG_ACCESS_SYSTEM_SECURITY 1)套接字操作权限/配合参数4使用
2)意义:可以对套接字send设置权限,就会触发相关的权限设置,提醒
(3)WSA_FLAG_NO_HANDLE_INHERIT 1)套接字不可被继承
2)在多线程开发中,子线程会继承父线程的socket,即主线程创建了一个socket,那么子线程有两种使用方式 : 一,直接用父类的,父子都使用这一个socket--共享 二,把父类的这个socket复制一份,自己用,这俩父子用两个socket,但是本质一样--继承
返回值:1.成功返回可用的socket 不用了就一定要销毁套接字
2.失败返回INVALID_SOCKET
*/
SOCKET socketServer = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
if (INVALID_SOCKET == socketServer)
{
printf("服务器socket创建失败,错误码:%d\n", WSAGetLastError());
WSACleanup();
return 0;
}
//绑定IP和端口
struct sockaddr_in socketServerMsg;
socketServerMsg.sin_family = AF_INET;
socketServerMsg.sin_port = htons(12345);
socketServerMsg.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (SOCKET_ERROR == bind(socketServer, (const struct sockaddr *)&socketServerMsg, sizeof(socketServerMsg)))
{
printf("绑定IP和端口失败,错误码:%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//监听
if (SOCKET_ERROR == listen(socketServer, SOMAXCONN))
{
printf("监听失败,错误码:%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
g_allSock[g_count] = socketServer;
g_allOlp[g_count].hEvent = WSACreateEvent();
g_count++;
//第三步,投递AcceptEx
/*
1.立即完成 (1)对客户端套接字投递WSARecv
1)立即完成 处理信息 对客户端套接字投递WSARecv 重复上述
2)延迟完成 那就去循环等消息
(2) 根据需求对客户端套接字投递WSASend
1)立即完成 处理消息 重复上述
2)延迟完成 那就去循环等消息
(3) 对服务器套接字继续投递AcceptEx 重复上述
2.延迟完成 那就去循环等消息
*/
if (0 != PostAccept())
{
Clear();
WSACleanup();
return 0;
}
//循环等待事件
/*
1.等信号 WSAWaitForMultipleEvents
2.有信号 (1) 获取重叠结构上的信息 WSAGetOverlappedResult
(2)客户端推出 删除服务端的信息
(3)接受链接 投递AcceptEx 上边这个逻辑写好了,封装成函数就非常清晰
(4)接受信息 处理消息 对客户端套接字投递WSARecv
(5)发送消息 根据需求对客户端套接字投递WSASend
*/
while (1)
{
for (int i = 0; i < g_count; i++)
{
DWORD nRes = WSAWaitForMultipleEvents(1, &g_allOlp[i].hEvent, FALSE, 0, FALSE);
if (WSA_WAIT_FAILED == nRes || WSA_WAIT_TIMEOUT == nRes)
{
continue;
}
//有信号了
/*
功能:获取对应的socket上的具体情况
参数1:有信号的socket
参数2:对应的重叠结构
参数3: 1.由发送或者接收到的实际字节数
2. 0 表示客户端下线
参数4: 1.仅当重叠操作选择了基于事件的完成通知时,才能将fWait参数设置为TRUE
2.选择事件通知,填TRUE
参数5: 1.装WSARecv的参数5 lpflags
2.不能是NULL
返回值:1.函数执行成功返回TRUE
2.失败返回FALSE
*/
DWORD dwState;
DWORD dwFlag;
BOOL bFlag = WSAGetOverlappedResult(g_allSock[i], &g_allOlp[i], &dwState, TRUE, &dwFlag);
//信号置空
WSAResetEvent(g_allOlp[i].hEvent);
if (FALSE == bFlag)
{
int a = WSAGetLastError();
if (10054 == a) //跟Recv一样
{
//客户端强制退出
printf("force close\n");
//关闭
closesocket(g_allSock[i]);
WSACloseEvent(g_allOlp[i].hEvent);
//从数组中删掉
g_allSock[i] = g_allSock[g_count - 1];
g_allOlp[i] = g_allOlp[g_count - 1];
//循环控制变量减1
i--;
//个数减1
g_count--;
}
continue;
}
//成功
if (0 == i)
{
//接收链接完成了
printf("accept\n");
PostSend(g_count);
//投递Recv
PostRecv(g_count);
//根据情况投递send
//客户端适量++
g_count++;
//投递accept
PostAccept();
continue;
}
if (0 == dwState) //accept时dwState依然是0,所以应该先判断accept再判断是否正常下线
{
//客户端正常下线
printf("close\n");
//关闭
closesocket(g_allSock[i]);
WSACloseEvent(g_allOlp[i].hEvent);
//从数组中删掉
g_allSock[i] = g_allSock[g_count - 1];
g_allOlp[i] = g_allOlp[g_count - 1];
//循环控制变量减1
i--;
//个数减1
g_count--;
continue;
}
if (0 != dwState)
{
//发送或者接收成功了
if (g_strRecv[0] != 0)
{
//recv
//打印信息
printf("%s\n", g_strRecv);
memset(g_strRecv, 0, MAX_RECV_COUNT);
//根据情况投递send
//对自己投递接收
PostRecv(i);
}
else
{
//send
}
}
}
}
Clear();
//清理网络库
WSACleanup();
system("pause");
return 0;
}
//投递AcceptEx
int PostAccept()
{
//投递异步接收链接请求
/*
功能:投递服务器socket,异步接收链接
参数1:服务器socket
参数2:链接服务器的客户端的socket 1.注意:我们要调用WSASocket亲自创建
2.AcceptEx将客户端的IP端口号绑在这个socket上
参数3: 1.缓冲区的指针,接收在新连接上发送的第一个数据 (1)客户端第一次send,由这个函数接收
(2)第二次以后就由WSARecv接收
2.char str[1024]
3.不能设置NULL
参数4: 1.设置0 取消了参数3的功能
2.设置成参数3的1024: (1)那么就会接收第一次的数据
(2)此时,客户端链接并发送了一条消息,服务器才产生信号 : 所以会有阻塞状况,光链接不行,必须等客户端发来一条消息,他才完事有信号,所以设置0就行了
参数5: 1.为本地地址信息保留的字节数。此值必须至少比使用的传输协议的最大地址长度长16个字节 (本地去保存客户端地址信息空间的大小)
2.sizeof(struct sockaddr_in) + 16
参数6: 1.为远程地址信息保留的字节数,此值必须至少比使用的传输协议的最大地址长度长16个字节,不能为0 (大概意思:在物理内存上申请多大空间去临时存储客户端的地址信息) (文件地址,物理地址)
2.sizeof(struct sockaddr_in) + 16
参数7: 1.该函数可以接收第一次客户端发来的消息,如果这个消息刚好是调用时候接收到了,也即立即接收到了(客户端链接的同时发送了消息),这时候装着接收到的字节数(配合参数3,4使用)
(1)也就是这个接收是同步完成的时候,这个参数会被装上
(2)没有立即处理,也即异步接收到消息,这时候这个参数没用
2.大家可以填写:(1)填写NULL,不想获得这个字节数 (2)也可以填写DWORD变量的地址, 填这个就行
参数8:我们的重叠结构(服务器socket对应的重叠重构)
返回值:1.TRUE 立即返回 刚执行就已经有客户端到了
2.FALSE 出错 (1)int a = WSAGetLatError()
(2)如果 a == ERROR_IO_PENDING 异步等待, 客户端还没来
(3)其他,根据错误码解决
*/
//创建客户端socket和相应的事件 (参数2需要)
g_allSock[g_count] = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
g_allOlp[g_count].hEvent = WSACreateEvent();
//创建字符数组 (参数3需要)
char str[1024] = { 0 };
DWORD dwRecvcount; //参数7需要
//投递AcceptEx
BOOL bRes = AcceptEx(g_allSock[0], g_allSock[g_count], str, 0, sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16, &dwRecvcount, &g_allOlp[0]);
if (TRUE == bRes)
{
//立即完成了
//投递Recv
printf("accept\n");
PostSend(g_count);
PostRecv(g_count);
//根据情况投递send
//客户端适量++
g_count++;
//投递accept
PostAccept();
return 0;
}
else
{
int a = WSAGetLastError();
if (ERROR_IO_PENDING == a)
{
//延迟处理
return 0;
}
else
{
return a;
}
}
}
int PostRecv(int index)
{
/*
作用:投递异步接收信息
参数1:客户端socket
参数2:接收后的信息存储buffer WSABUF struct _WSABUF{ULONG len; CHAR *buf} 成员1:字节数 成员2:指向字符数组的指针
参数3:参数2是个WSABUF的个数 1个
参数4: 1.接收成功的话,这里装着成功接收到的字节数
2.参数6重叠结构不为NULL的时候,此参数可以设置为NULL
参数5: 1.指向用于修改WSARecv函数调用行为的标志的指针
2.MSG_PEEK 协议缓冲区信息复制出来,不删除,跟recv参数5一样
3.MSG_OOB 带外数据
4.MSG_PUSH_IMMEDIATE 通知传送尽快完成(1)比如传输10M数据,一次只能传1M,这个包要拆成10份发送,第一份发送中,后面9份要排队等待,指定了这个标记,那么指示了快点,别等了,那么没被发送的就被舍弃了,从而造成了数据发送缺失
(2)该参数不建议用于多数据的发送 聊天的那种没问题,发个文件什么的就不建议了
(3)提示系统尽快处理,所以能减少一定的延迟
5.MSG_WAITALL 呼叫者提供的缓冲区已满,连接已关闭,请求已取消或发生错误 才把数据发送出去
6.MSG_PARTIIAL 传出的(send指定,recv收入不指定) 表示咱们此次接收到的数据是客户端发来的一部分,接下来接收下一部分
参数6:重叠结构
参数7:回调函数 完成例程形式使用 事件形式可以不使用 设置NULL
返回值:1.立即发生 0 计算机比较闲,立刻就发送出去了
2.SOCKET_ERROR int a = WSAGetLastError() a == WSA_IO_PENDING表示你自己去干把
*/
WSABUF wsabuf;
wsabuf.buf = g_strRecv;
wsabuf.len = MAX_RECV_COUNT;
DWORD dwRecvCount;
DWORD dwflag = 0;
int nRes = WSARecv(g_allSock[index], &wsabuf, 1, &dwRecvCount, &dwflag, &g_allOlp[index], NULL);
if (0 == nRes)
{
//立即完成
//打印信息
printf("%s\n", wsabuf.buf);
memset(g_strRecv, 0, MAX_RECV_COUNT);
//根据情况投递send
//对自己投递接收
PostRecv(index);
return 0;
}
else
{
int a = WSAGetLastError();
if (ERROR_IO_PENDING == a)
{
//延迟处理
return 0;
}
else
{
return a;
}
}
return 0;
}
int PostSend(int index)
{
WSABUF wsabuf;
wsabuf.buf = "你好";
wsabuf.len = MAX_RECV_COUNT;
DWORD dwSendCount; //成功发送的字节数
DWORD dwflag = 0; //函数调用行为的标志
int nRes = WSASend(g_allSock[index], &wsabuf, 1, &dwSendCount, dwflag, &g_allOlp[index], NULL);
if (0 == nRes)
{
//立即完成
//打印信息
printf("send成功\n");
return 0;
}
else
{
int a = WSAGetLastError();
if (ERROR_IO_PENDING == a)
{
//延迟处理
return 0;
}
else
{
return a;
}
}
return 0;
}
<file_sep>/3.事件选择模型/增大处理事件的数量之一组一组询问.c
//时间:2019年8月5日23:33:27
//事件选择模型
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
//定义事件集合以及socket集合的结构体
struct fd_es_set
{
unsigned short count;
SOCKET sockall[WSA_MAXIMUM_WAIT_EVENTS];
WSAEVENT eventall[WSA_MAXIMUM_WAIT_EVENTS];
};
//一组一组询问,定义成结构体数组
struct fd_es_set esSet[20]; //结构体数组
//回调函数
BOOL WINAPI fun(DWORD dwCtrlType)
{
switch (dwCtrlType)
{
case CTRL_CLOSE_EVENT:
for (int j = 0; j < 20; j++)
{
for (int i = 0; i < esSet[j].count; i++)
{
closesocket(esSet[j].sockall[i]);
WSACloseEvent(esSet[j].eventall[i]);
}
}
break;
}
return TRUE;
}
int main()
{
//控制台退出 主函数投递一个监视
SetConsoleCtrlHandler(fun, TRUE);
//打开网络库
WSADATA wsadata;
int nRes = WSAStartup(MAKEWORD(2, 2), &wsadata);
if (0 != nRes)
{
printf("创建失败,错误码为%d\n", WSAGetLastError());
return 0;
}
//校验版本
if (2 != HIBYTE(wsadata.wVersion) || 2 != LOBYTE(wsadata.wVersion))
{
printf("版本错误\n");
WSACleanup();
return 0;
}
//创建服务器Socket
SOCKET socketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == socketServer)
{
printf("创建服务器Socket失败\n");
WSACleanup();
return 0;
}
//绑定IP地址和端口
struct sockaddr_in socketMsg;
socketMsg.sin_family = AF_INET;
socketMsg.sin_port = htons(12345);
socketMsg.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (SOCKET_ERROR == bind(socketServer, (const struct sockaddr*)&socketMsg, sizeof(socketMsg)))
{
printf("绑定IP地址和端口出现错误,错误码为%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//监听
if (SOCKET_ERROR == listen(socketServer, SOMAXCONN))
{
printf("监听失败,错误码为%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//一组一组询问,定义成结构体数组
//struct fd_es_set esSet[20]; //结构体数组
//memset(esSet, 0, sizeof(struct fd_es_set)*20); //memset:将esSet当前位置后面的sizeof(struct fd_es_set)*20个字节用0替换,并返回esSet
//创建事件
WSAEVENT eventServer = WSACreateEvent();
if (WSA_INVALID_EVENT == eventServer)
{
printf("创建事件失败,错误码为%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//绑定并投递 WSAEventSelect
if (SOCKET_ERROR == WSAEventSelect(socketServer, eventServer, FD_ACCEPT))
{
printf("绑定事件失败,错误码为%d\n", WSAGetLastError());
//释放事件句柄
WSACloseEvent(eventServer);
//释放socket
closesocket(socketServer);
//清理网络库
WSACleanup();
}
//装进去
esSet[0].eventall[esSet[0].count] = eventServer;
esSet[0].sockall[esSet[0].count] = socketServer;
esSet[0].count++;
//一组一组处理:(1)单线程,一组一组顺序处理 (2)创建多个线程,每个线程处理一个事件表,最大64,服务器socket只有一个,accept放在第一个线程,其他线程处理read,write,close就行
while (1)
{
//询问事件
for (int j = 0; j < 20; j++) //单线程,一组一组顺序处理
{
if (0 == esSet[j].count) //该组有效事件如果为0则跳到下一次循环
{
continue;
}
DWORD nRes = WSAWaitForMultipleEvents(esSet[j].count, esSet[j].eventall, FALSE, 0, FALSE);
if (WSA_WAIT_FAILED == nRes)
{
printf("询问事件失败,错误码为%d\n", WSAGetLastError());
break;
}
if (WSA_WAIT_TIMEOUT == nRes)
{
continue;
}
DWORD nIndex = nRes - WSA_WAIT_EVENT_0; //此时得到的是有信号事件中索引值最小的
//有序处理方法2,//此索引值前的事件都是无信号的,可以直接从此处开始循环接下来的所有事件,处理有信号的事件,优化2比优化1更好一点
for (int i = nIndex; i < esSet[j].count; i++)
{
DWORD nRes = WSAWaitForMultipleEvents(1, &esSet[j].eventall[i], FALSE, 0, FALSE);
if (WSA_WAIT_FAILED == nRes)
{
printf("询问事件失败,错误码为%d\n", WSAGetLastError());
continue;
}
//如果参数4写具体超时间隔,此时事件要加上超时判断
if (WSA_WAIT_TIMEOUT == nRes)
{
continue;
}
//列举事件,得到下标对应的具体操作
WSANETWORKEVENTS NetworkEvents;
if (SOCKET_ERROR == WSAEnumNetworkEvents(esSet[j].sockall[i], esSet[j].eventall[i], &NetworkEvents))
{
printf("得到下标对应的具体操作失败,错误码:%d\n", WSAGetLastError());
break;
}
if (NetworkEvents.lNetworkEvents & FD_ACCEPT)
{
if (0 == NetworkEvents.iErrorCode[FD_ACCEPT_BIT])
{
//正常处理
SOCKET socketClient = accept(esSet[j].sockall[i], NULL, NULL);
if (INVALID_SOCKET == socketClient)
{
continue;
}
//创建事件对象
WSAEVENT wsaClientEvent = WSACreateEvent();
if (WSA_INVALID_EVENT == wsaClientEvent)
{
closesocket(socketClient);
continue;
}
//投递给系统
if (SOCKET_ERROR == WSAEventSelect(socketClient, wsaClientEvent, FD_READ | FD_CLOSE | FD_WRITE))
{
closesocket(socketClient);
WSACloseEvent(wsaClientEvent);
continue;
}
//每组只能装64个,大于64个的话要装到下一组
for (int m = 0; m < 20; m++)
{
if (esSet[m].count < 64)
{
//装进结构体
esSet[m].sockall[esSet[m].count] = socketClient;
esSet[m].eventall[esSet[m].count] = wsaClientEvent;
esSet[m].count++;
break;
}
}
printf("accept event\n");
}
else
{
continue;
}
}
if (NetworkEvents.lNetworkEvents & FD_WRITE)
{
if (0 == NetworkEvents.iErrorCode[FD_WRITE_BIT])
{
if (SOCKET_ERROR == send(esSet[j].sockall[i], "connect success", strlen("connect success"), 0))
{
printf("send失败,错误码为:%d\n", WSAGetLastError());
continue;
}
printf("write event\n");
}
else
{
printf("socket error套接字错误,错误码为:%d\n", NetworkEvents.iErrorCode[FD_WRITE_BIT]);
}
}
if (NetworkEvents.lNetworkEvents & FD_READ)
{
if (0 == NetworkEvents.iErrorCode[FD_READ_BIT])
{
char strRecv[1500] = { 0 };
if (SOCKET_ERROR == recv(esSet[j].sockall[i], strRecv, 1499, 0))
{
printf("recv失败,错误码为:%d\n", WSAGetLastError());
continue;
}
printf("接收的数据:%s\n", strRecv);
}
else
{
printf("socket error套接字错误,错误码为:%d\n", NetworkEvents.iErrorCode[FD_READ_BIT]);
continue;
}
}
if (NetworkEvents.lNetworkEvents & FD_CLOSE)
{
//打印
printf("client close\n");
printf("client force out客户端强制退出,错误码:%d\n", NetworkEvents.iErrorCode[FD_CLOSE_BIT]);
//清理下线的客户端 套接字 事件
closesocket(esSet[j].sockall[i]);
esSet[j].sockall[i] = esSet[j].sockall[esSet[j].count - 1];
WSACloseEvent(esSet[j].eventall[i]);
esSet[j].eventall[i] = esSet[j].eventall[esSet[j].count - 1];
esSet[j].count--;
}
}
}
}
//释放socket,释放事件句柄
for (int j = 0; j < 20; j++)
{
for (int i = 0; i < esSet[j].count; i++)
{
closesocket(esSet[j].sockall[i]);
WSACloseEvent(esSet[j].eventall[i]);
}
}
//清理网络库
WSACleanup();
system("pause");
return 0;
}
*/
/*
->事件机制 事件选择模型 ->重叠I/O模型
C/S -> select
->消息机制 异步选择模型 ->完成端口模型
*/
<file_sep>/2.select模型/select.c
//时间:2019年7月30日16:32:25
/*
select模型
1.解决基本c / s模型中,accept recv傻等的问题 1)解决傻等阻塞
2)不解决执行阻塞 send recv accept在执行过程中都是阻塞的,所以注意,select模型是解决傻等的问题的,不解决这几个函数本身的阻塞问题
2.实现多个客户端链接,与多个客户端分别通信
3.用于服务器,客户端就不用这个了,因为只有一个socket 客户端recv等待的的时候,也不能send :只需要单独创建一根线程,recv放线程里
select模型逻辑
1.每个客户端都有socket, 服务器也有自己的socket, 将所有的socket装进一个数据结构里,即数组
2.通过select函数,遍历1中的socket数组,当某个socket有响应,select就会通过其参数 / 返回值反馈出来
3.做相应处理 1)如果检测到的是服务器socket, 那就是有客户端链接,调用accept
2)如果检测到的是客户端socket, 那就是客户端请求通信,调用send或recv
*/
//#define FD_SETSIZE 128 //FD_SETSIZE默认是64,可以在winsock2.h前声明这个宏,就可以让select模型处理更多的socket,不要过大,select原理就是遍历检测,越多肯定效率越低,延迟越大,select模型应用就是小用户量访问量
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h> //头文件
#pragma comment(lib, "ws2_32.lib") //库文件
fd_set allSockets;
//回调函数:系统调用我们的函数
BOOL WINAPI fun(DWORD dwCtrlType)
{
switch (dwCtrlType)
{
case CTRL_CLOSE_EVENT:
//释放所有socket
for (u_int i = 0; i < allSockets.fd_count; i++) //这边要调用allSockets所以定义成全局的
{
closesocket(allSockets.fd_array[i]);
}
//清理网络库
WSACleanup();
}
return TRUE;
}
int main()
{
//控制台窗口点X退出,让操作系统帮我们释放数据 主函数投递一个监视
SetConsoleCtrlHandler(fun, TRUE); //(fun true):操作系统执行默认的函数处理默认的东西,然后调用fun函数,把我们的东西处理掉进行释放 如果fun改为NULL,系统会做一些默认的事
//(fun false):操作系统执行默认的函数处理默认的东西,不调用fun函数
//打开网络库
WSADATA wsadata;
if (0 != WSAStartup(MAKEWORD(2, 2), &wsadata))
{
printf("网络库打开失败!\n");
return 0;
}
//校验版本号
if (2 != HIBYTE(wsadata.wVersion) || 2 != LOBYTE(wsadata.wVersion))
{
printf("版本号有误!\n");
if (SOCKET_ERROR == WSACleanup())
printf("错误码:%d\n", WSAGetLastError());
return 0;
}
//创建服务器socket
SOCKET socketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //地址类型,套接字类型,协议类型
if (INVALID_SOCKET == socketServer)
{
printf("服务器socket创建失败,错误码:%d\n", WSAGetLastError());
WSACleanup();
return 0;
}
//绑定IP地址和端口
struct sockaddr_in socketMsg;
socketMsg.sin_family = AF_INET; //协议
socketMsg.sin_port = htons(12345); //端口
socketMsg.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //地址
if (SOCKET_ERROR == bind(socketServer, (const struct sockaddr*)&socketMsg, sizeof(socketMsg)))
{
printf("绑定失败,错误码:%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//开始监听,监听客户端来的链接
if (SOCKET_ERROR == listen(socketServer, SOMAXCONN)) //参数2是挂起连接队列的最大长度,SOMAXCONN是让系统自动选择最合适的个数
{
printf("监听失败,错误码:%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
/*
select
第一步:定义一个装客户端socket结构
fd_set allSockets;
FD_ZERO(&allSockets); 集合清零
FD_SET(socketServer, &allSockets); 集合添加一个元素 当socket数量不足64且此socket不存在的时候
FD_CLR(socketServer, &clientSockets); 集合中删除指定的socket 我们要手动释放closesocket
int a = FD_ISSET(socketServer, &clientSockets); 判断一个socket是否在集合中 不在返回0,在返回非0
第二步:select
作用:监视socket集合,如果某个socket发生事件(链接或者收发数据),通过返回值以及参数告诉我们
select(); 参数2处理accept与recv傻等问题,这是select结构比基本模型得最大得作用,参数3,4一般可以为NULL
参数1. 忽略,此处填0,为了兼容berkeley sockets 向下兼容旧标准
参数2.(1)检查是否有可读的socket:即客户端发来消息了,该socket就会被设置
(2)&setRead 初始化为所有的socket,通过select投放给系统,系统将有事件发生的socket再赋值回来,调用后,这个参数就只剩下有请求的socket
参数3.(1)检查是否有可写的socket:就是可以给哪些客户端套接字发消息,即send,只要链接成功建立起来,那该客户端套接字就是可写的
(2)&setWrite 初始化为所有的socket,通过select投放给系统,系统将可写的socket再赋值回来,调用后,这个参数就是装着可以被send数据的客户端socket.一般我们就直接send了,所以这个参数逻辑上,用的不是非常多
参数4.(1)检查套接字上的异常错误:用法跟2.3一样,将有异常错误的套接字重新装进来,反馈给我们
(2)得到异常套接字上的具体错误码 getsockopt
参数5.(1)最大等待时间 比如当客户端没有请求时,那么select函数可以等一会,一段时间过后还没有,就继续执行select下面的语句,如果有就立即执行下面的语句
(2)TIMEVAL 两个成员:tv_sec 秒,tv_usec 微秒 如果是0 0 则是非阻塞状态,立即返回 如果3 4 就是无客户端响应的情况下等待3秒4微妙
(3)NULL select完全阻塞 直到客户端有反应,才继续
返回值(1)0 客户端再等待时间内没有反应 处理 continue就行了 (2)>0 有客户端请求交流了 (3)SOCKET_ERROR 发生了错误, WSAGetLastError()得到错误码
*/
//fd_set allSockets;
FD_ZERO(&allSockets);
FD_SET(socketServer, &allSockets); //服务器装进去
while (1)
{
//临时socket集合,调用select函数后只返回有响应的socket,集合中的socket就变了,所以不能直接使用保存所有socket的allsockets
fd_set readSockets = allSockets; //select处理参数2,可读的socket集合
fd_set writeSockets = allSockets; //select处理参数3,可写的socket集合
//FD_CLR(socketServer, &writeSockets); //测试参数2时,可把服务器socket先删除,也可没有,不去删除
fd_set errorSockets = allSockets; //select处理参数4,异常错误集合
//时间段
struct timeval st;
st.tv_sec = 3;
st.tv_usec = 0;
//select
int nRes = select(0, &readSockets, &writeSockets, &errorSockets, &st); //测试:参数2.3.4分别测试,测试参数3时只要有客户端链接服务器,select函数结果就会大于0,循环执行大于0的分支
if (0 == nRes) //没有响应
{
continue;
}
else if (nRes > 0) //有响应
{
//处理异常错误集合
for (u_int i = 0; i < errorSockets.fd_count; i++)
{
char str[100] = { 0 };
int len = 99;
if (SOCKET_ERROR == getsockopt(errorSockets.fd_array[i], SOL_SOCKET, SO_ERROR, str, &len))
{
printf("无法得到错误信息\n");
}
printf("%s\n", str);
}
//处理可写集合
for (u_int i = 0; i < writeSockets.fd_count; i++)
{
//printf("服务器%d,%d:可写\n", socketServer, writeSockets.fd_array[i]); //printf测试,发现printf不会打印writeSockets中的服务器socket
if (SOCKET_ERROR == send(writeSockets.fd_array[i], "ok", 2, 0)) //如果有发送信息send返回值只有大于0和SOCKET_ERROR两种情况,客户端正常退出或强制退出时此处send都返回SOCKET_ERROR
{ //如果什么都不发,send返回0
int a = WSAGetLastError();
}
}
//处理可读集合,客户端关闭退出也在这处理
for (u_int i = 0; i < readSockets.fd_count; i++)
{
if (readSockets.fd_array[i] == socketServer)
{
//accept
SOCKET socketClient = accept(socketServer, NULL, NULL);
if (INVALID_SOCKET == socketClient)
{
//链接出错
continue;
}
FD_SET(socketClient, &allSockets);
printf("链接成功\n");
//send
}
else
{
//客户端
char strBuf[1500] = { 0 };
int nRecv = recv(readSockets.fd_array[i], strBuf, 1500, 0);
if (0 == nRecv)
{
//客户端下线了
//从集合中拿掉
SOCKET socketTemp = readSockets.fd_array[i];
FD_CLR(readSockets.fd_array[i], &allSockets);
//释放
closesocket(socketTemp);
}
else if (nRecv > 0)
{
//接收到了消息
printf(strBuf);
}
else //SOCK_ERROR
{
//强制下线也是出错 10054
int a = WSAGetLastError();
switch (a)
{
case 10054:
{
SOCKET socketTemp = readSockets.fd_array[i];
FD_CLR(readSockets.fd_array[i], &allSockets);
closesocket(socketTemp);
break;
}
}
}
}
}
}
else
{
//发生错误了
//根据具体的错误码进行处理,包括结束while循环,或者等待或者continue下一次循环
break;
}
}
//释放所有socket
for (u_int i = 0; i < allSockets.fd_count; i++)
{
closesocket(allSockets.fd_array[i]);
}
//清理网络库
WSACleanup();
system("pause");
return 0; //正常关闭控制台窗口
}
/*
流程总结
socket集合 select判断有没有响应的 1.返回0:没有,继续挑
2.返回>0:有响应的 (1)可读的(accept, recv)
(2)可写的 send 不是非得从此处调用send
(3)异常的 getsockopt
3.SOCKET_ERROR 函数本身执行错误
执行阻塞
假如发送1500个字节,send把1500个字节复制到协议缓冲区,复制的过程是卡死的,如果复制中途有客户端响应处理不了,给多个客户端send消息只能一个个send,
我们自己写的函数也是执行阻塞,但是调用频率低,也不会有大量的数据复制,send / recv调用频率高,可能导致等待时间太久
select是阻塞的 1.不等待 执行阻塞 + 时间非阻塞状态 参数5时间设置为0,遍历完就立即下一次循环,但是遍历集合时不能干别的 傻等 没有目标的等待
2.半等待 执行阻塞 + 软阻塞 参数5时间设置为不为0,比如3s,遍历集合完再等待3s 傻等 没有目标的等待
3.全等待 执行阻塞 + 硬阻塞 参数5时间设置为NULL, 直到有客户端发消息或链接 死等 等到可用的目标响应
*/
<file_sep>/6.完成端口/完成端口.c
//时间:2019年8月13日20:23:23
//完成端口
/*
完成端口也是windows的一种机制 在重叠IO模型基础上的优化
重叠IO存在问题 1.事件通知 (1)无序
(2)循环询问 延迟高,做了很多无用功
(3)采用多线程 管理很难合理 数量太多
2.完成例程 (1)线程数量太多 每个客户端都有一个线程去调用回调函数
3.线程过多 (1)切换线程消耗大量CPU资源/时间
(2)为什么 CPU单核中多线程执行状况 1)在一个时间片周期内,每个线程执行一样的时间
2)假设一个时间片周期是1ms,有100个线程在单核上运行,那么这些线程一个时间周期内分得0.01ms执行时间,时间到,不管执行到什么位置,
立即切换下一个线程执行,如此,这些线程就在不停的切换中执行,由于速度太快,咱们人分辨不出来,所以就展现出同时运行的效果 大家电脑开太多软件会卡,这就是其中一个原因 单核是伪多线程 骗人的
所以同一个应用程序,在单核中执行多个线程,理论上还是单线程的执行效率,假设一条线程执行需要1s,那么10个线程,总共执行完需要10s,单核上运行10条,还要加上线程切换的时间,所以大于10s
多核中多线程的执行状况 1)多个核的线程,达到了真正的同时运行
2)所以假设一台电脑是8核CPU,那么一个程序创建8条线程,操作系统会自动把8条线程分给8个核,从而达到了最高的效率
正常情况下,电脑运行着很多的软件,有几千个线程同时运行 系统首先是以软件为单位进行线程分配执行的
4.最优线程数是多少? (1)理论上跟CPU核数一样是最好的
(2)到底是几个 1)网上有几种答案 CPU核数 CPU核数*2 CPU核数*2+2
2)CPU有个重要参数就是n核m线程 比如i7 700K 4核8线程 4核指物理四核,也就是CPU真实核数 理论上最佳的线程数是4个,但是因特尔在此使用了超线程技术,使得物理单核可以模拟出双核的性能,核数是8的来历,所以在应用中跟8核没啥两样 这应该就是CPU核数*2的来历
i7 9700K 8核8线程 这个就是没有使用超线程技术,单核单线程 所以线程数=CPU核数
(3)CPU核数*2+2 这个数量,是根据实际应用中的经验得来 线程函数中可能会调用Sleep(),WSAWaitForMultipleEvents()这类函数,会使线程挂起(不占CPU时间片),从而使得CPU某个核空闲了,这就不好了,所以一般多建个两三根,以解决此类情况,让CPU不停歇,从而在整体上保证程序的执行效率
(4)引申理解 1)某一个程序在CPU一个周期分的时间越多(创建的线程更多),那就越快 其他线程分的时间就越少了
2)考虑切换时间 数量就会有个瓶颈 系统性能分析工具
3)根据出发点不同创建对应数量的线程
完成端口 1.模仿消息队列,创造一个通知队列,系统创建 保证有序,不做无用功
2.创建最佳数量的线程 充分利用CPU的性能
代码逻辑 原理: 1.将重叠套接字(客户端+服务器)与一个完成端口(一个类型的变量)绑定在一起
2.使用AcceptEx, WSARecv, WSASend投递请求
3.当系统异步完成请求,就会把通知存进一个队列,我们就叫他通知队列,该队列由操作系统创建,维护
4.完成端口可以理解为这个队列的头,我们通过GetQueueCompletionStatus从队列头往外拿,一个一个处理
代码: 1.创建完成端口 CreateIoCompletionPort
2.将完成端口与socket绑定 CreateIoCompletionPort
3.创建指定数目的线程 (1)CPU核数一样 CreateThread
(2)线程内部 1)GetQueueCompletionStatus 2)分类处理
4.使用AcceptEx, WSARecv, WSASend投递请求
5.主线程阻塞 (不阻塞的话程序就执行完了,软件就关闭了)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <mswsock.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")
#define MAX_COUNT 1024
#define MAX_RECV_COUNT 1500
SOCKET g_allsockets[MAX_COUNT];
OVERLAPPED g_allOlp[MAX_COUNT];
int g_count;
//int g_newsocketID;
HANDLE hPort;
HANDLE *pThread;
int nProcessorsCount;
//接收缓冲区
char g_strrecv[1500] = {0};
int PostAccept(void); //C语言加void表示不接受参数, 如果为空,表示参数个数不确定
int PostRecv(int index);
int PostSend(int index);
void Clear(void)
{
for (int i = 0; i < g_count; i++)
{
if (0 == g_allsockets[i])
continue;
closesocket(g_allsockets[i]);
WSACloseEvent(g_allOlp[i].hEvent);
}
}
BOOL g_flag = TRUE;
//线程函数
DWORD WINAPI ThreadProc(LPVOID lpPrameter);
//回调函数 (点控制台退出)
BOOL WINAPI fun(DWORD dwCtrlType)
{
switch (dwCtrlType)
{
case CTRL_CLOSE_EVENT:
CloseHandle(hPort);
Clear();
g_flag = FALSE; //控制台点×退出时关闭子线程
//释放线程句柄
for (int i = 0; i < nProcessorsCount; i++)
{
//TerminateThread();
CloseHandle(pThread[i]);
}
free(pThread);
break;
}
return TRUE;
}
int main()
{
//控制台退出 主函数投递一个监视
SetConsoleCtrlHandler(fun, TRUE);
WSADATA wsadata;
if (0 != WSAStartup(MAKEWORD(2, 2), &wsadata))
{
printf("网络库打开失败\n");
return -1;
}
if (2 != HIBYTE(wsadata.wVersion) || 2 != LOBYTE(wsadata.wVersion))
{
printf("版本错误\n");
WSACleanup();
return -1;
}
SOCKET socketServer = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
if (INVALID_SOCKET == socketServer)
{
printf("创建服务器socket失败,错误码:%d\n", WSAGetLastError());
WSACleanup();
return -1;
}
struct sockaddr_in socketServerMsg;
socketServerMsg.sin_family = AF_INET;
socketServerMsg.sin_port = htons(12345);
socketServerMsg.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (SOCKET_ERROR == bind(socketServer, (struct sockaddr *)&socketServerMsg, sizeof(socketServerMsg)))
{
printf("绑定IP和端口失败,错误码:%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return -1;
}
/*
功能:1.创建一个完成端口 2.将完成端口与SOCKET绑定再一起
参数1: 1.创建完成端口 INVALID_HANDLE_VALUE (1)此时参数2为NULL
(2)参数3忽略 填个0
2.绑定的话 服务器socket
参数2:1.创建完成端口 NULL
2.绑定的话 完成端口变量
参数3:1.创建完成端口 0
2.绑定的话 (1)再次传递socketServer 也可以传递一个下标,做编号
(2)与系统接收到的对应的数据关联在一起
参数4:1.创建完成端口 (1)允许此端口上最多同时运行的线程数量
(2)填CPU的核数即可 咱们自己获取 GetSystemInfo
(3)可填写0 表示默认是CPU核数
2.绑定的话 (1)忽略此参数,填0就行了
(2)当说忽略的时候,我们填啥都是没有作用的,我们一般填0
返回值:1.成功 (1)当参数2为NULL, 返回一个新的完成端口
(2)当参数2不为NULL 返回自己
(3)当参数1为socket 返回与socket绑定后的端口
2.失败返回0 (1)GetLastError()
(2)完成端口也是windows的一种机制 不是网络专属,文件操作均可以
*/
g_allsockets[g_count] = socketServer;
g_allOlp[g_count].hEvent = WSACreateEvent();
g_count++;
//创建完成端口
hPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
if (0 == hPort)
{
int a = GetLastError();
printf("%d\n", a);
closesocket(socketServer);
WSACleanup();
return -1;
}
//绑定
HANDLE hPort1 = CreateIoCompletionPort((HANDLE)socketServer, hPort, 0, 0);
if (hPort1 != hPort)
{
int a = GetLastError();
printf("%d\n", a);
CloseHandle(hPort);
closesocket(socketServer);
WSACleanup();
return -1;
}
if (SOCKET_ERROR == listen(socketServer, SOMAXCONN))
{
printf("监听失败,错误码:%d\n", WSAGetLastError());
CloseHandle(hPort);
closesocket(socketServer);
WSACleanup();
return -1;
}
if (0 != PostAccept())
{
Clear();
WSACleanup();
return -1;
}
//创建线程数量有了
SYSTEM_INFO SystemProcessorsCount;
GetSystemInfo(&SystemProcessorsCount);
nProcessorsCount = SystemProcessorsCount.dwNumberOfProcessors;
//创建
/*
功能:创建一根线程
参数1:1.线程句柄是否被继承 NULL不继承
2.指定线程的执行权限 NULL默认的
参数2:1.线程栈大小 填0,系统使用默认大小 1M
2.字节为单位
参数3:线程函数地址 (1)DWORD WINAPI ThreadProc(LPVOID lpPrameter)
(2)参数LPVOID lpPrameter,就是参数4传递进来的数据
参数4:外部给线程传递数据
参数5:1. 0 线程立即执行
2. CREATE_SUSPENDED 线程创建完挂起状态,调用ResumeThread启动函数
3. STACK_SIZE_PARAM_IS_A_RESERVATION (1)设置了,参数2就是栈保留大小 虚拟内存上栈的大小 1M
(2)未设置,就是栈提交大小 物理内存上栈的大小 4KB
参数6:线程ID 可以填NULL
返回值:1.成功 返回线程句柄 (1)内核对象
(2)最后要释放 CloseHandle
2.失败 NULL GetLastError 得到错误码
*/
pThread = (HANDLE)malloc(sizeof(HANDLE) * nProcessorsCount);
for (int i = 0; i < nProcessorsCount; i++)
{
pThread[i] = CreateThread(NULL, 0, ThreadProc, hPort, 0, NULL);
if (NULL == pThread[i])
{
int a = GetLastError();
printf("%d\n", a);
CloseHandle(hPort);
closesocket(socketServer);
WSACleanup();
return -1;
}
}
//阻塞
while (1)
{
Sleep(1000); //主线程挂起1s,不占用CPU执行周期,腾出1S给CPU,处理其他线程,对CPU友好
}
//释放线程句柄
for (int i = 0; i < nProcessorsCount; i++)
{
CloseHandle(pThread[i]);
}
free(pThread);
CloseHandle(hPort);
Clear();
WSACleanup();
system("pause");
return 0;
}
//线程函数
DWORD WINAPI ThreadProc(LPVOID lpPrameter)
{
/*
无通知时,线程挂起,不占用CPU的时间,非常棒
功能:尝试从指定的I/O完成端口取I/O完成数据包
参数1:完成端口 咱们要从主函数传进来
参数2:接收或者发送的字节数
参数3:完成端口函数参数3传进来的
参数4:重叠结构
参数5: 1.等待时间 当没有客户端响应时候,通知队列里什么都没有,咱们这里也get不到什么东西,那么等一会还是一直等
2.INFINITE 一直等,闲着也是闲着
返回值:1.成功返回TRUE
2.失败返回FALSE GetLastError
continue
*/
HANDLE port = (HANDLE)lpPrameter;
DWORD NumberOfBytes;
ULONG_PTR index;
LPOVERLAPPED lpOverlapped;
while (g_flag)
{
BOOL bFlag = GetQueuedCompletionStatus(port, &NumberOfBytes, &index, &lpOverlapped, INFINITE);
if (FALSE == bFlag)
{
int a = GetLastError();
if (64 == a)
{
printf("force close\n");
}
printf("错误码:%d\n", a);
continue;
}
//处理
//accept
if (0 == index)
{
printf("accept\n");
//绑定到完成端口
HANDLE hPort1 = CreateIoCompletionPort((HANDLE)g_allsockets[g_count], hPort, g_count, 0);
if (hPort1 != hPort)
{
int a = GetLastError();
printf("%d\n", a);
closesocket(g_allsockets[g_count]);
continue;
}
PostSend(g_count);
//新客户端投递recv
PostRecv(g_count);
g_count++;
PostAccept();
}
else
{
if (0 == NumberOfBytes)
{
//客户端下线
printf("close\n");
//关闭
closesocket(g_allsockets[index]);
WSACloseEvent(g_allOlp[index].hEvent);
g_allsockets[index] = 0; //socket跟下标绑定了,不能直接把最后一个socket赋值过来,给个特殊值0,之后释放0就别释放了
g_allOlp[index].hEvent = NULL;
}
else
{
if (g_strrecv[0] != 0)
{
//收到recv
printf("%s\n", g_strrecv);
memset(g_strrecv, 0, sizeof(g_strrecv));
//投递
PostRecv(index);
}
else
{
//send
printf("send ok\n");
}
}
}
}
return 0;
}
int PostAccept()
{
g_allsockets[g_count] = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
g_allOlp[g_count].hEvent = WSACreateEvent();
//g_newsocketID = g_count; //PostRecv和PostSend应该是传递最新一个socket,而不是socket有效个数,因为删了socket对导致有效个数g_count变化,此时再传递g_count会出错 不行还是有问题
char str[1500] = {0};
DWORD recv_count;
BOOL bFlag = AcceptEx(g_allsockets[0], g_allsockets[g_count], str, 0, sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16, &recv_count, &g_allOlp[0]);
//完成端口不需要区分立即完成还是异步完成,只要完成就会产生通知,通知就会装进通知队列,线程就能取出通知
//if (TRUE == bFlag)
//{
// HANDLE hPort1 = CreateIoCompletionPort((HANDLE)g_allsockets[g_count], hPort, g_count, 0);
// if (hPort1 != hPort)
// {
// int a = GetLastError();
// printf("%d\n", a);
// closesocket(g_allsockets[g_count]);
// //continue;
// }
// printf("accept");
// PostRecv(g_count);
// PostSend(g_count);
// g_count++;
// PostAccept();
// return 0;
//}
//else
//{
// int a = WSAGetLastError();
// if (ERROR_IO_PENDING == a)
// {
// return 0;
// }
// else
// {
// return a;
// }
//}
int a = WSAGetLastError();
if (ERROR_IO_PENDING != a)
{
//函数执行出错
return -1;
}
return 0;
}
int PostRecv(int index)
{
WSABUF wsabuf;
wsabuf.buf = g_strrecv;
wsabuf.len = MAX_RECV_COUNT;
DWORD read_count;
DWORD flag = 0;
int nRes = WSARecv(g_allsockets[index], &wsabuf, 1, &read_count, &flag, &g_allOlp[index], NULL);
//完成端口不需要区分立即完成还是异步完成,只要完成就会产生通知,通知就会装进通知队列,线程就能取出通知
/*if (0 == nRes)
{
printf("%s\n", g_strrecv);
memset(g_strrecv, 0, MAX_RECV_COUNT);
PostRecv(index);
return 0;
}
else
{
int a = WSAGetLastError();
if (ERROR_IO_PENDING == a)
{
return 0;
}
else
{
return a;
}
}*/
int a = WSAGetLastError();
if (ERROR_IO_PENDING != a) //有问题:WSASend函数执行立即完成nRes=0, 此时取错误码a=0, a != ERROR_IO_PENDING也会进入if内部?
{
//函数执行出错
return -1;
}
return 0;
}
int PostSend(int index)
{
WSABUF wsabuf;
wsabuf.buf = "链接成功";
wsabuf.len = MAX_RECV_COUNT;
DWORD send_count;
DWORD flag = 0;
int nRes = WSASend(g_allsockets[index], &wsabuf, 1, &send_count, flag, &g_allOlp[index], NULL);
//完成端口不需要区分立即完成还是异步完成,只要完成就会产生通知,通知就会装进通知队列,线程就能取出通知
/*if (0 == nRes)
{
printf("send成功\n");
return 0;
}
else
{
int a = WSAGetLastError();
if (ERROR_IO_PENDING == a)
{
return 0;
}
else
{
return a;
}
}*/
int a = WSAGetLastError(); //有问题:WSASend函数执行立即完成nRes=0, 此时取错误码a=0, a != ERROR_IO_PENDING也会进入if内部?
if (ERROR_IO_PENDING != a)
{
//延迟处理
//函数执行出错
return -1;
}
return 0;
}<file_sep>/3.事件选择模型/eventSelect.c
//时间:2019年8月3日16:46:15
//事件选择模型
/*
windows处理用户行为的两种方式: 1.消息机制:核心是消息队列 处理过程:所有的用户操作,比如点鼠标,摁键盘,点软件上的按钮。。等等,所有操作均依次按顺序被记录,装进一个队列
(整体使用) 特点:(1)消息队列由操作系统维护,咱们做的操作,然后把消息取出来,分类处理
(2)有先后顺序
其他:win32,MFC都是基于消息队列,异步选择模型也是基于这个消息队列的
2.事件机制:核心是事件集合 处理过程:(1)根据需求,我们为用户的特定操作绑定一个事件,事件由我们自己调用API创建,需要多少创建多少
(局部使用) (2)将事件投递给系统,系统就帮咱们监视着,所以不能无限创建,太多系统运行就卡了
(3)如果操作发生了,比如用户点击鼠标了,那么对应的事件就会被置成有信号,也就是类似1变2了,用个数标记
(4)我们直接获取到有信号的事件,然后处理
特点:(1)所有事件都是咱们自己定义的,系统只是帮咱们置有无信号,所以我们自己掌管定义
(2)无序的
其他:事件选择就是应用这个
事件选择的逻辑 WSAEventSelect 整体逻辑跟select差不多,进化版
第一步:创建一个事件对象(变量) WSACreateEvent
第二步:为每一个事件对象绑定个socket以及操作accept,read,close并投递给系统
(1)投递给系统,咱们就完全不用管了,系统自己监管 ,咱们就去做别的事去了
(2)WSAEventSelect
第三步:查看事件是否有信号 WSAWaitForMultipleEvents
第四步:有信号的话就分类处理 WSAEnumNetworkEvents
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
//定义事件集合以及socket集合的结构体
struct fd_es_set
{
unsigned short count;
SOCKET sockall[WSA_MAXIMUM_WAIT_EVENTS]; //WSAWaitForMultipleEvents所能询问的一组事件的最大个数是WSA_MAXIMUM_WAIT_EVENTS,是64,所以事件数组最大也设置64,多了也询问不了,所以可以多组多次询问或者一次询问一个,不以组的形式询问
WSAEVENT eventall[WSA_MAXIMUM_WAIT_EVENTS];
};
struct fd_es_set esSet;
//回调函数
BOOL WINAPI fun(DWORD dwCtrlType)
{
switch (dwCtrlType)
{
case CTRL_CLOSE_EVENT:
for (int i = 0; i < esSet.count; i++)
{
closesocket(esSet.sockall[i]);
WSACloseEvent(esSet.eventall[i]);
}
break;
}
return TRUE;
}
int main()
{
//控制台退出 主函数投递一个监视
SetConsoleCtrlHandler(fun, TRUE);
//打开网络库
WSADATA wsadata;
int nRes = WSAStartup(MAKEWORD(2, 2), &wsadata);
if (0 != nRes)
{
printf("创建失败,错误码为%d\n", WSAGetLastError());
return 0;
}
//校验版本
if (2 != HIBYTE(wsadata.wVersion) || 2 != LOBYTE(wsadata.wVersion))
{
printf("版本错误\n");
WSACleanup();
return 0;
}
//创建服务器Socket
SOCKET socketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == socketServer)
{
printf("创建服务器Socket失败\n");
WSACleanup();
return 0;
}
//绑定IP地址和端口
struct sockaddr_in socketMsg;
socketMsg.sin_family = AF_INET;
socketMsg.sin_port = htons(12345);
socketMsg.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (SOCKET_ERROR == bind(socketServer, (const struct sockaddr*)&socketMsg, sizeof(socketMsg)))
{
printf("绑定IP地址和端口出现错误,错误码为%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//监听
if (SOCKET_ERROR == listen(socketServer, SOMAXCONN))
{
printf("监听失败,错误码为%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//struct fd_es_set esSet = {0}; 定义成全局变量以便回调函数使用
//创建事件
WSAEVENT eventServer = WSACreateEvent(); //成功返回一个事件
/*
WSAEVENT->HANDLE->void* 句柄:1.ID
2.内核对象: 操作系统是一个大的应用程序exe,运行360,QQ以及我们写的EventSelect可以理解为函数,在操作系统上运行该应用就类似于调用函数,
我们在EventSelect内定义a就相当于局部变量,内核对象相当于系统在系统的空间里申请的变量,相当于全局的,只能由操作系统申请以及操作
(1)由系统在内核申请
(2)由操作系统访问
(3)我们不能定位其内容,也不能修改,不能在编写其他程序去修改
1)void*是通用类型指针,不知道是什么类型,不能解引用取内容,只能先强转再解引用,不知道类型不能修改
2)对内核的保护,对规则的保护,从而使操作系统有序平稳有效的运行,而不会随便出问题
(4)调用系统函数创建,调用系统函数释放 如果我们没有调用释放,那么他可能就一直存在于内核,造成内核内存泄漏,占用的是操作系统的空间(全局的,所有程序都在用的),单单重启软件是没法释放的,这种只能重启电脑 (比如QQ申请12345端口,360就申请不了12345端口)
(5)内核对象有哪些:socket,thread,event,file都是内核对象(Kernel Objects)
*/
if (WSA_INVALID_EVENT == eventServer) //失败返回WSA_INVALID_EVENT
{
printf("创建事件失败,错误码为%d\n", WSAGetLastError());
closesocket(socketServer);
WSACleanup();
return 0;
}
//WSAResetEvent(eventServer); //将指定事件主动置成无信号 重置WSAEventSelect函数使用的事件对象状态的正确方法是将事件对象的句柄传递给hEventObject参数中的WSAEnumNetworkEvents函数,这将重置事件对象并以原子方式调整套接字上活动FD事件的状态
//WSASetEvent(eventServer); //将指定事件主动置成有信号
//绑定并投递 WSAEventSelect
if (SOCKET_ERROR == WSAEventSelect(socketServer, eventServer, FD_ACCEPT))
{
printf("绑定事件失败,错误码为%d\n", WSAGetLastError());
//释放事件句柄
WSACloseEvent(eventServer);
//释放socket
closesocket(socketServer);
//清理网络库
WSACleanup();
}
/*
功能:给事件绑上socket与操作码,并投递给操作系统
参数1:被绑定的socket 最终,每个socket都会绑定一个事件
参数2:事件对象 逻辑就是将参数1与参数2绑定在一起
参数3:具体事件: (1)FD_ACCEPT 有客户端链接 与服务器socket绑定
(2)FD_READ 有客户端发来消息 与客户端socket绑定 可多个属性并列用|,WSAEventSelect(,,FD_ACCEPT); WSAEventSelect(,,FD_READ);如果前后调用两次后一次绑定会覆盖掉前一次
(3)FD_CLOSE 客户端下线了 与客户端socket绑定 包含强制下线,正常下线
(4)FS_WRITE 可以给客户端发信息 与客户端socket绑定 会在accept后立即产生该信号,可以说明客户端连接成功,即可随时send
(5)FD_CONNECT 客户端事件模型使用,客户端一方,给服务器绑定这个
(6)0 取消事件监视,事件和socket还是绑定的 WSAEventSelect(,,FD_ACCEPT|FD_READ); WSAEventSelect(,,0); 取消了事件信号
(7)FD_OOB 带外数据 一般不使用
(8)FD_QOS 1)套接字服务质量状态发生变化消息通知 比如:当网络发生拥堵时:用户下载,看电影,聊天,听歌好多用网事件一起再做,那么计算机网速是有限的,每秒可以处理多少数据,这时候计算机就会把要紧事优先,比如降低下载的速度,以保证看电影流畅,这时候,下载的服务质量就发生了变化。如果投放了这个事件就会接收到信号了。
2)可以通过WSAloctl得到服务质量信息 char strOut[2048] = {0}; DWORD nLen = 2048; WSAloctl(socketServer,SIO_QOS,0,0,strout,nLen,&nLen,NULL,NULL)
(9)FD_GROUP_QOS 保留 还没有对其赋值具体意义,还没用呢 想要接收套接字组Qos更改的通知
(10)用在重叠I/O模型中 FD_ROUTING_INTERFACE_CHANGE 1)想要接受指定目标的路由接口更改通知
2)数据到达对方的所经过的线路改变了,是由于动态路线优化的选择
3)要通过函数WSAloct注册之后,才可使用 第二个参数改为SIO_ROUTING_INTERFACE_CHANGE
FD_ADDRESS_LIST_CHANGE 1)想要接收套接字地址族的本地地址列表更改通知 服务器链接了很多客户端,那服务器就记录着所有的客户端的地址信息,也就是相当于一个列表,当多一个或者少一个,就是变化了,就能得到相关的信号了
2)要通过函数WSAloct注册之后,才可使用 第二个参数改为SIO_ADDRESS_LIST_CHANGE
返回值:成功返回0,失败返回SOCKET_ERROR
*/
//装进去
esSet.eventall[esSet.count] = eventServer;
esSet.sockall[esSet.count] = socketServer;
esSet.count++;
while (1)
{
//询问事件
DWORD nRes = WSAWaitForMultipleEvents(esSet.count, esSet.eventall, FALSE, WSA_INFINITE, FALSE);
/*
作用:获取发生信号的事件
参数1:事件个数 定义事件列表(数组)个数
(1)WSA_MAXIMUM_WAIT_EVENTS 64个,该函数参数1最大64个
(2)可以变大, 方法比较复杂,不像select模型,直接就能变大,因为select本身就是个数组,然后遍历就行了,比较直接,时间选择是异步投放,由系统管理,不能随便修改了,要按规则来
参数2:事件列表
参数3:事件等待方式
(1)TRUE 所有的事件都产生信号,才返回
(2)FALSE 1).任何一个事件产生信号,立即返回
2).返回值减去WSA_WAIT_EVENT_0表示事件对象的索引,其状态导致函数返回
3).如果在调用期间发生多个事件对象的信号,则这是信号事件对象的数组索引,返回所有信号事件中索引值最小的
参数4:超时间隔 以毫秒为单位,跟select参数5一样的意义
(1)123:等待123毫秒 期间有信号立即返回,如果超时返回WSA_WAIT_TIMEOUT
(2)0:检查事件对象的状态并立即返回,不管有没有信号
(3)WSA_INFINITE 等待直到事件发生
参数5:
(1)TRUE 重叠I/O使用
(2)FALSE 事件选择模型填写FALSE
返回值:(1)数组下标的运算值
1)参数3为TRUE 所有的事件均有信号
2)参数3为FALSE 返回值减去WSA_WAIT_EVENT_0 == 数组中事件的下标
(2)WSA_WAIT_IO_COMPLETION 参数5为TRUE,才会返回这个值
(3)WSA_WAIT_TIMEOUT 超时了,continue即可
*/
if (WSA_WAIT_FAILED == nRes)
{
//出错了
printf("询问事件失败,错误码为%d\n", WSAGetLastError());
break;
}
//如果参数4写具体超时间隔,此时事件要加上超时判断
//if (WSA_WAIT_TIMEOUT == nRes)
//{
// continue;
//}
DWORD nIndex = nRes - WSA_WAIT_EVENT_0;
//列举事件,得到下标对应的具体操作
WSANETWORKEVENTS NetworkEvents;
if (SOCKET_ERROR == WSAEnumNetworkEvents(esSet.sockall[nIndex], esSet.eventall[nIndex], &NetworkEvents))
{
printf("得到下标对应的具体操作失败,错误码:%d\n", WSAGetLastError());
break;
}
/*
作用:获取事件类型,并将事件上的信号重置 accept,recv,send等等
参数1:对应的socket
参数2:对应的事件
参数3:(1)触发的事件类型在这里装着
(2)是一个结构体指针 struct_WSANETWORKEVENTS{long lNetworkEvents; int iErrorCode[FD_MAX_EVENTS];}
成员1:具体操作 一个信号可能包含两个消息,以按位或的形式存在
成员2:错误码数组 1)FD_ACCEPT事件错误码在FD_ACCEPT_BIT下标里
2)没有错误,对应的就是0
返回值:成功 0 ; 失败 SOCKET_ERROR
*/
/*
事件分类处理逻辑 程序打断点,虽然程序卡住了,但是事件投递给了系统,期间客户端发送给服务器的全部信息关联的事件都会产生有信号的,是异步的, 如果客户端连续send几次,服务器会一次recv全部接收,因为系统底层协议栈照常运行
1.多if逻辑更好,更严谨,但效率低第一点
测试while后加断点,打开客户端发一句消息,实际执行了两次socket, 第一次lNetworkEvents = 8, 服务器socket执行accept操作,第二次是客户端socket,lNetworkEvents = 3, 服务器执行write和read
2.if - else是多选一,有小bug, 但bug情况不多见
测试while后加断点,打开客户端发一句消息,实际执行了两次socket, 第一次是服务器socket,执行accept操作,第二次是客户端socket,但是因为if_else只选择其中一个信号,所以服务器只执行了write
3.switch的话,大bug,需要很多改进
测试while后加断点,打开客户端发一句消息,实际执行了两次socket, 第一次是服务器socket执行accept操作,第二次过来是客户端socket,但是write和read信号是一起过来的, lNetworkEvents = 3,write是2,read是1,case匹配不到3,继续下一次循环
*/
if (NetworkEvents.lNetworkEvents & FD_ACCEPT) //if结果为真说明:不管其他信号如何,FD_ACCEPT这个信号是有信号过来的
{
if (0 == NetworkEvents.iErrorCode[FD_ACCEPT_BIT])
{
//正常处理
SOCKET socketClient = accept(esSet.sockall[nIndex], NULL, NULL);
if (INVALID_SOCKET == socketClient)
{
continue;
}
//创建事件对象
WSAEVENT wsaClientEvent = WSACreateEvent();
if (WSA_INVALID_EVENT == wsaClientEvent)
{
closesocket(socketClient);
continue;
}
//投递给系统
if (SOCKET_ERROR == WSAEventSelect(socketClient, wsaClientEvent, FD_READ | FD_CLOSE | FD_WRITE))
{
closesocket(socketClient);
WSACloseEvent(wsaClientEvent);
continue;
}
//装进结构体
esSet.sockall[esSet.count] = socketClient;
esSet.eventall[esSet.count] = wsaClientEvent;
esSet.count++;
printf("accept event\n");
}
else
{
continue;
}
}
if (NetworkEvents.lNetworkEvents & FD_WRITE) //事件选择模型做了优化,只在aceept后紧接着产生一次,成功链接后随时都可以send,不需要一直触发事件,而select模型send是一直有效的,有相应的
{
if (0 == NetworkEvents.iErrorCode[FD_WRITE_BIT])
{
//客户端链接服务器后的第一次进行初始化,后面随时都可以send,不一定需要进入if判断
if (SOCKET_ERROR == send(esSet.sockall[nIndex], "connect success", strlen("connect success"), 0)) //strlen比sizeof得到的字节数少一个,'\0'
{
printf("send失败,错误码为:%d\n", WSAGetLastError()); //send函数执行出现错误
continue;
}
printf("write event\n");
}
else
{
printf("socket error套接字错误,错误码为:%d\n", NetworkEvents.iErrorCode[FD_WRITE_BIT]); //套接字出现错误
}
}
if (NetworkEvents.lNetworkEvents & FD_READ)
{
if (0 == NetworkEvents.iErrorCode[FD_READ_BIT])
{
char strRecv[1500] = {0};
if (SOCKET_ERROR == recv(esSet.sockall[nIndex], strRecv, 1499, 0)) //客户端退出在FD_CLOSE分支进行
{
printf("recv失败,错误码为:%d\n", WSAGetLastError());
continue;
}
printf("接收的数据:%s\n", strRecv);
}
else
{
printf("socket error套接字错误,错误码为:%d\n", NetworkEvents.iErrorCode[FD_READ_BIT]);
continue;
}
}
if (NetworkEvents.lNetworkEvents & FD_CLOSE)
{
//if (0 == NetworkEvents.iErrorCode[FD_CLOSE_BIT])
//{
//}
//else
//{
// printf("client force out客户端强制退出,错误码:%d\n", NetworkEvents.iErrorCode[FD_CLOSE_BIT]);
//}
//三种返回值:WSAENETDOWN WSAECONNRESET 其他情况都是返回WSAECONNABORTED,包括正常退出,强制退出
//不管错误码是0是1都要清理
//打印
printf("client close\n");
printf("client force out客户端强制退出,错误码:%d\n", NetworkEvents.iErrorCode[FD_CLOSE_BIT]);
//清理下线的客户端 套接字 事件
//套接字
closesocket(esSet.sockall[nIndex]);
esSet.sockall[nIndex] = esSet.sockall[esSet.count - 1]; //由于事件选择时无序的,所以直接把当前要关闭的socket和最后一个socket交换,然后数量减1
//事件
WSACloseEvent(esSet.eventall[nIndex]);
esSet.eventall[nIndex] = esSet.eventall[esSet.count - 1];
//数量减1
esSet.count--;
}
}
//释放事件句柄,释放socket
for (int i = 0; i < esSet.count; i++)
{
closesocket(esSet.sockall[i]);
WSACloseEvent(esSet.eventall[i]);
}
//清理网络库
WSACleanup();
system("pause");
return 0;
}
/*
->事件机制 事件选择模型 ->重叠I/O模型
C/S -> select
->消息机制 异步选择模型 ->完成端口模型
*/
|
789de53c7d9aadaaafa123a50c73da2c7eaf7ef6
|
[
"C"
] | 10
|
C
|
haon16/windows-network-programming
|
495efbd6e828868ddbb397481c2301cb26a4edca
|
6d621c14e8f8d88fc33e4588c8f21cc2cc2446e6
|
refs/heads/master
|
<repo_name>agascoig/products<file_sep>/ui.R
library(shiny)
desc<-paste("A small (N=24) dataset from a 1974 Motor Trend US Magazine is used by this application to study",
"variables that affect miles per gallon (MPG). Select the variables used to fit a linear model
for MPG on the left, and then click the Run Regression button to fit the model.")
shinyUI(
pageWithSidebar(
# Application title
titlePanel("Miles Per Gallon Regression Application"),
sidebarPanel(
checkboxGroupInput("checkGroup",
label=h3("Regressors"),
choices = list("Number of Cylinders"=2,
"Displacement"=3,
"Gross Horesepower"=4,
"Real axle ratio"=5,
"Vehicle Weight"=6,
"Quarter-Mile Time"=7,
"V/S"=8,
"Automatic Transmission"=9,
"Number of Forward Gears"=10,
"Number of Carburetors"=11),select=c(6,4)),
submitButton("Run Regression")
),
mainPanel(
p("<NAME>"),
p("February 10th, 2016"),
hr(),
p(desc),
hr(),
tableOutput("table1"),
hr(),
plotOutput("plot1"),
plotOutput("plot2"),
plotOutput("plot3"),
plotOutput("plot4"),
hr(),
h4("mtcars dataset"),
tableOutput("table2")
)
)
)<file_sep>/server.R
library(shiny)
require(datasets)
data(mtcars)
mydata<-mtcars
mydata$am<-as.factor(mydata$am)
shinyServer(
function(input, output, session) {
fit1<-reactive({
lm(as.formula(paste(colnames(mydata)[1], "~",
paste(colnames(mydata)[as.integer(input$checkGroup)], collapse = "+"),
sep = "")),data=mydata)
})
output$table1 <- renderTable({summary(fit1())})
output$plot1 <- renderPlot({plot(fit1(),which=1)})
output$plot2 <- renderPlot({plot(fit1(),which=2)})
output$plot3 <- renderPlot({plot(fit1(),which=3)})
output$plot4 <- renderPlot({plot(fit1(),which=4)})
output$table2 <- renderTable({mtcars})
}
)
|
bcac281b10c0078edc6e5715de1dddf4242a18e7
|
[
"R"
] | 2
|
R
|
agascoig/products
|
881b00c101e9f1c34d8fbb8e5605c891839465ea
|
e6ff43458515e4e0fa16a97cbd796066078288d5
|
refs/heads/master
|
<file_sep>package BLLayer;
/*
* 连接数据库
* 2017-05-04 21:57:57
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnect {
public static String DRIVER_MAYSQL = "com.mysql.jdbc.Driver";//MySQL JDBC驱动字符串
//数据库URL,用来标识要连接的数据库,其中数据库名、用户名、密码是根据数据库情况设定
public static String URL = "jdbc:mysql://localhost:3306/chatroom?"
+ "user=root&password=<PASSWORD>&useUnicode=true&charcterEncoding=UTF8" ;
private static Connection conn = null;
static{//静态初始化程序
try {
Class.forName(DRIVER_MAYSQL);//加载JDBC驱动
System.out.println("Driver Load Success.");
//创建数据库连接对象
conn = DriverManager.getConnection(URL);
System.out.println("GetConnectionToDB");
} catch (SQLException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
return conn;
}
public static void closeDB()throws SQLException{
conn.close();
}
}
<file_sep>package DALayer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import BLLayer.DBConnect;
import BLLayer.UsersEntity;
/*
* 2017-05-04 18:34:55
* users实体类的数据访问
* 即对数据库中users表的“增删减更”
*/
public class UsersDA {
//登陆验证并获取用户信息
public UsersEntity findByNamePassword(String name,String password) throws SQLException{
Connection connection = DBConnect.getConnection();
Statement statement = connection.createStatement();
//主语SQL语句的空格
String sql = "SELECT * FROM users WHERE name='"+name+"' AND password='"+password+"'";
ResultSet rs = statement.executeQuery(sql);
UsersEntity user = null;
if (rs.next()) {
user = new UsersEntity();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setSex(rs.getString("sex"));
user.setStatus(rs.getInt("status"));
System.out.println(user.toString());
}
rs.close();//关闭结果集
statement.close();
return user;
}
public boolean insert(UsersEntity user) throws SQLException {
Connection conn = DBConnect.getConnection();
String sql = "insert into users values(NULL,?,?,?,?)";
// 预编译
PreparedStatement ptmt = conn.prepareStatement(sql);
// 传参
ptmt.setString(1, user.getName());
ptmt.setString(2, user.getPassword());
ptmt.setString(3, user.getSex());
ptmt.setInt(4, user.getStatus());
// 执行
ptmt.execute();
return true;
}
public UsersEntity findByName(String name) throws SQLException {
Connection conn = DBConnect.getConnection();
Statement state = conn.createStatement();
ResultSet rs = state.executeQuery(
"SELECT id,name,password,sex,status FROM users u WHERE u.name='"+name+"'");
UsersEntity user = null;
if (rs.next()) {
user = new UsersEntity();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setSex(rs.getString("sex"));
user.setStatus(rs.getInt("status"));
}
return user;
}
public UsersEntity findById(int id) throws SQLException {
Connection conn = DBConnect.getConnection();
Statement state = conn.createStatement();
ResultSet rs = state.executeQuery(
"SELECT id,name,password,sex,status FROM users u WHERE u.id="+id);
UsersEntity user = null;
if (rs.next()) {
user = new UsersEntity();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(<PASSWORD>("<PASSWORD>"));
user.setSex(rs.getString("sex"));
user.setStatus(rs.getInt("status"));
}
return user;
}
public void offline(int id) throws SQLException {//用户离线status=0
Connection conn = DBConnect.getConnection();
Statement state = conn.createStatement();
String sql = "UPDATE users SET status = 0 WHERE id="+id;
state.execute(sql);
}
public void online(int id) throws SQLException {//用户上线status=1
Connection conn = DBConnect.getConnection();
Statement state = conn.createStatement();
String sql = "UPDATE users SET status = 1 WHERE id="+id;
state.execute(sql);
}
public void hide(int id) throws SQLException {//用户隐身status=2
Connection conn = DBConnect.getConnection();
Statement state = conn.createStatement();
String sql = "UPDATE users SET status = 2 WHERE id="+id;
state.execute(sql);
}
}
<file_sep>package UILayer;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import BLLayer.UsersBL;
import BLLayer.UsersEntity;
/*
* 注册界面
* 2017-05-06 00:43:13
*/
public class SignupUI extends JPanel {
private static final long serialVersionUID = 1L;
private static final int DEFAULT_WTDTH = 240;
private static final int DEFAULT_HEIGHT = 150;
private JTextField username;
private JPasswordField password;
private JButton okButton;
private boolean ok;
private JDialog dialog;
public SignupUI() {
setLayout(new BorderLayout());
// construct a panel with user name and password fields
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel(" User name:"));
panel.add(username = new JTextField(""));
panel.add(new JLabel(" Password:"));
panel.add(password = new JPasswordField(""));
JRadioButton sexM = new JRadioButton(" ♂",true);//0
JRadioButton sexW = new JRadioButton(" ♀",false);//1
panel.add(sexM);
panel.add(sexW);
add(panel, BorderLayout.CENTER);
// create Ok and Cancel buttons that terminate the dialog
okButton = new JButton("Ok");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String tname = username.getText();
String tpass = new String(password.getPassword());
String tsex=null;
if(sexW.isSelected()) tsex="F";
else tsex="M";
UsersEntity u = new UsersEntity(tname,tpass,tsex,0);
int isSuccess = new UsersBL().signUp(u);
if (isSuccess == 2) {
ok = true;
JOptionPane.showMessageDialog(null, "Signup successfully!");
dialog.setVisible(false);
}else
if (isSuccess == 1) {
ok = false;
JOptionPane.showMessageDialog(SignupUI.this,"Username has been used,please try again!","Signup Failed",JOptionPane.ERROR_MESSAGE);
dialog.setVisible(true);
}
else {
JOptionPane.showMessageDialog(null, "Unknown error!Please try again","Signup Failed" , JOptionPane.ERROR_MESSAGE);
}
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dialog.setVisible(false);
}
});
// add buttons to southern border
JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
add(buttonPanel, BorderLayout.SOUTH);
}
/**
* Show the chooser panel in a dialog
*
* @param parent a component in the owner frame or null
* @param title the dialog window title
*/
public boolean showDialog(Component parent, String title) {
ok = false;
//获取屏幕长宽
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
// locate the owner frame
Frame owner = null;
if (parent instanceof Frame) owner = (Frame) parent;
else owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
// if first time, or if owner has changed, make new dialog
if (dialog == null || dialog.getOwner() != owner) {
dialog = new JDialog(owner, true);
dialog.add(this);
dialog.getRootPane().setDefaultButton(okButton);
dialog.setSize(DEFAULT_WTDTH, DEFAULT_HEIGHT);
dialog.setLocation((screenWidth - DEFAULT_WTDTH) / 2, (screenHeight - DEFAULT_HEIGHT) / 2);
}
dialog.setTitle(title);
dialog.setVisible(true);
return ok;
}
}
<file_sep># JavaChatRoomProject
Java大作业_聊天室
<file_sep>DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(25) DEFAULT NULL,
`password` varchar(25) DEFAULT NULL,
`sex` varchar(2) DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
<file_sep>package Run;
import java.awt.EventQueue;
import javax.swing.*;
import UILayer.ChatFrame;
/*
* 客户端执行入口
* 2017-05-05 16:05:09
*/
public class RunChatClient {
public static void main(String[] args){
EventQueue.invokeLater(new Runnable() {//用于打开一个新的swing.fame的事件队列
public void run() {
ChatFrame chatClientFrame = new ChatFrame();
chatClientFrame.setVisible(true);
chatClientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
|
37987be199e9fd1e9c92473893924b7ff15786fd
|
[
"Markdown",
"Java",
"SQL"
] | 6
|
Java
|
ooorangee/JavaChatRoomProject
|
77eafc4f4be5de9b3059fcb13309065ce1bb3adf
|
f5a68ed9a38003ff6a85502813201d00437274cf
|
refs/heads/master
|
<repo_name>Faizerz/React-Practice-Code-Challenge-london-web-career-021819<file_sep>/sushi-saga-client/src/containers/SushiContainer.js
import React, {Fragment} from 'react'
import MoreButton from '../components/MoreButton'
import Sushi from '../components/Sushi'
const SushiContainer = (props) => {
return (
<Fragment>
<div className="belt">
{props.sushi.map(sush => <Sushi sushi={sush} key={sush.id} changeMoney={props.changeMoney} plates={props.plates}/>)}
<MoreButton next={props.next} />
</div>
</Fragment>
)
}
export default SushiContainer
<file_sep>/sushi-saga-client/src/App.js
import React, {Component} from 'react';
import SushiContainer from './containers/SushiContainer';
import Table from './containers/Table';
const API = "http://localhost:3000/sushis"
class App extends Component {
state = {
sushi: [],
iteration: 1,
money: 100,
plates: []
}
render() {
return (<div className="app">
<form onSubmit={this.addCash}>
<input type="number" min="0" name="cash"></input>
<button>Add Money</button>
</form>
{this.state.sushi.length !== 0 && <SushiContainer sushi={this.fourSushi()} next={this.nextIteration} changeMoney={this.changeMoney} plates={this.state.plates}/>}
<Table money={this.state.money} plates={this.state.plates} />
</div>);
}
componentDidMount = () => {
fetch(API).then(res => res.json()).then(sushi => this.setState({sushi}))
}
fourSushi = () => {
let four = []
for (let x = 4; x > 0; x--) {
four.push(this.state.sushi[(this.state.iteration * 4) - x])
}
return four
}
nextIteration = () => {
this.state.iteration < 25 && this.setState({
iteration: this.state.iteration + 1
})
this.state.iteration === 25 && this.setState({
iteration: 1
})
}
changeMoney = (price, id) => {
if (this.state.money - price >= 0) {
this.setState({
money: this.state.money - price,
plates: [...this.state.plates, id]
})
}
}
addCash = (e) => {
e.preventDefault()
this.setState({
money: this.state.money + parseInt(e.target.cash.value, 10)
})
}
}
export default App;
|
648a4827f8bb2c2086df1dcdf7ac77abfdd62177
|
[
"JavaScript"
] | 2
|
JavaScript
|
Faizerz/React-Practice-Code-Challenge-london-web-career-021819
|
b1408c554fc70cd0d21f0dccac027921b1e092ba
|
445570d63d6d41c1243272473b8ec06896d336e6
|
refs/heads/master
|
<file_sep>//
// File.swift
// BlackDice
//
// Created by Alumne on 15/5/18.
// Copyright © 2018 ErikyGerard. All rights reserved.
//
import Foundation
import UIKit
class Icone {
var id:Int
var imagen:UIImage
var puntuacion:Int
var nombre:String
init(id:Int, imagen:UIImage, puntuacion:Int, nombre:String) {
self.id = id
self.imagen = imagen
self.puntuacion = puntuacion
self.nombre = nombre
}
}
<file_sep>//
// LimitNumberCircleView.swift
// BlackDice
//
// Created by Alumne on 12/4/18.
// Copyright © 2018 ErikyGerard. All rights reserved.
//
import UIKit
@IBDesignable
class LimitNumberCircleView: UIView {
@IBInspectable
var circleScale: CGFloat = 0.90
@IBInspectable
var circleCenter : CGPoint {return CGPoint(x:bounds.midX,y:bounds.midY)}
@IBInspectable
var circleRadius : CGFloat {return circleScale*min (bounds.size.width,bounds.size.height) / 2 }
@IBInspectable
var circleLineWidth : CGFloat = 5.0
@IBInspectable
var circleColor:UIColor = UIColor.black
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
*/
override func draw(_ rect: CGRect) {
//let circleRadius = min (bounds.size.width, bounds.size.height)
let path = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: 0, endAngle:CGFloat(2*Double.pi), clockwise:true)
path.lineWidth = circleLineWidth
circleColor.set()
path.stroke()
}
}
<file_sep>//
// ViewController.swift
// BlackDice
//
// Created by Alumne on 12/4/18.
// Copyright © 2018 ErikyGerard. All rights reserved.
//
import UIKit
import AudioToolbox
class GameViewController: UIViewController {
var photo: Array<UIImage>=[]
var randomLimitNum:Int = Int(arc4random_uniform(24) + 7)
var punts = 0
let defaults = UserDefaults.standard
var otherPunts = 0
var soundID:SystemSoundID=0;
@IBOutlet weak var otherScore: UILabel!
@IBOutlet weak var myScore: UILabel!
@IBOutlet weak var imageDice1: UIImageView!
@IBOutlet weak var imageDice2: UIImageView!
@IBOutlet weak var imageDice3: UIImageView!
@IBOutlet weak var imageDice4: UIImageView!
@IBOutlet weak var limitNumber: UILabel!
@IBOutlet weak var finishButton: UIButton!
@IBAction func prueba(_ sender: UIPanGestureRecognizer) {
AudioServicesPlaySystemSound(soundID)
switch sender.view {
case imageDice1?:
if sender.state == .ended{
if let dice1 = imageDice1 {
print(Int(arc4random_uniform(6) + 1))
diceAnimation(imagen: dice1)
}
}
case imageDice2?:
if sender.state == .ended{
if let dice2 = imageDice2 {
diceAnimation(imagen: dice2)
print("2")
}
}
case imageDice3?:
if sender.state == .ended{
if let dice3 = imageDice3 {
diceAnimation(imagen: dice3)
print("3")
}
}
case imageDice4?:
if sender.state == .ended{
if let dice4 = imageDice4 {
diceAnimation(imagen: dice4)
print("4")
}
}
default:
print("adeu")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
limitNumber.text = String(randomLimitNum)
if let soundURL=Bundle.main.url(forResource:"dicesound",withExtension: "mp3"){
AudioServicesCreateSystemSoundID(soundURL as CFURL, &soundID)
}
for index in 1...6{
let name:String="dice\(index)"
var image:UIImage=UIImage(named:name)!
photo.append(image)
}
}
func newGame(){
self.randomLimitNum = Int(arc4random_uniform(24) + 7)
self.punts = 0
self.otherPunts = 0
self.myScore.text = String(self.punts)
self.otherScore.text = String(self.otherPunts)
self.limitNumber.text = String(self.randomLimitNum)
self.imageDice1.image = UIImage(named: "finger")
self.imageDice2.image = UIImage(named: "finger")
self.imageDice3.image = UIImage(named: "finger")
self.imageDice4.image = UIImage(named: "finger")
}
@IBAction func stopDice(_ sender: UITapGestureRecognizer) {
switch sender.view {
case imageDice1?:
if sender.state == .ended{
if let dice1 = imageDice1 {
diceAnimatioStop(imagen: dice1)
}
}
case imageDice2?:
if sender.state == .ended{
if let dice2 = imageDice2 {
diceAnimatioStop(imagen: dice2)
print("2")
}
}
case imageDice3?:
if sender.state == .ended{
if let dice3 = imageDice3 {
diceAnimatioStop(imagen: dice3)
print("lol 3")
}
}
case imageDice4?:
if sender.state == .ended{
if let dice4 = imageDice4 {
diceAnimatioStop(imagen: dice4)
print("4")
}
}
default:
print("adeu")
}
}
func diceAnimatioStop(imagen: UIImageView){
imagen.stopAnimating()
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 1,
delay: 0,
options: .curveLinear,
animations: {
imagen.alpha=0
}, completion: {finished in
let imagePoints = Int(arc4random_uniform(5) + 1)
let other = Int(arc4random_uniform(5) + 1)
print("holas \(imagePoints)")
self.punts = self.punts + imagePoints+1
print("Els meus punts \(self.punts)")
self.otherPunts = self.otherPunts + other+1
imagen.image=self.photo[imagePoints]
let animator = UIViewPropertyAnimator(
duration: 1,
curve: UIViewAnimationCurve.linear,
animations: {
imagen.alpha=1
}
)
animator.startAnimation()
self.myScore.text = String(self.punts)
self.otherScore.text = String(self.otherPunts)
})
}
func diceAnimation(imagen : UIImageView){
imagen.animationImages=self.photo
imagen.animationDuration=1.5
imagen.animationRepeatCount=0
imagen.startAnimating()
}
func myDelayedFunction(image: UIImageView) {
let imagePoints = Int(arc4random_uniform(5) + 1)
image.image=photo[imagePoints]
print("delayed")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "listo" {
let destinationVC = segue.destination as! WinnerViewController
destinationVC.myPoints = self.punts
destinationVC.otherPoints = self.otherPunts
destinationVC.limitNumber = self.randomLimitNum
self.newGame()
}
}
}
<file_sep>//
// TragaPerrasViewController.swift
// BlackDice
//
// Created by Alumne on 10/5/18.
// Copyright © 2018 ErikyGerard. All rights reserved.
//
import UIKit
class TragaPerrasViewController: UIViewController {
var iconos:Array<Icone>=[]
//var imageArray:Array<UIImage>=[]
var playing:Bool = false
var displayLink: Bool = false;
var tragaperras:TragaPerras = TragaPerras()
var stepCount:Int = 0
let defaults = UserDefaults.standard
var dinersGuanyats:Int = 0
var counter:Int = 0
var button1Icone:Icone?
var button2Icone:Icone?
var button3Icone:Icone?
@IBOutlet weak var stopButton1: UIButton!
@IBOutlet weak var stopButton2: UIButton!
@IBOutlet weak var stopButton3: UIButton!
@IBOutlet weak var dineroView: UILabel!
@IBOutlet weak var fichasView: UILabel!
@IBOutlet weak var playbutton: UIButton!
@IBOutlet weak var panel1: UIImageView!
@IBOutlet weak var panel2: UIImageView!
@IBOutlet weak var panel3: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
actualizeLabels()
areButtonsHidden(areHidden: true)
var strings = ["lemon","cherry","pickle","smekel","dollar"]
tragaperras.fichas = defaults.integer(forKey: "fichas")
tragaperras.dinero = defaults.integer(forKey: "dinero")
fichasView.text = String(describing: tragaperras.fichas)
dineroView.text = String(describing: tragaperras.dinero)
for index in 1...5{
var image:UIImage=UIImage(named:strings[index-1])!
var icono = Icone(id:index-1,imagen:image,puntuacion:index*100,nombre:strings[index-1])
iconos.append(icono)
//imageArray.append(image)
}
// Do any additional setup after loading the view.
}
func actualizeLabels(){
dineroView.text = String(defaults.integer(forKey: "diners"))
fichasView.text = String(defaults.integer(forKey: "fichas"))
}
@IBAction func startGame(_ sender: Any) {
if(!playing){
areButtonsHidden(areHidden: false)
if(defaults.integer(forKey: "fichas")<=0){
displayAlert(title: "No te quedan fichas!", message:"Juega a Black Dice para conseguir mas")
areButtonsHidden(areHidden: true)
}else{
if(!displayLink){
createDisplayLink()
displayLink = true
}
playing = true
tragaperras.button1 = true
tragaperras.button2 = true
tragaperras.button3 = true
tragaperras.gastarFicha()
fichasView.text = String(defaults.integer(forKey: "fichas"))
}
}
}
func sumarDinero(){
}
func createDisplayLink() {
let displaylink = CADisplayLink(target: self, selector: #selector(rotate))
displaylink.add(to: .current,
forMode: .defaultRunLoopMode)
}
@objc func rotate() {
if(playing){
if(tragaperras.button1){
rotatePanels(panel: panel1, id: 1)
}
if(tragaperras.button2){
rotatePanels(panel: panel2, id: 2)
}
if(tragaperras.button3){
rotatePanels(panel: panel3, id: 3)
}
stepCount = stepCount + 1
}
}
@IBAction func stopButton1(_ sender: Any) {
tragaperras.button1 = false
checkPanels()
stopButton1.isHidden = true
}
@IBAction func stopButton2(_ sender: Any) {
tragaperras.button2 = false
checkPanels()
stopButton2.isHidden = true
}
@IBAction func stopButton3(_ sender: Any) {
tragaperras.button3 = false
checkPanels()
stopButton3.isHidden = true
}
func checkPanels(){
if(!tragaperras.button1 && !tragaperras.button2 && !tragaperras.button3){
playing = false;
if(button1Icone?.nombre == button2Icone?.nombre && button1Icone?.nombre == button3Icone?.nombre){
if(button1Icone?.nombre=="dollar"){
dinersGuanyats = 10000
displayAlert(title: "Enhorabuena!! ", message: "Has ganado \(dinersGuanyats) €")
}else{
dinersGuanyats = (button1Icone?.puntuacion)! * 3
displayAlert(title: "Enhorabuena!! ", message: "Has ganado \(dinersGuanyats) €")
}
}else if(button1Icone?.nombre == button2Icone?.nombre || button3Icone?.nombre == button2Icone?.nombre){
dinersGuanyats = (button2Icone?.puntuacion)! * 2
displayAlert(title: "Enhorabuena!! ", message: "Has ganado \(dinersGuanyats) €")
}else{
dinersGuanyats = 0
displayAlert(title: "Que penaa...", message: "Has ganado \(dinersGuanyats) € :(")
}
var totalDiners = dinersGuanyats + defaults.integer(forKey: "diners")
defaults.set(totalDiners, forKey: "diners")
dineroView.text = String(totalDiners)
actualizeLabels()
}
}
func rotatePanels(panel:UIImageView, id:Int){
if (stepCount % (4*1) == 0){
if(counter==5){
counter=0;
}
panel.image = iconos[counter].imagen
switch id {
case 1:
button1Icone = iconos[counter]
case 2:
button2Icone = iconos[counter]
default:
button3Icone = iconos[counter]
}
counter = counter + 1
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func displayAlert(title:String , message:String){
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
}
func areButtonsHidden(areHidden:Bool){
stopButton1.isHidden = areHidden
stopButton2.isHidden = areHidden
stopButton3.isHidden = areHidden
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// WinnerViewController.swift
// BlackDice
//
// Created by Alumne on 3/5/18.
// Copyright © 2018 ErikyGerard. All rights reserved.
//
import UIKit
import AudioToolbox
class WinnerViewController: UIViewController {
var myPoints:Int = 0
var otherPoints:Int = 0
var limitNumber:Int = 0
let defaults = UserDefaults.standard
var winSoundID:SystemSoundID = 0
var loseSoundID:SystemSoundID = 0
@IBOutlet weak var winnerLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if let winSoundURL=Bundle.main.url(forResource:"winSound",withExtension: "mp3"){
AudioServicesCreateSystemSoundID(winSoundURL as CFURL, &winSoundID)
}
if let loseSoundURL=Bundle.main.url(forResource:"failSound",withExtension: "mp3"){
AudioServicesCreateSystemSoundID(loseSoundURL as CFURL, &loseSoundID)
}
setGanador()
// Do any additional setup after loading the view.
}
func setGanador(){
let myFinalPoints = limitNumber-myPoints
let otherFinalPoints = limitNumber-otherPoints
if(myFinalPoints < 0 && otherFinalPoints < 0){
self.winnerLabel.text = "EMPATE"
}
else if(myFinalPoints < 0 && otherFinalPoints >= 0){
self.winnerLabel.text = "HAS PERDIDO"
AudioServicesPlaySystemSound(loseSoundID)
}else if(otherFinalPoints < 0 && myFinalPoints >= 0){
self.winnerLabel.text = "HAS GANADO 3 FICHAS"
var totalFichas = defaults.integer(forKey: "fichas");
defaults.set(totalFichas+3, forKey: "fichas")
AudioServicesPlaySystemSound(winSoundID)
}else if(myFinalPoints > otherFinalPoints){
self.winnerLabel.text = "HAS PERDIDO"
AudioServicesPlaySystemSound(loseSoundID)
}else if(myFinalPoints==otherFinalPoints){
self.winnerLabel.text = "EMPATE"
}else{
self.winnerLabel.text = "HAS GANADO 3 FICHAS"
var totalFichas = defaults.integer(forKey: "fichas");
defaults.set(totalFichas+3, forKey: "fichas")
AudioServicesPlaySystemSound(winSoundID)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
@IBOutlet weak var winnerLabel: UILabel!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// TragaPerras.swift
// BlackDice
//
// Created by Alumne on 10/5/18.
// Copyright © 2018 ErikyGerard. All rights reserved.
//
import Foundation
class TragaPerras {
let array: [Int] = [0, 1, 2, 3]
var icones: [Int]?
var puntuacio:Int = 0
var button1:Bool = false
var button2:Bool = false
var button3:Bool = false
var fichas:Int = 0
var dinero:Int = 0
init(){
}
func gastarFicha() {
fichas = fichas - 1
UserDefaults.standard.set(fichas, forKey: "fichas")
}
}
|
358f76964fec37dcaa708fe86729df59683eba48
|
[
"Swift"
] | 6
|
Swift
|
llanasnas/BlackDice
|
57a222e4c24277ab08dda847e1ca07d9d8e71967
|
7ffdd5f7d2a0be5ad224c6c9604e29896f032ea7
|
refs/heads/master
|
<file_sep>#include<iostream>
#include<string.h>
#include<conio.h>
#include<fstream>
using namespace std;
struct node
{
char* data1;
char* data2;
char* location;
char* soil;
char* area;
int n,m;
char query[300];
char answer[300];
struct node *next;
};
class login
{
public:
node *head;
login(){head=NULL;}
void add_begin(char* x,char* y);
void display();
bool isexist(char* x);
bool iscorrect(char* x,char* y);
void details(char* m,char* n);
void read_query(char* x,char* y);
bool is_query_asked(char* x,char* y);
bool is_query_answered(char* x,char* y);
void query_clearance();
void unanswered_query();
void assign_query(char* x,char* y);
};
void login::assign_query(char* x,char* y)
{
node *p;
p=head;
while(p!=NULL)
{
if(strcmp(x,p->data1)==0)
{
strcpy(p->query,y);
p->n=1;
p->m=1;
}
p=p->next;
}
}
void login::unanswered_query()
{
fstream file("uns_query.txt",ios::in|ios::out|ios::trunc);
if(!file.is_open())
{
file.open("uns_query.txt");
}
node *p;
p=head;
while(p!=NULL)
{
if(p->n==1&&p->m!=0)
{
file<<p->data1<<endl;
file<<p->query<<endl;
}
p=p->next;
}
file.close();
}
void login::query_clearance()
{
node *p;
p=head;
while(p!=NULL)
{
if(p->n==1&&p->m!=0)
{
cout<<endl<<p->data1<<":"<<endl<<p->query<<endl<<endl<<endl;
}
p=p->next;
}
cout<<"Do you want to answer any of the queries?"<<endl;
cout<<"If yes...enter 1"<<endl;
cout<<"If no....enter 0"<<endl;
int s1;
cin>>s1;
if(s1==1)
{
cout<<endl<<"Enter the username of the query which you want to answer:";
char user[40];char s2[400];
cin>>user;
p=head;
while(p!=NULL)
{
if(strcmp(user,p->data1)==0)
{
cout<<endl<<"Enter the solution of the query:"<<endl;
cout<<p->query<<endl;
int f=0;
char h;
for(f=0;;)
{
h=getch();
if((h>=' '&&h<='~'))
{
s2[f]=h;
++f;
cout<<h;
}
if(h=='\b'&&f>=1)
{
cout<<"\b \b";
--f;
}
if(h=='\r')
{
s2[f]='\0';
break;
}
}
strcpy(p->answer,s2);
p->m=0;
break;
}
p=p->next;
}
fstream file5("query.txt",ios::in|ios::out|ios::app);
if(!file5.is_open())
{
file5.open("query.txt");
}
file5<<user<<endl<<p->query<<endl<<s2<<endl;
file5.close();
}
}
bool login::is_query_answered(char* x,char* y)
{
node *p;
p=head;
while(p!=NULL)
{
if(strcmp(p->data1,x)==0)
{
if(p->m==0&&p->n==1)
{
return true;
}
else
{
return false;
}
}
p=p->next;
}
}
bool login::is_query_asked(char* x,char* y)
{
node *p;
p=head;
while(p!=NULL)
{
if(strcmp(p->data1,x)==0)
{
if(p->n==1)
{
return true;
}
else
{
return false;
}
}
p=p->next;
}
}
void login::read_query(char* x,char* y)
{
cout<<endl<<endl<<"Enter your query:"<<endl;
char str[300];
int f=0;
char h;
for(f=0;;)
{
h=getch();
if((h>=' '&&h<='~'))
{
str[f]=h;
++f;
cout<<h;
}
if(h=='\b'&&f>=1)
{
cout<<"\b \b";
--f;
}
if(h=='\r')
{
str[f]='\0';
break;
}
}
cout<<endl<<endl<<endl;
cout<<endl<<"query read"<<endl;
node *p;
p=head;
while(p!=NULL)
{
cout<<endl<<"while loop entered"<<endl;
if(strcmp(p->data1,x)==0)
{
strcpy(p->query,str);
p->m=1;
p->n=1;
break;
}
p=p->next;
}
}
void login::details(char* m,char* n)
{
char l[50],s[50],t[50];
int z=0,f=0;
node *p;
p=head;
while(p!=NULL)
{
if(strcmp(p->data1,m)==0 && strcmp(p->data2,n)==0)
{
cout<<endl<<endl<<endl<<"Login successful"<<endl<<endl<<endl;
cout<<endl<<endl<<endl<<"Enter the following details:-"<<endl<<endl<<endl;
cout<<endl<<"If you belong to any of these districts, select an option."<<endl<<"If not type your district or state manually:"<<endl;
cout<<"Select the location:"<<endl;
cout<<"1.Karimnagar"<<endl<<"2.Warangal"<<endl<<"3.Khammam"<<endl<<"4.Adilabad"<<endl;
cout<<"5.Nizamabad"<<endl<<"6.Ranga Reddy"<<endl<<"7.Rajendranagar"<<endl;
cout<<"8.Medak"<<endl<<"9.Mahabubnagar"<<endl<<"10.Nalgonda"<<endl;
cout<<"Enter your choice:";
cin>>f;
switch(f)
{
case 1:
p->location=new char[strlen("Karimnagar")+1];
strcpy(p->location,"Karimnagar");
break;
case 2:
p->location=new char[strlen("Warangal")+1];
strcpy(p->location,"Warangal");
break;
case 3:
p->location=new char[strlen("Khammam")+1];
strcpy(p->location,"Khammam");
break;
case 4:
p->location=new char[strlen("Adilabad")+1];
strcpy(p->location,"Adilabad");
break;
case 5:
p->location=new char[strlen("Nizamabad")+1];
strcpy(p->location,"Nizamabad");
break;
case 6:
p->location=new char[strlen("Rangareddy")+1];
strcpy(p->location,"Rangareddy");
break;
case 7:
p->location=new char[strlen("Rajendranagar")+1];
strcpy(p->location,"Rajendranagar");
break;
case 8:
p->location=new char[strlen("Medak")+1];
strcpy(p->location,"Medak");
break;
case 9:
p->location=new char[strlen("Mehabubnagar")+1];
strcpy(p->location,"Mehabubnagar");
break;
case 10:
p->location=new char[strlen("Nalgonda")+1];
strcpy(p->location,"Nalgonda");
break;
default:
cout<<"Invalid choice."<<endl<<endl;
}
cout<<endl<<endl<<endl<<endl<<"Select the type of soil:"<<endl<<"1.red soil"<<endl<<"2.black soil"<<endl<<"3.loamy soil"<<endl<<"4.clayey soil"<<endl<<"5.sandy soil"<<endl;
cin>>z;
switch(z)
{
case 1: p->soil=new char[strlen("red soil")+1];
strcpy(p->soil,"red soil");
break;
case 2: p->soil=new char[strlen("black soil")+1];
strcpy(p->soil,"black soil");
break;
case 3:p->soil=new char[strlen("loamy soil")+1];
strcpy(p->soil,"loamy soil");
break;
case 4:p->soil=new char[strlen("clayey soil")+1];
strcpy(p->soil,"clayey soil");
break;
case 5:p->soil=new char[strlen("sandy soil")+1];
strcpy(p->soil,"sandy soil");
break;
}
cout<<endl<<endl<<endl<<"Enter the area of the farmfield in meter square:";
cin>>t;
p->area=new char[strlen(t)+1];
strcpy(p->area,t);
cout<<endl<<endl;
cout<<"Based on the type of climate in your location,the type of your soil and the area of your farm field"<<endl;
cout<<"Suggested crops are:"<<endl<<endl<<endl;
if(z==1)
{
cout<<endl<<endl<<"1.cotton"<<endl<<"2.groundnut"<<endl<<"3.millets"<<endl<<"4.pulses"<<endl<<"5.tobacco"<<endl<<endl<<endl;
}
if(z==2)
{
cout<<endl<<endl<<"1.Sugarcane"<<endl<<"2.Wheat"<<endl<<"3.oilseeds"<<endl<<"4.cotton"<<endl<<"5.tobacco"<<endl<<"6.millets"<<endl<<endl<<endl;
}
if(z==3)
{
cout<<endl<<endl<<"1.Wheat"<<endl<<"2.jute"<<endl<<"3.vegetables"<<endl<<"4.cotton"<<endl<<"5.sugarcane"<<endl<<"6.pulses"<<endl<<"7.oilseeds"<<endl<<endl<<endl;
}
if(z==4)
{
cout<<endl<<endl<<"1.paddy"<<endl<<endl<<endl;
}
if(z==5)
{
cout<<endl<<endl<<"1.melon"<<endl<<"2.coconut"<<endl<<"3.maize"<<endl<<"4.millets"<<endl<<"5.barley"<<endl<<endl<<endl;
}
break;
}
p=p->next;
}
}
void login::add_begin(char* x,char* y)
{
node *temp=new node;
temp->data1=new char[strlen(x)+1];
strcpy(temp->data1,x);
temp->data2=new char[strlen(y)+1];
strcpy(temp->data2,y);
temp->next=NULL;
temp->m=0;
temp->n=0;
if(head==NULL)
{
head=temp;
}
else
{
temp->next=head;
head=temp;
}
}void login:: display()
{
node *p;
p=head->next;
while(p!=NULL)
{
cout<<"Username:"<<p->data1<<"\t"<<"Password:"<<p->data2<<endl;
p=p->next;
}
cout<<endl;
}
bool login::isexist(char* x)
{
node *p;
p=head;
while(p!=NULL)
{
if(strcmp(p->data1,x)==0)
{
return true;
}
p=p->next;
}
return false;
}bool login::iscorrect(char* x,char* y)
{
node *p;
p=head;
while(p!=NULL)
{
if(strcmp(p->data1,x)==0 && strcmp(p->data2,y)==0)
{
return true;
}
p=p->next;
}
return false;
}
int main()
{
cout<<" -----------------------FARMER'S GUIDE-----------------------------"<<endl<<endl<<endl;
login t;
int a;
char b[50];
char c[50];
char d[50];
char quer[300];
fstream file("details3.txt",ios::in|ios::out);
if(!file.is_open())
{
file.open("details3.txt");
}
while(!file.eof())
{
file.getline(b,50);
file.getline(c,50);
t.add_begin(b,c);
}
file.close();
fstream file2("uns_query.txt",ios::in|ios::out);
if(!file2.is_open())
{
file2.open("uns_query.txt");
}
while(!file2.eof())
{
file2.getline(b,50);
file2.getline(quer,200);
t.assign_query(b,quer);
}
file2.close();
while(1)
{
cout<<endl<<endl<<endl<<"1.Create username and password"<<endl<<"2.login"<<endl<<"3.Admin login"<<endl;
cout<<"4.Query Clearance."<<endl<<"5.exit"<<endl;
cout<<"Enter your choice:";
cin>>a; switch(a)
{
case 1:
{
cout<<"Create your username:";
cin>>b;
cout<<"Create your password:";
int f=0;
char h;
for(f=0;;)
{
h=getch();
if((h>=' '&&h<='~'))
{
c[f]=h;
++f;
cout<<"*";
}
if(h=='\b'&&f>=1)
{
cout<<"\b \b";
--f;
}
if(h=='\r')
{
c[f]='\0';
break;
}
}
if(!t.isexist(b))
{
t.add_begin(b,c);
fstream file("details3.txt",ios::in|ios::out|ios::app);
if(!file.is_open())
{
file.open("details3.txt");
}
file<<b<<endl<<c<<endl;
file.close();
}
else
{
cout<<"Username already exists"<<endl;
}
break;
}
case 2:
{
cout<<"Enter your username:";
cin>>b;
cout<<"Enter your password:";
int f=0;
char h;
for(f=0;;)
{
h=getch();
if((h>=' '&&h<='~'))
{
c[f]=h;
++f;
cout<<"*";
}
if(h=='\b'&&f>=1)
{
cout<<"\b \b";
--f;
}
if(h=='\r')
{
c[f]='\0';
break;
}
}
if(t.iscorrect(b,c))
{
while(1)
{
int o;
cout<<endl<<endl<<endl<<"1.Enter details for crop suggestions.";
cout<<endl<<"2.Display query solutions.";
cout<<endl<<"3.Ask a query.";
cout<<endl<<"4.Crop Production.";
cout<<endl<<"5.Post Harvest Technologies.";
cout<<endl<<"6.Market information.";
cout<<endl<<"7.Best Practices.";
cout<<endl<<"8.Policies and schemes.";
cout<<endl<<"9.State-specific schemes for farmers.";
cout<<endl<<"10.ICT applications in Agriculture.";
cout<<endl<<"11.Previous years analysis of crops.";
cout<<endl<<"12.Logout."<<endl<<endl<<endl;
cout<<"Select your choice:";
cin>>o;
switch(o)
{
case 1:
t.details(b,c);
break;
case 2:
{
char user[50],que[200],ans[200];
fstream file8("query.txt",ios::in|ios::out);
if(!file8.is_open())
{
file8.open("query.txt");
}
while(!file8.eof())
{
file8.getline(user,50);
file8.getline(que,200);
file8.getline(ans,200);
if(strcmp(b,user)==0)
{
cout<<"query asked is:"<<endl<<que<<endl<<"Solution is:"<<endl<<ans<<endl;
}
}
file8.close();
break;
}
case 3:
{
if(!t.is_query_asked(b,c))
{
cout<<endl<<"Do you want to ask a query?"<<endl<<endl;
cout<<"If yes...enter 1"<<endl;
cout<<"If no....enter 0"<<endl;
int h1;
cin>>h1;
if(h1==1)
{
cout<<endl<<"You can ask your query here and if it is answered it will be shown here in your next login"<<endl;
t.read_query(b,c);
}
}
if(t.is_query_answered(b,c))
{
cout<<"entered into is query answered function"<<endl;
cout<<endl<<endl<<"Do you want to ask another query?"<<endl;
cout<<endl<<"If yes...enter 1"<<endl;
cout<<endl<<"If no....enter 0"<<endl;
int q2;
cin>>q2;
if(q2==1)
{
t.read_query(b,c);
}
}
else
{
cout<<"You can ask another query once the previous one is answered"<<endl<<endl;
}
break;
}
case 4:
{
cout<<endl<<"Critical factors to be considered for selection of crops:"<<endl<<endl;
cout<<endl<<"Key requirements for improving productivity:"<<endl<<endl;
cout<<endl<<"Increase in productivity and profitability can be achieved through:"<<endl<<endl;
cout<<"~Blending practical knowledge with scientific technologies."<<endl;
cout<<"~Efficient use of natural resources."<<endl;
cout<<"~Adopting time specific management practices."<<endl;
cout<<"~Giving priority for quality driven production."<<endl;
cout<<"~Adopting suitable farming systems."<<endl;
cout<<"~Adoption of location specific technology."<<endl;
cout<<"~Market demand driven production."<<endl;
cout<<"~Adopting low cost and no cost technologies."<<endl<<endl<<endl;
cout<<endl<<"Factors influencing decisions on the selection of crops & cropping system:"<<endl<<endl<<endl;
cout<<endl<<"Farmers need to answer all the below questions while making decisions for choosing a crop/ cropping pattern. During this decision making process, farmers cross check the suitability of proposed crop/cropping systems with their existing resources and other conditions. Thereby, they justify choosing or rejecting a crop/cropping systems. This process enables the farmers to undertake a SWOT analysis internally which in turn guides them to take an appropriate decision."<<endl;
cout<<endl<<"1.Climatic factors - Is the crop/cropping system suitable for local weather parameters such as temperature, rainfall, sun shine hours, relative humidity, wind velocity, wind direction, seasons and agro-ecological situations?"<<endl;
cout<<endl<<"2.Soil conditions - Is the crop/cropping system suitable for local soil type, pH and soil fertility?"<<endl;
cout<<endl<<"3.Water:"<<endl<<"~Do you have adequate water source like a tanks, wells, dams, etc.?"<<endl<<"~Do you receive adequate rainfall?"<<"~Is the distribution of rainfall suitable to grow identified crops?"<<endl<<"~Is the water quality suitable?"<<endl<<"~Is electricity available for lifting the water?"<<endl<<"~Do you have pump sets, micro irrigation systems?"<<endl;
cout<<endl<<"4.Cropping system options:"<<endl<<"~Do you have the opportunity to go for inter-cropping, mixed cropping, multi-storeyed cropping, relay cropping, crop rotation, etc.?"<<endl<<"~Do you have the knowledge on cropping systems management?"<<endl;
cout<<endl<<"5.Past and present experiences of farmers:"<<endl<<
"~What were your previous experiences with regard to the crop/cropping systems that you are planning to choose?"<<endl<<
"~What is the opinion of your friends, relatives and neighbours on proposed crop/cropping systems?"<<endl;
cout<<endl<<endl<<"6.Expected profit and risk:"<<endl<<
"~How much profit are you expecting from the proposed crop/cropping system?"<<endl<<
"~Whether this profit is better than the existing crop/cropping system?"<<endl<<
"~What are the risks you are anticipating in the proposed crop/cropping system?"<<endl<<
"~Do you have the solution?"<<endl<<
"~Can you manage the risks?"<<endl<<
"~Is it worth to take the risks for anticipated profits?"<<endl<<endl<<endl;
cout<<endl<<"7.Economic conditions of farmers including land holding:"<<endl<<
"~Are the proposed crop/cropping systems suitable for your size of land holding?"<<endl<<
"~Are your financial resources adequate to manage the proposed crop/cropping system?"<<endl<<
"~If not, can you mobilize financial resources through alternative routes?"<<endl<<endl<<endl<<
"8.Labour availability and mechanization potential:"<<endl<<
"~Can you manage the proposed crop/cropping system through your family labour?"<<endl<<
"~If not, do you have adequate labours to manage the same?"<<endl<<
"~Is family/hired labour equipped to handle the proposed crop/cropping system?"<<endl<<
"~Are there any mechanization options to substitute the labour?"<<endl<<
"~Is machinery available? Affordable? Cost effective?"<<endl<<
"~Is family/hired labour equipped to handle the machinery?"<<endl<<endl<<endl<<
"9.Technology availability and suitability:"<<endl<<
"~Is the proposed crop/cropping system suitable?"<<endl<<
"~Do you have technologies for the proposed crop/cropping system?"<<endl<<
"~Do you have extension access to get the technologies?"<<endl<<
"~Are technologies economically feasible and technically viable?"<<endl<<
"~Are technologies complex or user-friendly?"<<endl<<endl<<endl<<
"10.Market demand and availability of market infrastructure:"<<endl<<
"~Are the crops proposed in market demand?"<<endl<<
"~Do you have market infrastructure to sell your produce?"<<endl<<
"~Do you have organized marketing system to reduce the intermediaries?"<<endl<<
"~Do you have answers for questions such as where to sell? When to sell? Whom to sell to? What form to sell in? What price to sell for?"<<endl<<
"~Do you get real time market information and market intelligence on proposed crops?"<<endl<<endl<<endl<<
"11.Policies and schemes:"<<endl<<
"~Do Government policies favour your crops?"<<endl<<
"~Is there any existing scheme which incentivises your crop?"<<endl<<
"~Are you eligible to avail those benefits?"<<endl<<endl<<endl<<
"12.Public and private extension influence:"<<endl<<
"~Do you have access to Agricultural Technology Management Agency (ATMA)/ Departmental extension functionaries to get advisory?"<<endl<<
"~Do you know Kissan Call Center?"<<endl<<
"~Do you have access to KVKs, Agricultural Universities and ICAR organizations?"<<endl<<
"~Do you subscribe agricultural magazines?"<<endl<<
"~Do you read agricultural articles in newspapers?"<<endl<<
"~Do you get any support from input dealers, Agribusiness Companies, NGOs, Agriclinics and Agribusiness Centers?"<<endl<<endl<<endl<<
"13.Availability of required agricultural inputs including agricultural credit:"<<endl<<
"~Do you get adequate agricultural inputs such as seeds, fertilizers, pesticides, and implements in time?"<<endl<<
"~Do you have access to institutional credit?"<<endl<<endl<<endl<<
"14.Post harvest storage and processing technologies:"<<endl<<
"~Do you have your own storage facility?"<<endl<<
"~If not, do you have access to such facility?"<<endl<<
"~Do you have access to primary processing facility?"<<endl<<
"~Do you know technologies for value addition of your crop?"<<endl<<
"~Do you have market linkage for value added products?"<<endl<<
"~Are you aware about required quality standards of value added products of proposed crops?"<<endl;
break;
}
case 5:
{
cout<<"Rice milling : process description"<<endl<<endl<<endl<<endl<<
"1.Paddy Cleaning - Essential for removal of undesired foreign matter, paddy cleaning is given utmost importance to ensure proper functioning of the Rice Milling machinery. Rough rice is passed through a series of sieves and closed circuit aspiration system is provided to remove dust and light impurities through positive air suction.Undesired material, heavier than rough rice (but of similar size) is removed through a de-stoner/gravity separator. This machine works on the principle of specific gravity. Stones and other heavy impurities, being heavier, stay on the screen surface whereas rough rice, being lighter, fluidizes into the positive air gradient created by an external source."<<endl;
cout<<endl<<endl<<"2.Paddy De-husking - A streamlined paddy flow is directed into a pair of rubber rolls, rotating at different speeds, in opposite directions. A horizontal inward pressure is applied on the rubble rollers, pneumatically. Due to the difference in the seed of rotation, a shear force is generated on the surface of hull (with two sides being rubber by tow rubber rolls) that breaks apart of the surface/hull."<<endl;
cout<<"Husk, being of lower specific gravity, is then separated form brown rice by a closed circuit aspiration system."<<endl;
cout<<"This process leads to breakage of brown rice. Although a proper horizontal inward pressure is mot important factor for breakage or rice, de-husking efficiency is equally important and should be maintained between 75 to 85%."<<endl<<endl<<endl;
cout<<"3.Paddy Separation - Rice surface is smooth as compared to rough paddy surface. This difference in surface texture is utilized to separate brown rice from paddy through paddy separator."<<endl<<endl<<endl;
cout<<"Grain surface with smooth texture, being of higher width, is removed off along with red grains by precision sizes."<<endl<<endl<<endl;
cout<<"4.Rice Whitening - Brown rice is rubbed with a rough surface, created using emery stones of specific grid size. The rough emery removes off the brown bran layer. The radial velocity of the stone wheels, grid size of the stones, clearance between stone surface & the other screen and the external pressure on the outlet chamber of the whitening machines determine the extent of whiteness.The bran layer removed from the surface if pneumatically conveyed to a separate room for further processing /storage."<<endl<<endl<<endl;
cout<<"5.Rice Polishing - The surface of whitened rice is still rough and is smoothened by a humidified rice polisher. The process involves rubbing of rice surface against another rice surface with mystified air acting as lubricant between the two surfaces. Usually a modified version of this process is used to produce superfine silky finish on rice surface.The bran layer removed from the surface if pneumatically conveyed to a separate room for further processing/storage."<<endl<<endl<<endl;
cout<<"6.Rice Grading - Broken rice is removed from whole rice by passing the lot through a cylindrical indented screen rotating at a particular speed. The broken/small grains, fit into the indents of the rotating cylinder, are lifted by centrifugal force and gravitational pull falls the grains into a trough. Adjusting the rotational speed and angle of trough can vary the average length of grains."<<endl<<endl<<endl;
cout<<"7.Rice Colour Sorting - Discoloured rice grains are removed off from the like coloured grains by Rice colour sorting machines. Photo sensors/CCD (Charged Coupled Device) sensors generate voltage signal on viewing discoloured grains, which are then removed off by air jet generated through solenoid valves."<<endl;
break;
}
case 6:
{
cout<<" Determination of MSP:"<<endl;
cout<<"In formulating the recommendations in respect of the level of minimum support prices and other non-price measures,"<<endl<<" the Commission takes into account, apart from a comprehensive view of the entire structure of the economy of a particular"<<endl<<" commodity or group of commodities, the following factors:-"<<endl;
cout<<"Cost of production"<<endl;
cout<<"Changes in input prices"<<endl;
cout<<"Input-output price parity"<<endl;
cout<<"Trends in market prices"<<endl;
cout<<"Demand and supply"<<endl;
cout<<"Inter-crop price parity"<<endl;
cout<<"Effect on industrial cost structure"<<endl;
cout<<"Effect on cost of living"<<endl;
cout<<"Effect on general price level"<<endl;
cout<<"International price situation"<<endl;
cout<<"Parity between prices paid and prices received by the farmers."<<endl;
cout<<"Effect on issue prices and implications for subsidy"<<endl;
cout<<endl<<"The Commission makes use of both micro-level data and aggregates at the level of district, state and the country. "<<endl<<"The information/data used by the Commission, inter-alia include the following :-"<<endl;
cout<<"Cost of cultivation per hectare and structure of costs in various regions of the country and changes there in;"<<endl;
cout<<"Cost of production per quintal in various regions of the country and changes therein;"<<endl;
cout<<"Prices of various inputs and changes therein;"<<endl;
cout<<"Market prices of products and changes therein;"<<endl;
cout<<"Prices of commodities sold by the farmers and of those purchased by them and changes therein;"<<endl;
cout<<"Supply related information - area, yield and production, imports, exports and domestic availability and stocks with the Government/public agencies or industry;"<<endl;
cout<<"Demand related information - total and per capita consumption, trends and capacity of the processing industry;"<<endl;
cout<<"Prices in the international market and changes therein, demand and supply situation in the world market;"<<endl;
cout<<"Prices of the derivatives of the farm products such as sugar, jaggery, jute goods, edible/non-edible oils and cotton yarn and changes therein;"<<endl;
cout<<"Cost of processing of agricultural products and changes therein;"<<endl;
cout<<"Cost of marketing - storage, transportation, processing, marketing services, taxes/fees and margins retained by market functionaries;"<<endl;
cout<<"Macro-economic variables such as general level of prices, consumer price indices and those reflecting monetary and fiscal factors."<<endl;
cout<<"Government has announced its historic decision to fix MSP at a level of at least 150 per cent of the cost of production for kharif crops 2018-19."<<endl;
cout<<endl<<endl<<"\t"<<"Commodity"<<"\t"<<"\t"<<"MSP for 2018-19"<<"\t\t"<<"MSP for 2019-20 "<<"\t"<<"Increase over previous year"<<endl;
cout<<"\t\t\t\t"<<" (Rs per quintal)"<<"\t"<<" (Rs per quintal)"<<"\t"<<" (Rs per quintal)"<<endl;
cout<<"\t"<<"Paddy"<<"\t\t\t\t"<<"1750"<<"\t\t\t"<<"1815"<<"\t\t\t"<<"65"<<endl;
cout<<"\t"<<"Jowar"<<"\t\t\t\t"<<"2430"<<"\t\t\t"<<"2550"<<"\t\t\t"<<"120"<<endl;
cout<<"\t"<<"Bajra"<<"\t\t\t\t"<<"1950"<<"\t\t\t"<<"2000"<<"\t\t\t"<<"50"<<endl;
cout<<"\t"<<"Maize"<<"\t\t\t\t"<<"1700"<<"\t\t\t"<<"1760"<<"\t\t\t"<<"60"<<endl;
cout<<"\t"<<"Ragi"<<"\t\t\t\t"<<"2897"<<"\t\t\t"<<"3150"<<"\t\t\t"<<"253"<<endl;
cout<<"\t"<<"Arhar"<<"\t\t\t\t"<<"1750"<<"\t\t\t"<<"1815"<<"\t\t\t"<<"65"<<endl;
cout<<"\t"<<"Moong"<<"\t\t\t\t"<<"6975"<<"\t\t\t"<<"7050"<<"\t\t\t"<<"75"<<endl;
cout<<"\t"<<"Urad"<<"\t\t\t\t"<<"5600"<<"\t\t\t"<<"5700"<<"\t\t\t"<<"100"<<endl;
cout<<"\t"<<"Cotton"<<"\t\t\t\t"<<"5150"<<"\t\t\t"<<"5255"<<"\t\t\t"<<"105"<<endl;
cout<<"\t"<<"Wheat"<<"\t\t\t\t"<<"1840"<<"\t\t\t"<<"1925"<<"\t\t\t"<<"85"<<endl;
cout<<"\t"<<"Barley"<<"\t\t\t\t"<<"1440"<<"\t\t\t"<<"1525"<<"\t\t\t"<<"85"<<endl;
cout<<"\t"<<"Gram"<<"\t\t\t\t"<<"4620"<<"\t\t\t"<<"4875"<<"\t\t\t"<<"255"<<endl;
cout<<"\t"<<"Masur"<<"\t\t\t\t"<<"4475"<<"\t\t\t"<<"4800"<<"\t\t\t"<<"325"<<endl;
cout<<"\t"<<"Sugarcane"<<"\t\t\t"<<"-"<<"\t\t\t"<<"275"<<"\t\t\t"<<"-"<<endl;
break;
}
case 7:
{
string x;;
fstream file("best.txt",ios::in|ios::out);
if(!file.is_open())
{
file.open("best.txt");
}
while (getline(file,x)) {
cout << x << endl ;
}
break;
}
case 8:
{
string x;;
fstream file5("poli.txt",ios::in|ios::out);
if(!file5.is_open())
{
file5.open("poli.txt");
}
while (getline(file5,x)) {
cout << x << endl ;
}
file5.close();
break;
}
case 9:
{
string x;;
fstream file5("state.txt",ios::in|ios::out);
if(!file5.is_open())
{
file5.open("state.txt");
}
while (getline(file5,x)) {
cout << x << endl ;
}
file5.close();
break;
}
case 10:
{
string x;;
fstream file5("ict.txt",ios::in|ios::out);
if(!file5.is_open())
{
file5.open("ict.txt");
}
while (getline(file5,x)) {
cout << x << endl ;
}
file5.close();
break;
}
case 11:
{
cout<<endl<<endl<<endl<<"PADDY:"<<endl<<"last year the cost was 1528/- per quintal.Note:Abundant sunshine is essential during its four months of growth.Paddy requires more water than any other crop."<<endl<<" As a result, paddy cultivation is done only in those areas where minimum rainfall is 115 cm."<<endl<<"Paddy requires three essential plant nutrients: nitrogen, phosphorus and potassium.It can grow in any type of soil."<<endl<<"HIGH CAPITAL";
cout<<endl<<endl<<endl<<"WHEAT:"<<endl<<"Previous 2 year's average cost was 1120/-per quintal.The amount of rainfall required for wheat cultivation varies between 30 cm and 100 cm.Red soil,Black soil."<<endl<<"CAPITAL INTENSIVE";
cout<<endl<<endl<<endl<<"MAIZE:"<<endl<<" Previous 2 year's average cost was 1325/-per quintal.Maize is grown mostly in regions having annual rainfall between 60 cm to 110 cm.NITROGEN is crucial for maize.Alluvial soil,Red Soil."<<endl<<"SMALL CAPITAL";
cout<<endl<<endl<<endl<<"COTTON:"<<endl<<"Previous 2 year's average cost was 3901/-per quintal.The amount of rainfall required for cotton cultivation varies between 50 cm and 100 cm.High nutrient contents is required.";
cout<<endl<<endl<<endl<<"ARHAR:"<<endl<<"Previous 2 year's average cost was 3967/-per quintal.The amount of rainfall required for arhar cultivation varies between 60 cm and 140 cm.Zinc is required in high amount";
cout<<endl<<endl<<endl<<"GROUNDNUT:"<<endl<<"Previous 2 year's average cost was 5675/-per quintal.The amount of rainfall required for groundnut cultivation varies between 60 cm and 150 cm.Sandy clay soil";
cout<<endl<<endl<<endl<<"GREEN GRAM:"<<endl<<"Previous 2 year's average cost was 4122/-per quintal.The amount of rainfall required for green gram cultivation varies between 60 cm and 90 cm.Phophorous,Nitrogen should be high.";
cout<<endl<<endl<<endl<<"BENGAL GRAM:"<<endl<<"Previous 2 year's average cost was 3850/-per quintal.The amount of rainfall required for bengal gram cultivation varies between 60 cm and 90 cm.Nitrogen conent should be high";
cout<<endl<<endl<<endl<<"BLACK GRAM:"<<endl<<"Previous 2 year's average cost was 4150/-per quintal.The amount of rainfall required for wheat cultivation varies between 60 cm and 75 cm.Black soil";
break;
}
case 12:
goto k;
}
}
k:
break;
}
else
{
cout<<endl<<endl<<endl<<"Username or password is invalid"<<endl;
}
break;
}
case 3:
{
cout<<"Enter admin password:";
int f=0;
char h;
for(f=0;;)
{
h=getch();
if((h>=' '&&h<='~'))
{
d[f]=h;
++f;
cout<<"*";
}
if(h=='\b'&&f>=1)
{
cout<<"\b \b";
--f;
}
if(h=='\r')
{
d[f]='\0';
break;
}
}
cout<<endl<<endl<<endl;
if(strcmp(d,"admin2627")==0)
{
t.display();
}
else
{
cout<<endl<<endl<<"Wrong password entered for admin."<<endl<<endl<<endl;
}
break;
}
case 4:
t.query_clearance();
break;
case 5:
t.unanswered_query();
return 0;
default:
cout<<"Invalid choice"<<endl;
}
}
return 0;
}
|
0a31ad18a1c15b30d35c82321486a58a2d3b2cd5
|
[
"C++"
] | 1
|
C++
|
jaisaikuntala1/Farmers-Guide
|
f509d52828d90235cffc8228e9a39699d59bba6b
|
795eb5e6cc1a77f298086c82ececa92c450bff2c
|
refs/heads/master
|
<repo_name>thangtran480/TextSummarization<file_sep>/requirements.txt
Flask==1.1.1
gensim==3.8.1
nltk==3.2.5
pyvi==0.0.9.7
networkx==2.4
pickleshare==0.7.5
tensorflow-gpu==1.15.2<file_sep>/abstract.py
import tensorflow as tf
import pickle
from model import Model
from utils import batch_iter
import re
from nltk.tokenize import word_tokenize
path_arg = "args.pickle"
path_word_dict = "word_dict.pickle"
class AbstractSummarization:
def __init__(self):
self.batch_size = 256
with open(path_arg, "rb") as f:
self.args = pickle.load(f)
with open(path_word_dict, "rb") as f:
self.word_dict = pickle.load(f)
self.reversed_dict = dict(zip(self.word_dict.values(), self.word_dict.keys()))
self.article_max_len = 50
self.summary_max_len = 15
self.sess = tf.Session()
print("Loading saved model...")
self.model = Model(self.reversed_dict, self.article_max_len, self.summary_max_len, self.args, forward_only=True)
saver = tf.train.Saver(tf.global_variables())
self.ckpt = tf.train.get_checkpoint_state("./saved_model/")
saver.restore(self.sess, self.ckpt.model_checkpoint_path)
def build_dataset(self, text):
text = [t.replace("\n", "") for t in text]
article_list = [re.sub("[#.]+", "#", t.strip()) for t in text]
x = [word_tokenize(d) for d in article_list]
x = [[self.word_dict.get(w, self.word_dict["<unk>"]) for w in d] for d in x]
x = [d[:self.article_max_len] for d in x]
x = [d + (self.article_max_len - len(d)) * [self.word_dict["<padding>"]] for d in x]
return x
def run(self, text):
valid_x = self.build_dataset(text)
batches = batch_iter(valid_x, [0] * len(valid_x), self.args.batch_size, 1)
for batch_x, _ in batches:
batch_x_len = [len([y for y in x if y != 0]) for x in batch_x]
valid_feed_dict = {
self.model.batch_size: len(batch_x),
self.model.X: batch_x,
self.model.X_len: batch_x_len,
}
prediction = self.sess.run(self.model.prediction, feed_dict=valid_feed_dict)
prediction_output = [[self.reversed_dict[y] for y in x] for x in prediction[:, 0, :]]
for line in prediction_output:
summary = list()
for word in line:
if word == "</s>":
break
if word not in summary:
summary.append(word)
return " ".join(summary)
if __name__ == '__main__':
abstract = AbstractSummarization()
with open("files2rouge/valid.title.filter.txt", "r",
encoding="utf-8") as f:
paper = f.readlines()
print(paper)
print(abstract.run(paper))
<file_sep>/static/js/upload.js
function pushDemo(path_image) {
document.getElementById("status").style.display = "block";
document.getElementById("loading").style.display = "block";
document.getElementById("status").innerText = "Please wait....";
fetch("/process/"+path_image, {
method:"GET"
}).then(response =>{
document.getElementById("loading").style.display = "none";
if(response.status !== 200){
document.getElementById("status").style.display = "block";
document.getElementById("status").innerText = "Please, Try again!";
console.log(`Looks like there was a problem. Status code: ${response.status}`);
return
}
document.getElementById("status").style.display = "none";
response.json().then(function (data) {
document.getElementById("image_result").src = data.path;
document.getElementById("image_input_1").src = data.path_image_input1;
document.getElementById("image_input_2").src = data.path_image_input2;
console.log(data)
});
})
}
const url_uploader = '/uploader';
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const text = document.getElementById("text").value;
fetch(url_uploader, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({'text':text}),
}).then(response => {
if (response.status !== 200) {
console.log(`Looks like there was a problem. Status code: ${response.status}`);
return;
}
response.json().then(function (data) {
console.log(data);
document.getElementById("result_abstract").innerText = data.result_abstract;
document.getElementById("result_extract").innerText = data.result_extract;
});
})
});<file_sep>/README.md
# Text Summarization for Vietnamese
Extract and Abstract Summarization Text Vietnamese
## Extract Summarization
## Abstract Summarization
## Run Demo
Setup (python=3.6)
```
git clone https://github.com/thangtran480/TextSummarization.git
cd TextSummarization
pip install -r requirements.txt
```
Download [pre-train](https://drive.google.com/drive/folders/1c9aCZROlOQsBKRUGqyrdOS7QiCm1zMCV?usp=sharing)
Run
```
python server.py
```
Open browser link http://0.0.0.0:1234<file_sep>/server.py
from flask import Flask, flash, render_template, request, redirect, abort, url_for, jsonify, make_response
from abstract import AbstractSummarization
from extract import ExtractSummarization
app = Flask(__name__)
abstract = AbstractSummarization()
extract = ExtractSummarization()
@app.route('/')
def main_layout():
return render_template('main.html')
@app.route('/uploader', methods=['POST'])
def uploader():
if request.method == 'POST':
text = request.json['text']
result_abstract = abstract.run([text])
result_extract = extract.run_textrank(text)
return jsonify({'result_abstract': result_abstract, 'result_extract': result_extract})
return abort(404)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=1234, debug=True)
<file_sep>/extract.py
import nltk
import numpy as np
from pyvi import ViTokenizer
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin_min
from gensim.models import KeyedVectors
from nltk.cluster.util import cosine_distance
import networkx as nx
def build_similarity_matrix(sentences):
# Create an empty similarity matrix
similarity_matrix = np.zeros((len(sentences), len(sentences)))
for idx1 in range(len(sentences)):
for idx2 in range(len(sentences)):
if idx1 == idx2: # ignore if both are same sentences
continue
similarity_matrix[idx1][idx2] = 1 - cosine_distance(sentences[idx1], sentences[idx2])
return similarity_matrix
class ExtractSummarization:
def __init__(self):
self.w2v = KeyedVectors.load_word2vec_format("vi.vec")
self.vocab = self.w2v.wv.vocab
@staticmethod
def output_size(input_size, max_size=10):
print('input_size ', input_size)
out_size = int(np.sqrt(input_size))
if out_size == 0:
out_size = input_size
if out_size > max_size:
out_size = max_size
return out_size
def run_textrank(self, text):
content = text.lower()
content = content.replace('\n', ' ')
content = content.strip()
sentences = nltk.sent_tokenize(content)
X = []
count = 0
for sentence in sentences:
words = ViTokenizer.tokenize(sentence).split(" ")
sentence_vec = np.zeros(100)
for word in words:
if word in self.vocab:
sentence_vec += self.w2v.wv[word]
count = count + 1
sentence_vec = sentence_vec / count
X.append(sentence_vec)
top_n = self.output_size(len(sentences))
sentence_similarity_matrix = build_similarity_matrix(X)
sentence_similarity_graph = nx.from_numpy_array(sentence_similarity_matrix)
scores = nx.pagerank(sentence_similarity_graph)
ranked_sentence_id = sorted(((scores[i], i) for i in range(len(sentences))), reverse=True)
summary_id = sorted((ranked_sentence_id[i][1] for i in range(top_n)), reverse=False)
summarize_text = "\n".join(sentences[i] for i in summary_id)
return summarize_text
def run_kmeans(self, content):
content = content.lower()
content = content.replace('\n', ' ')
content = content.strip()
sentences = nltk.sent_tokenize(content)
X = []
count = 0
for sentence in sentences:
words = ViTokenizer.tokenize(sentence).split(" ")
sentence_vec = np.zeros(100)
for word in words:
if word in self.vocab:
sentence_vec += self.w2v.wv[word]
count = count + 1
sentence_vec = sentence_vec / count
X.append(sentence_vec)
n_clusters = self.output_size(len(sentences))
kmeans = KMeans(n_clusters=n_clusters)
kmeans = kmeans.fit(X)
closest, _ = pairwise_distances_argmin_min(kmeans.cluster_centers_, X)
ordering = sorted(closest)
summarize_text = '\n'.join([sentences[idx] for idx in ordering])
return summarize_text
if __name__ == '__main__':
extract = ExtractSummarization()
with open("sumdata/train/valid.article.filter.txt", "r",
encoding="utf-8") as f:
paper = f.readlines()
print(extract.run_textrank(paper[0]))
|
899fac04d0ce3854249069f42910bbcbece569e2
|
[
"JavaScript",
"Python",
"Text",
"Markdown"
] | 6
|
Text
|
thangtran480/TextSummarization
|
023d4ea7fa593d5309e0b03097238bc9420397a9
|
339e54fce4bf4e1657b8b00dfb6f7329b4071e00
|
refs/heads/master
|
<repo_name>rulerliu/ext_transactional<file_sep>/src/main/java/com/transaction/aop/AopExtTransaction.java
package com.transaction.aop;
/**
* Created by Administrator on 2018/11/15 0015.
*/
import com.transaction.annotation.ExtTransaction;
import com.transaction.utils.TransactionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
/**
*
* 方法说明 环绕
* @version 1.0
* @date 2018/11/15 14:12
* @return java.lang.Object
* @exception
*/
// 定义切面可以让事务注解可以生效
@Aspect
@Component
public class AopExtTransaction {
@Autowired
private TransactionUtils transactionUtils;
//@Pointcut("execution(public * com.transaction.service.*.*(..))")
@Pointcut("@annotation(com.transaction.annotation.ExtTransaction)")
public void rlAop() {
}
// 使用异常通知 接受回滚事务
@AfterThrowing("rlAop()")
public void afterThrowing(JoinPoint point) {
System.out.println("afterThrowing");
// 获取当前事务状态
TransactionStatus transaction = transactionUtils.gteTransactionStatus();
if (transaction != null)
transactionUtils.rollback(transaction);
}
// 事务底层原理 采用那些通知?环绕和异常即可 注意单例线程安全问题
// 可以使用环绕通知对方法进行开启事务和提交事务 异常通知当程序抛出异常的情况下,进行回滚
@Around("rlAop()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("around");
// 1.判断方法上面是否有加上事务注解
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
ExtTransaction extTransaction = methodSignature.getMethod().getDeclaredAnnotation(ExtTransaction.class);
if (extTransaction == null) {// 方法上面没有加上注解执行原有方法
return pjp.proceed();
}
// 2.如果方法上加上事务直接的 开启或者是提交事务 proceed();执行原有方法
TransactionStatus transactionStatus = transactionUtils.begin();
Object proceed = pjp.proceed();// 执行原有方法
transactionUtils.commit(transactionStatus);
return proceed;
}
}
<file_sep>/src/main/java/com/transaction/annotation/ExtTransaction.java
package com.transaction.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 类说明
*
* @author wangyu
* @version 1.0
* @date $2018/11/15$ $11:10$
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtTransaction {
}
<file_sep>/src/main/java/com/transaction/mapper/UserMapper.java
package com.transaction.mapper;
import com.transaction.entity.User;
import org.apache.ibatis.annotations.Insert;
/**
* 类说明
*
* @author wangyu
* @version 1.0
* @date $2018/11/15$ $10:49$
*/
public interface UserMapper {
@Insert("INSERT INTO user(`name`, `age`) VALUES (#{name}, #{age}) ")
Integer addUser(User user);
}
|
b81a9da053a2c34bde6d1aebf3b014bfb27a4ce3
|
[
"Java"
] | 3
|
Java
|
rulerliu/ext_transactional
|
245909ff6172ea0966454b3d32f6e9d576d5fa67
|
77fda89ca16ce1c20211b0cc38cd455e587ee0a9
|
refs/heads/master
|
<file_sep>from google.appengine.ext import ndb
class ProfileImage(ndb.Model):
file_name = ndb.StringProperty()
image_file = ndb.BlobProperty()
class User(ndb.Model):
name = ndb.StringProperty()
datetime_created = ndb.DateTimeProperty(auto_now_add=True)
num_post = ndb.IntegerProperty()
num_follower = ndb.IntegerProperty()
num_following = ndb.IntegerProperty()
total_reply = ndb.IntegerProperty()
total_reply_to = ndb.IntegerProperty()
total_good_post = ndb.IntegerProperty()
total_neutral_post = ndb.IntegerProperty()
about = ndb.StringProperty()
profile_pic = ndb.KeyProperty(kind=ProfileImage)
private = ndb.BooleanProperty(default=False)
ip = ndb.StringProperty()
geo_location = ndb.StringProperty()
class Post(ndb.Model):
subject = ndb.StringProperty()
content = ndb.StringProperty()
view_count = ndb.IntegerProperty()
user_pk = ndb.KeyProperty(kind=User)
datetime_created = ndb.DateTimeProperty(auto_now_add=True)
num_high_fives = ndb.IntegerProperty()
num_low_fives = ndb.IntegerProperty()
replies = ndb.KeyProperty(kind='Post', repeated=True)
reply_tos = ndb.KeyProperty(kind='Post', repeated=True)
post_type = ndb.StringProperty(required=True, choices=['good', 'bad', 'neutral'])
ip = ndb.StringProperty()
geo_location = ndb.StringProperty()
class Image(ndb.Model):
post_pk = ndb.KeyProperty(kind=Post)
image_file = ndb.BlobProperty()
image_links = ndb.StringProperty(repeated=True)
user_pk = ndb.KeyProperty(kind=User)
description = ndb.StringProperty()
class Video(ndb.Model):
post_pk = ndb.KeyProperty(kind=Post)
video_file = ndb.BlobProperty()
video_links = ndb.StringProperty(repeated=True)
user_pk = ndb.KeyProperty(kind=User)
description = ndb.StringProperty()<file_sep>import webapp2
from google.appengine.ext.webapp import template
class MainPage(webapp2.RequestHandler):
def get(self):
html = template.render('template/index.html', {})
self.response.out.write(html)
app = webapp2.WSGIApplication([('/', MainPage)],
debug=True)
|
78e939cb6dd6301e5db591ff030be0f444b5429e
|
[
"Python"
] | 2
|
Python
|
peterchen16-zz/mood
|
984c2b440b12ec114ae37569c1df9d3d6763710a
|
7c49d6222c7afebe83bbd9c64e282d02845b1914
|
refs/heads/master
|
<file_sep><?php
/**
* Created by PhpStorm.
* User: aleksandr
* Date: 27.02.14
* Time: 2:15
*/
class Fgac_Application_Acl_Engine {
const REGISTRY_ALIAS = "fgac-acl";
const SESSION_ALIAS = "fgac-acl";
static protected $_instance;
static protected $_options;
static public function setup($options) {
self::$_options = $options;
}
static public function getInstance() {
if (null === self::$_instance) {
$session = new Zend_Session_Namespace(self::SESSION_ALIAS);
if (null !== $session->fgac) {
self::$_instance = unserialize($session->fgac);
} else {
self::$_instance = new self(self::$_options);
$session->fgac = serialize(self::$_instance);
}
}
return self::$_instance;
}
protected function __construct($options) {
$this->setOptions($options);
}
protected $_rules = array();
protected $_tables = array();
protected $_aclAlias;
public function setAclAlias($alias) {
$this->_aclAlias = $alias;
}
public function getAclAlias() {
return $this->_aclAlias;
}
/**
* @return Zend_Log
*/
protected function getLogger() {
return Zend_Registry::get('logger')->ensureStream('fgac');
}
protected function setOptions($options) {
if ("yes" !== $options['enabled']) return;
$this->getLogger()->log("FGAC Plugin initialization", Zend_Log::DEBUG);
$this->setAclAlias($options['acl-alias']);
// loading data from application.ini
if (isset($options['rule'])) {
foreach($options['rule'] as $rule => $ruleOptions) {
$this->getLogger()->log("Rule (config):: \"$rule\"", Zend_Log::DEBUG);
$this->addRule($ruleOptions['plugin'], array(
'tables' => explode(",", $ruleOptions['tables']),
'roles' => explode(",", $ruleOptions['roles']),
));
}
}
// loading data from DB storage
$table = new Fgac_Application_Db_FgacAcl();
$rules = $table->getFull();
if ($rules->count() > 0) {
foreach($rules as $rule) {
$this->getLogger()->log("Rule (db):: \"" . $rule->name . "\"", Zend_Log::DEBUG);
$this->addRule($rule->plugin, array(
'tables' => $rule->table_name,
'roles' => $rule->code,
));
}
}
}
public function addRule($rule, $options) {
$table = $options['tables'];
$roles = $options['roles'];
if (null === $this->_rules[$rule]) {
$this->_rules[$rule] = new Fgac_Application_Acl_Rule($rule, $table, $roles);
} else {
/**
* @var $ruleObject Fgac_Application_Acl_Rule
*/
$ruleObject = $this->_rules[$rule];
$ruleObject->addRoles($roles);
$ruleObject->addTables($table);
}
if (null === $this->_tables[$table]) {
$this->_tables[$table] = array($rule);
} elseif (!in_array($rule, $this->_tables[$table])) {
$this->_tables[$table][] = $rule;
}
$this->fixate();
}
public function hasRule($table, $roles = array()) {
if (array_key_exists($table, $this->_tables)) {
if (empty($roles))
return true;
foreach ($this->_tables[$table] as $rule) {
/**
* @var $ruleObject Fgac_Application_Acl_Rule
*/
$ruleObject = $this->_rules[$rule];
if ($ruleObject->assert($table, $roles)) {
return true;
}
}
}
return false;
}
public function invoke($table, $roles, Pro_Db_Select &$select) {
if (array_key_exists($table, $this->_tables)) {
foreach ($this->_tables[$table] as $rule) {
/**
* @var $ruleObject Fgac_Application_Acl_Rule
*/
$ruleObject = $this->_rules[$rule];
if ($ruleObject->assert($table, $roles)) {
$ruleObject->invoke($select);
}
}
}
}
protected function fixate() {
$session = new Zend_Session_Namespace(self::SESSION_ALIAS);
$session->fgac = serialize(self::$_instance);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: aleksandr
* Date: 27.02.14
* Time: 2:15
*/
class Fgac_Application_Acl_DbPlugin extends Pro_Db_Plugin_PluginAbstract {
public function beforeFetch($tableName, Pro_Db_Select &$select) {
$fgac = Fgac_Application_Acl_Engine::getInstance();
$acl = Zend_Registry::get($fgac->getAclAlias());
$fgac->invoke($tableName, $acl->getCurrentHierarchy(), $select);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: aleksandr
* Date: 27.02.14
* Time: 2:41
*/
class Fgac_Application_Acl_Resource_Fgac extends Zend_Application_Resource_ResourceAbstract {
public function init() {
$this->getBootstrap()->bootstrap('logger');
$this->getBootstrap()->bootstrap('acl');
Fgac_Application_Acl_Engine::setup($this->getOptions());
return Fgac_Application_Acl_Engine::getInstance();
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: aleksandr
* Date: 27.02.14
* Time: 3:53
*/
class Fgac_Application_Plugins_Account implements Fgac_Application_Plugins_PluginInterface {
public function addRule(Zend_Db_Table_Select &$select) {
$select->join(array("acc" => "account"), "acc.id = account_id");
}
}<file_sep>[production]
resource.fgac.enabled = "yes"
; used for getting current Zend_Acl implementation from Zend_Registry
resource.fgac.acl-alias = "acl"
resource.fgac.rule.trader-default.plugin = "Fgac_Application_Plugins_Trdaer"
resource.fgac.rule.trader-default.roles = "trader:demo"
resource.fgac.rule.trader-default.tables = "table1,table2"
resource.fgac.rule.account-default.plugin = "Fgac_Application_Plugins_Account"
resource.fgac.rule.account-default.roles = "trader:demo"
resource.fgac.rule.account-default.tables = "table1,table2"<file_sep><?php
/**
* Created by PhpStorm.
* User: aleksandr
* Date: 27.02.14
* Time: 3:53
*/
class Fgac_Application_Plugins_Trader implements Fgac_Application_Plugins_PluginInterface {
public function addRule(Zend_Db_Table_Select &$select) {
$select->join(array("tr" => "trader"), "tr.id = trader_id");
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: aleksandr
* Date: 27.02.14
* Time: 13:59
*/
interface Fgac_Application_Plugins_PluginInterface {
public function addRule(Zend_Db_Table_Select &$select);
}<file_sep><?php
/**
* Created by PhpStorm.
* User: aleksandr
* Date: 27.02.14
* Time: 14:56
*/
class Fgac_Application_Acl_Rule {
const ANY_ROLE = "*";
protected $_rule;
protected $_tables = array();
protected $_roles = array();
public function __construct($rule, $tables, $roles = array()) {
$this->_rule = $rule;
$this->addTables($tables);
$this->addRoles($roles);
}
public function addTables($tables) {
if (is_array($tables)) {
foreach($tables as $table) {
$this->addTable($table);
}
} else {
$this->addTable($tables);
}
}
public function addTable($table) {
if (null !== $table && !in_array($table, $this->_tables))
$this->_tables[] = $table;
}
public function addRoles($roles) {
if (is_array($roles)) {
foreach ($roles as $role) {
$this->addRole($role);
}
} else {
$this->addRole($roles);
}
}
public function addRole($role) {
if (null !== $role && !in_array($role, $this->_roles)) {
$this->_roles[] = $role;
}
}
/**
* @param string $table
* @param array|null $roles
* @return bool
*/
public function assert($table, $roles = null) {
if (in_array($table, $this->_tables)) {
if (null === $roles || self::ANY_ROLE == $roles)
return true;
foreach ($roles as $role) {
if (in_array($role, $this->_roles))
return true;
}
}
return false;
}
public function invoke(Pro_Db_Select &$select) {
if ($this->_rule instanceof Fgac_Application_Plugins_PluginInterface) {
$this->_rule->addRule($select);
} else {
$ruleClass = $this->_rule;
/** @var $rule Fgac_Application_Plugins_PluginInterface */
$rule = new $ruleClass();
$rule->addRule($select);
}
}
}<file_sep>
create table fgac_rules (
id bigint(11) not null auto_increment,
`name` varchar(140) not null,
`table_name` varchar(140) not null ,
plugin varchar (140) not null ,
primary key (id)
);
create table fgac_acl (
fgac_id bigint(11) not null ,
role_id bigint(11) not null ,
primary key (fgac_id, role_id),
foreign key (fgac_id) references fgac_rules (id),
foreign key (role_id) references acl_roles (id)
);<file_sep><?php
/**
* Created by PhpStorm.
* User: aleksandr
* Date: 27.02.14
* Time: 14:14
*/
class Fgac_Application_Db_FgacRules extends Pro_Db_Table {
protected $_name = "fgac_rules";
}<file_sep><?php
/**
* Created by PhpStorm.
* User: aleksandr
* Date: 27.02.14
* Time: 14:25
*/
class Fgac_Application_Db_FgacAcl extends Pro_Db_Table {
protected $_name = "fgac_acl";
public function getFull() {
$select = $this->select()
->setIntegrityCheck(false)
->join(array("fr" => "fgac_rules"), "fr.id = fgac_id")
->join(array("acl" => "acl_roles"), "acl.id = role_id");
return $this->fetchAll($select);
}
}
|
611db371a6e799615e056be17034fc77d9effcaf
|
[
"SQL",
"PHP",
"INI"
] | 11
|
PHP
|
qshurick/pro_fgac
|
7ac467d2f0ccdeaef3cd391304835a9bb4e10739
|
8a6fb465cfbb26107e9307e9b84bcfe6a4da80a3
|
refs/heads/master
|
<file_sep>import React, {Component} from 'react'
const d3 = require('d3');
export default class NewEntryForm extends Component {
render() {
return(
<form className="new-entry-form" onSubmit={this.props.handleNewEntry}>
<div>
<input type="text" name="newEntryTitle" className="new-entry-title" placeholder="New entry" value={this.props.newEntryTitle} onChange={this.props.onInputChange}/>
<input type="number" name="newEntryNumber" className="new-entry-number" placeholder="0" value={this.props.newEntryNumber} onChange={this.props.onInputChange}/>
</div>
<div>
<input type="submit"/>
</div>
</form>
)
}
}
|
c9395b37d0d2bca9aab264da2ffd1d2de73c2c0f
|
[
"JavaScript"
] | 1
|
JavaScript
|
emmabckstrm/hello-react-piechart
|
31b558711219bd3ba5e8a8d297586e89b2a2b6d9
|
242487e4500f5dcb21fd86db47a77a8dd71aa8f7
|
refs/heads/main
|
<repo_name>IgorBekerskyy/Web_labs-6-11<file_sep>/src/Navigation/Navigation.js
import React from 'react';
import { NavList, NavUl, Navigat } from './Navigation.styled';
import {Switch, BrowserRouter as Router, Route, NavLink} from "react-router-dom";
import Home from "../Home/Home";
const Navigation = () => {
return(
<Router>
<Navigat>
<NavUl>
<NavList>
<NavLink exact to="/" activeClassName="selected">HOME</NavLink>
</NavList>
<NavList>
<NavLink exact to="/planes" activeClassName="selected">PLANES</NavLink>
</NavList>
<NavList>
<NavLink exact to="/sale" activeClassName="selected" >SALES</NavLink>
</NavList>
</NavUl>
<Switch>
<Route path="/planes">
<div> It is list of planes</div>
</Route>
<Route path="/sale">
<div> It is list of sales</div>
</Route>
<Route path="/">
<Home/>
</Route>
</Switch>
</Navigat>
</Router>);
};
export default Navigation;<file_sep>/src/container/Home/Home.js
import React from 'react';
import {Advertisment, AdvertismentTitle, AdvertismentText, ShowMoreBtn, MostPopular, MostPopularTitle, Cards, Slider, Dots, HomePage} from './Home.styled'
import {ReactComponent as Line } from "./../../icons/line.svg";
import {ReactComponent as LeftBtn } from "./../../icons/LeftBtn.svg";
import {ReactComponent as RightBtn } from "./../../icons/RightBtn.svg";
import {ReactComponent as ActiveDot } from "./../../icons/ActiveDot.svg";
import {ReactComponent as Dot } from "./../../icons/Dot.svg";
import kyiv from "./../../icons/34200.jpg";
import karpaty from "./../../icons/83ed9178f6d0cccf5cf63ce3e31e6c4c.jpg";
import CardItem from './../../components/CardItem/CardsItem'
const data = [
{
placePhoto: kyiv,
name: 'Kyiv',
time: 'night',
priceInUAH: 2500,
height: 2000,
},
{
placePhoto: karpaty,
name: 'Karpaty',
time: 'afternoon',
priceInUAH: 3500,
height: 3000,
},
];
const Home = () => {
return(
<HomePage>
<Advertisment>
<AdvertismentTitle>Flights over city </AdvertismentTitle>
<AdvertismentText>If you want to enjoy the view of Ukrainian cities from a height, click below </AdvertismentText>
<ShowMoreBtn>Show me more</ShowMoreBtn>
</Advertisment>
<MostPopular>
<MostPopularTitle>
<Line/>
<p>The most popular landscapes</p>
<Line/>
</MostPopularTitle>
<Cards>
{data.map(({placePhoto, name, time, priceInUAH, height }, idx) => (
<CardItem
placePhoto={placePhoto}
name={name}
time={time}
priceInUAH={priceInUAH}
height={height}
id={idx}
/>
))}
</Cards>
<Slider>
<LeftBtn/>
<Dots>
<ActiveDot/>
<Dot/>
<Dot/>
<Dot/>
</Dots>
<RightBtn/>
</Slider>
</MostPopular>
</HomePage>);
};
export default Home;<file_sep>/README.md
# Web_labs-6-11<file_sep>/src/components/CardItem/CardsItem.js
import React from 'react';
import {CardContainer, BootsPhoto, CardInfo, CardTitle, CardDescription, Price, ShopNowBtn} from './CardsItem.styled';
const CardItem = ({placePhoto, name, time, height, priceInUAH}) => {
return (
<CardContainer>
<BootsPhoto src={placePhoto}/>
<CardInfo>
<CardTitle>Journey</CardTitle>
<CardDescription> {name} {time} landscape, with height of flight {height} metres. </CardDescription>
<Price>$ {priceInUAH}</Price>
<ShopNowBtn>Reserve</ShopNowBtn>
</CardInfo>
</CardContainer>
);
};
export default CardItem;
|
b4eaabc041ea6b5f59f7ff106e8594efad332c90
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
IgorBekerskyy/Web_labs-6-11
|
afb6d31de3df43147f79184fd402f5eb5d8491b6
|
988f3506442b26d4a0a573308b65be3f84a3f0ff
|
refs/heads/master
|
<file_sep>
# coding: utf-8
# In[ ]:
import math
from math import pi
import copy
import cv2
import numpy as np
img = cv2.imread("task2.jpg", 0)
image=list(img)
#Function to form the Gaussian kernel
def GaussianKernel(height,width,sigma):
total=0
Gkernel1=[]
#Creating an empty list to store the Gaussian kernel
for i in range(height):
Gkernel1.append([0]*width)
#Calculating each element value for the given sigma
for cols,i in zip(range(0,width),range(-3,4)):
for rows,j in zip(range(0,height),range(3,-4,-1)):
ival=0
val=0
ival=math.exp((-1*((i**2)+(j**2)))/(2*(sigma**2)))
val=(1/(2*pi*sigma**2))*ival
Gkernel1[rows][cols]=val
total=total+val
Gkernel1=[[x/total for x in lst] for lst in Gkernel1]
return Gkernel1
#Convolution Function to perform Convolution of the image with the gaussian kernel
def conv_func(image,kernel):
rows=len(image)
cols=len(image[0])
krows=len(kernel)
kcols=len(kernel[0])
gx = copy.deepcopy(image)
# find center position of kernel (half of kernel size)
kCenterX = kcols // 2
kCenterY = krows // 2
for i in range(rows):
for j in range(cols):
sum=0
for m in range(krows):
mm = krows - 1 - m;
for n in range(kcols):
nn = kcols - 1 - n
ii = i + (kCenterY - mm)
jj = j + (kCenterX - nn)
# ignore input samples which are out of bound
if( ii >= 0 and ii < rows and jj >= 0 and jj < cols ):
sum += image[ii][jj] * kernel[mm][nn]
if sum > 255:
sum = 255
if sum < 0:
sum = 0
gx[i][j]=sum
return gx
########Forming the first octave#####
gkernel_1Oct=[] #initialising empty list to hold the different gaussian kernel for 1st octave
BlurImg_1stOct=[] #initialising empty list to hold the different blurred image for 1st octave
gkernel_1Oct.append(GaussianKernel(7,7,0.707))
BlurImg_1stOct.append(conv_func(image, gkernel_1Oct[0]))
Bimage1_1=np.asarray(BlurImg_1stOct[0])
gkernel_1Oct.append(GaussianKernel(7,7,1))
BlurImg_1stOct.append(conv_func(image, gkernel_1Oct[1]))
Bimage1_2=np.asarray(BlurImg_1stOct[1])
gkernel_1Oct.append(GaussianKernel(7,7,1.414))
BlurImg_1stOct.append(conv_func(image,gkernel_1Oct[2]))
Bimage1_3=np.asarray(BlurImg_1stOct[2])
gkernel_1Oct.append(GaussianKernel(7,7,2))
BlurImg_1stOct.append(conv_func(image,gkernel_1Oct[3]))
Bimage1_4=np.asarray(BlurImg_1stOct[3])
gkernel_1Oct.append(GaussianKernel(7,7,2.828))
BlurImg_1stOct.append(conv_func(image,gkernel_1Oct[4]))
Bimage1_5=np.asarray(BlurImg_1stOct[4])
########Forming the 2nd octave#####
#Scaling the image by half
image2col=[row[0::2] for row in image]
image2=image2col[0::2]
image2_s=np.asarray(image2)
cv2.imwrite('2nd_Octave_Scaled_Image.png',image2_s)
print('2nd Octave Scaled Image resolution is: ',len(image2),',',len(image2[0]))
gkernel_2Oct=[] #initialising empty list to hold the different gaussian kernel for 2ns octave
BlurImg_2Oct=[] #initialising empty list to hold the different blurred image for 2nd octave
gkernel_2Oct.append(GaussianKernel(7,7,1.414))
BlurImg_2Oct.append(conv_func(image2,gkernel_2Oct[0]))
Bimage2_1=np.asarray(BlurImg_2Oct[0])
gkernel_2Oct.append(GaussianKernel(7,7,2))
BlurImg_2Oct.append(conv_func(image2,gkernel_2Oct[1]))
Bimage2_2=np.asarray(BlurImg_2Oct[1])
gkernel_2Oct.append(GaussianKernel(7,7,2.828))
BlurImg_2Oct.append(conv_func(image2,gkernel_2Oct[2]))
Bimage2_3=np.asarray(BlurImg_2Oct[2])
gkernel_2Oct.append(GaussianKernel(7,7,4))
BlurImg_2Oct.append(conv_func(image2,gkernel_2Oct[3]))
Bimage2_4=np.asarray(BlurImg_2Oct[3])
gkernel_2Oct.append(GaussianKernel(7,7,5.656))
BlurImg_2Oct.append(conv_func(image2,gkernel_2Oct[4]))
Bimage2_5=np.asarray(BlurImg_2Oct[4])
########Forming the 3rd octave#####
#Scaling the image by half
image3col=[row[0::2] for row in image2]
image3=image3col[0::2]
image3_s=np.asarray(image3)
cv2.imwrite('3rd_Octave_Scaled_Image.png',image3_s)
print('3rd Octave Scaled Image resolution is: ',len(image3),',',len(image3[0]))
gkernel_3Oct=[] #initialising empty list to hold the different gaussian kernel for 2ns octave
BlurImg_3Oct=[] #initialising empty list to hold the different blurred image for 2nd octave
gkernel_3Oct.append(GaussianKernel(7,7,2.828))
BlurImg_3Oct.append(conv_func(image3,gkernel_3Oct[0]))
Bimage3_1=np.asarray(BlurImg_3Oct[0])
gkernel_3Oct.append(GaussianKernel(7,7,4))
BlurImg_3Oct.append(conv_func(image3,gkernel_3Oct[1]))
Bimage3_2=np.asarray(BlurImg_3Oct[1])
gkernel_3Oct.append(GaussianKernel(7,7,5.656))
BlurImg_3Oct.append(conv_func(image3,gkernel_3Oct[2]))
Bimage3_3=np.asarray(BlurImg_3Oct[2])
gkernel_3Oct.append(GaussianKernel(7,7,8))
BlurImg_3Oct.append(conv_func(image3,gkernel_3Oct[3]))
Bimage3_4=np.asarray(BlurImg_3Oct[3])
gkernel_3Oct.append(GaussianKernel(7,7,11.313))
BlurImg_3Oct.append(conv_func(image3,gkernel_3Oct[4]))
Bimage3_5=np.asarray(BlurImg_3Oct[4])
########Forming the 4th octave#####
#Scaling the image by half
image4col=[row[0::2] for row in image3]
image4=image4col[0::2]
gkernel_4Oct=[] #initialising empty list to hold the different gaussian kernel for 2ns octave
BlurImg_4Oct=[] #initialising empty list to hold the different blurred image for 2nd octave
gkernel_4Oct.append(GaussianKernel(7,7,5.656))
BlurImg_4Oct.append(conv_func(image4,gkernel_4Oct[0]))
Bimage4_1=np.asarray(BlurImg_4Oct[0])
gkernel_4Oct.append(GaussianKernel(7,7,8))
BlurImg_4Oct.append(conv_func(image4,gkernel_4Oct[1]))
Bimage4_2=np.asarray(BlurImg_4Oct[1])
gkernel_4Oct.append(GaussianKernel(7,7,11.313))
BlurImg_4Oct.append(conv_func(image4,gkernel_4Oct[2]))
Bimage4_3=np.asarray(BlurImg_4Oct[2])
gkernel_4Oct.append(GaussianKernel(7,7,16))
BlurImg_4Oct.append(conv_func(image4,gkernel_4Oct[3]))
Bimage4_4=np.asarray(BlurImg_4Oct[3])
gkernel_4Oct.append(GaussianKernel(7,7,22.627))
BlurImg_4Oct.append(conv_func(image4,gkernel_4Oct[4]))
Bimage4_5=np.asarray(BlurImg_4Oct[4])
######Creating DoGs for first octave#####
DoG1_1=Bimage1_1 - Bimage1_2
DoG1_2=Bimage1_2 - Bimage1_3
DoG1_3=Bimage1_3 - Bimage1_4
DoG1_4=Bimage1_4 - Bimage1_5
DoG2_1=Bimage2_1 - Bimage2_2
DoG2_2=Bimage2_2 - Bimage2_3
DoG2_3=Bimage2_3 - Bimage2_4
DoG2_4=Bimage2_4 - Bimage2_5
cv2.imwrite('2nd_Octave_1st_DoG.png',DoG2_1)
cv2.imwrite('2nd_Octave_2nd_DoG.png',DoG2_2)
cv2.imwrite('2nd_Octave_3rd_DoG.png',DoG2_3)
cv2.imwrite('2nd_Octave_4th_DoG.png',DoG2_4)
DoG3_1=Bimage3_1 - Bimage3_2
DoG3_2=Bimage3_2 - Bimage3_3
DoG3_3=Bimage3_3 - Bimage3_4
DoG3_4=Bimage3_4 - Bimage3_5
cv2.imwrite('3rd_Octave_1st_DoG.png',DoG3_1)
cv2.imwrite('3rd_Octave_2nd_DoG.png',DoG3_2)
cv2.imwrite('3rd_Octave_3rd_DoG.png',DoG3_3)
cv2.imwrite('3rd_Octave_4th_DoG.png',DoG3_4)
DoG4_1=Bimage4_1 - Bimage4_2
DoG4_2=Bimage4_2 - Bimage4_3
DoG4_3=Bimage4_3 - Bimage4_4
DoG4_4=Bimage4_4 - Bimage4_5
#####Finding points of maxima and minima in each Octave
DoG1_1_lst=list(DoG1_1)
DoG1_2_lst=list(DoG1_2)
DoG1_3_lst=list(DoG1_3)
DoG1_4_lst=list(DoG1_4)
DoG1_11=[]
DoG1_11.append(DoG1_1_lst)
DoG1_11.append(DoG1_2_lst)
DoG1_11.append(DoG1_3_lst)
DoG1_11.append(DoG1_4_lst)
#finding points of minima/maxima for 1st octave
for i in range(1,len(DoG1_11[0])-1):
for j in range(1,len(DoG1_11[0][0])-1):
for k in range(0,len(DoG1_11)-1):
if(DoG1_11[1][i][j]>=DoG1_11[k][i][j] or DoG1_11[1][i][j]<DoG1_11[k][i][j]):
DoG1_11[1][i][k]=255
for i in range(1,len(DoG1_11[2])-1):
for j in range(1,len(DoG1_11[2][0])-1):
for k in range(1,len(DoG1_11)):
if(DoG1_11[2][i][j]>=DoG1_11[k][i][j] or DoG1_11[2][i][j]<DoG1_11[k][i][j]):
DoG1_11[2][i][k]=255
#2nd octave
DoG2_1_lst=list(DoG2_1)
DoG2_2_lst=list(DoG2_2)
DoG2_3_lst=list(DoG2_3)
DoG2_4_lst=list(DoG2_4)
DoG2_11=[]
DoG2_11.append(DoG2_1_lst)
DoG2_11.append(DoG2_2_lst)
DoG2_11.append(DoG2_3_lst)
DoG2_11.append(DoG2_4_lst)
#finding points of minima/maxima for 2nd octave
for i in range(1,len(DoG2_11[0])-1):
for j in range(1,len(DoG2_11[0][0])-1):
for k in range(0,len(DoG2_11)-1):
if(DoG2_11[1][i][j]>=DoG2_11[k][i][j] or DoG2_11[1][i][j]<DoG2_11[k][i][j]):
DoG2_11[1][i][k]=255
for i in range(1,len(DoG2_11[2])-1):
for j in range(1,len(DoG2_11[2][0])-1):
for k in range(1,len(DoG2_11)):
if(DoG2_11[2][i][j]>=DoG2_11[k][i][j] or DoG2_11[2][i][j]<DoG2_11[k][i][j]):
DoG2_11[2][i][k]=255
for i in range(len(DoG2_11[1])):
for j in range(len(DoG2_11[1][0])):
if(DoG2_11[1][i][j]<255):
DoG2_11[1][i][j]=0
if(DoG2_11[1][i][j]==255):
image[i*2][j*2]=255
image_detected=np.asarray(image)
#cv2.imshow('first detection',image_detected)
cv2.imwrite('1st_image_showing_detected_Keypoints_in_white_from_second_octave.png',image_detected)
###Co-ordinates of the five lefmost detected points
cntr=0
for i in range(len(image)//2):
for j in range(len(image[0]//2)):
if (image[i][j]==255):
cntr=cntr+1
print('The five leftmost detected points in second octave 1st image are: ',i,',',j)
if(cntr==5):
break
else:
continue # only executed if the inner loop did NOT break
break # only executed if the inner loop DID break
img = cv2.imread("task2.jpg", 0)
image=list(img)
for i in range(len(DoG2_11[2])):
for j in range(len(DoG2_11[2][0])):
if(DoG2_11[2][i][j]<255):
DoG2_11[2][i][j]=0
if(DoG2_11[2][i][j]==255):
image[i*2][j*2]=255
image_detected=np.asarray(image)
cv2.imwrite('2nd_image_showing_detected_Keypoints_in_white_from_second_octave.png',image_detected)
cntr=0
for i in range(len(image)//2):
for j in range(len(image[0]//2)):
if (image[i][j]==255):
cntr=cntr+1
print('The five leftmost detected points in second octave 2nd image are: ',i,',',j)
if(cntr==5):
break
else:
continue # only executed if the inner loop did NOT break
break # only executed if the inner loop DID break
#3rd octave
DoG3_1_lst=list(DoG3_1)
DoG3_2_lst=list(DoG3_2)
DoG3_3_lst=list(DoG3_3)
DoG3_4_lst=list(DoG3_4)
DoG3_11=[]
DoG3_11.append(DoG3_1_lst)
DoG3_11.append(DoG3_2_lst)
DoG3_11.append(DoG3_3_lst)
DoG3_11.append(DoG3_4_lst)
#finding points of minima/maxima for 3rd octave
for i in range(1,len(DoG3_11[0])-1):
for j in range(1,len(DoG3_11[0][0])-1):
for k in range(0,len(DoG3_11)-1):
if(DoG3_11[1][i][j]>=DoG3_11[k][i][j] or DoG3_11[1][i][j]<DoG3_11[k][i][j]):
DoG3_11[1][i][k]=255
for i in range(1,len(DoG3_11[2])-1):
for j in range(1,len(DoG3_11[2][0])-1):
for k in range(1,len(DoG3_11)):
if(DoG3_11[2][i][j]>=DoG3_11[k][i][j] or DoG3_11[2][i][j]<DoG3_11[k][i][j]):
DoG3_11[2][i][k]=255
img = cv2.imread("task2.jpg", 0)
image=list(img)
for i in range(len(DoG3_11[1])):
for j in range(len(DoG3_11[1][0])):
if(DoG3_11[1][i][j]<255):
DoG3_11[1][i][j]=0
if(DoG3_11[1][i][j]==255):
image[i*4][j*4]=255
image_detected=np.asarray(image)
cv2.imwrite('1st_image_showing_detected_Keypoints_in_white_from_third_octave.png',image_detected)
cntr=0
for i in range(len(image)//2):
for j in range(len(image[0]//2)):
if (image[i][j]==255):
cntr=cntr+1
print('The five leftmost detected points in 3rd octave 1st image are: ',i,',',j )
if(cntr==5):
break
else:
continue # only executed if the inner loop did NOT break
break # only executed if the inner loop DID break
img = cv2.imread("task2.jpg", 0)
image=list(img)
for i in range(len(DoG3_11[2])):
for j in range(len(DoG3_11[2][0])):
if(DoG3_11[2][i][j]<255):
DoG3_11[2][i][j]=0
if(DoG3_11[2][i][j]==255):
image[i*4][j*4]=255
image_detected=np.asarray(image)
cv2.imwrite('2nd_image_showing_detected_Keypoints_in_white_from_third_octave.png',image_detected)
cntr=0
for i in range(len(image)//2):
for j in range(len(image[0]//2)):
if (image[i][j]==255):
cntr=cntr+1
print('The five leftmost detected points in 3rd octave 2nd image are: ',i,',',j )
if(cntr==5):
break
else:
continue # only executed if the inner loop did NOT break
break # only executed if the inner loop DID break
#4th octave
DoG4_1_lst=list(DoG4_1)
DoG4_2_lst=list(DoG4_2)
DoG4_3_lst=list(DoG4_3)
DoG4_4_lst=list(DoG4_4)
DoG4_11=[]
DoG4_11.append(DoG4_1_lst)
DoG4_11.append(DoG4_2_lst)
DoG4_11.append(DoG4_3_lst)
DoG4_11.append(DoG4_4_lst)
#finding points of minima/maxima for 1st octave
for i in range(1,len(DoG4_11[0])-1):
for j in range(1,len(DoG4_11[0][0])-1):
for k in range(0,len(DoG4_11)-1):
if(DoG4_11[1][i][j]>=DoG4_11[k][i][j] or DoG4_11[1][i][j]<DoG4_11[k][i][j]):
DoG4_11[1][i][k]=255
for i in range(1,len(DoG4_11[2])-1):
for j in range(1,len(DoG4_11[2][0])-1):
for k in range(1,len(DoG4_11)):
if(DoG4_11[2][i][j]>=DoG4_11[k][i][j] or DoG4_11[2][i][j]<DoG4_11[k][i][j]):
DoG4_11[2][i][k]=255
img = cv2.imread("task2.jpg", 0)
image=list(img)
for i in range(len(DoG4_11[1])):
for j in range(len(DoG4_11[1][0])):
if(DoG4_11[1][i][j]<255):
DoG4_11[1][i][j]=0
if(DoG4_11[1][i][j]==255):
image[i*8][j*8]=255
img = cv2.imread("task2.jpg", 0)
image=list(img)
for i in range(len(DoG4_11[2])):
for j in range(len(DoG4_11[2][0])):
if(DoG4_11[2][i][j]<255):
DoG4_11[2][i][j]=0
if(DoG4_11[2][i][j]==255):
image[i*8][j*8]=255
cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep># Keypont-Detection
Key Point Detection using SIFT in pure Python
The aim of this project was to to detect keypoints in an image according to the following steps, which are also the first three
steps of Scale-Invariant Feature Transform (SIFT).
1. Generating four octaves. Each octave is composed of five images blurred using Gaussian kernels. For each
octave, the bandwidth parameters σ (five different scales) of the Gaussian kernels.
2. Computing Difference of Gaussian (DoG) for all four octaves.
3. Detecting keypoints which are located at the maxima or minima of the DoG images. Only
pixel-level locations of the keypoints is needed to be shown.
|
7b9b05663b28f0140b140a6332e686bf049e4779
|
[
"Markdown",
"Python"
] | 2
|
Python
|
ktrishala/Keypont-Detection
|
9eb695b9ba9868b8db1f6e9ddfac8408ce4567ba
|
ef8a283921c4544fb551b11a1b887f685724e570
|
refs/heads/master
|
<file_sep>package interview.lnkd;
/**
* Given a String implement the conversion to Integer
* @author <EMAIL>
*
*/
public class MyInteger {
public int parseInt(String input) throws NumberFormatException{
int result=0;
boolean is_negative = false;
char[] chars = input.toCharArray();
for(char c : chars){
if(c=='-'){
is_negative = true;
continue;
}else if(Character.isLetter(c)){
throw new NumberFormatException("Provide a valid numeric input");
}
int ic = (int)(c -'0');
result = 10*result + ic;
}
if(is_negative)
result = (-1)* result;
return result;
}
public static void main(String[] args){
System.out.println(new MyInteger().parseInt("123"));
}
}
<file_sep>package interview.tenor;
/**
* ConnectFour Game implementation like mentioned here ....https://en.wikipedia.org/wiki/Connect_Four
* @author <EMAIL>
* Interview Question: Tenor (formerly Riffsy, Inc)
*/
public class ConnectGame {
public static final char BLANK = '-';
public static final char SPACE = ' ';
public static final int ROWMAX = 6;
public static final int COLMAX = 7;
public static final int MIN = 0;
public static final int WINSEQ=4;
Board board;
Player player1 , player2;
private Player currentPlayer;
int player1Wins=0,player2Wins=0;
public enum Player {
X('x'), O('o');
char c;
Player(char cin){
c=cin;
}
char getChar(){
return c;
}
};
public ConnectGame(Player pl1 , Player pl2){
board = new Board();
this.player1 = pl1;
this.player2 = pl2;
this.currentPlayer = pl1;
}
public Board getBoard(){
return this.board;
}
public Player getCurrentPlayer(){
return this.currentPlayer;
}
public void setCurrentPlayer(Player curplayer){
this.currentPlayer = curplayer;
}
public void swapPlayer(){
if(getCurrentPlayer()== this.player1){
setCurrentPlayer(this.player2);
}else{
setCurrentPlayer(this.player1);
}
}
public static int getRandomRows(){
return (int)( Math.random()*((ROWMAX-MIN) ) + MIN); // "exclusive" of max values ...
}
public static int getRandomCols(){
return (int)( Math.random()*((COLMAX-MIN) ) + MIN);
}
//inner Board class
class Board{
private char [][] cells;
private Player currentPlayer ;
Board(){
cells = new char[ROWMAX][COLMAX];
initialize();
}
void initialize(){
for(int rowid=0;rowid<ROWMAX;rowid++){
for(int colid=0;colid<COLMAX;colid++){
cells[rowid][colid] =BLANK;
}
}
//display();
}
/**
* Coins would drop down so automatically start stacking from bottom of the board!
* @param rowid - intended row id
* @param col - intended column id
* @param player - current player marking the board
* @return success - if it was placed within the same column starting @ the highest available row...
*/
boolean dropCoin(int row, int col , Player player){
boolean rval = false;
for(int rowid=ROWMAX-1;rowid>=row;rowid--){//reverse from the bottom of the board
if(cells[rowid][col]==BLANK){ //found an empty larger row
cells[rowid][col]= player.getChar();//fill it. and quit
rval = true;
break;
}
}
return rval;
}
/**
* Check at Every element "if there was a move possible" along the following direction
* in forward(same row ),
* downwards(same column),
* diagonally downwards,
* reverse-diagonal - diagonally upwards
* within the board for specified number of winning steps +3
* if possible Get the sequences of the same type x/o in these direction ...
* check if equals or greater than 4
*/
public void countWins(){
//Count player X wins
player1Wins=0;
player2Wins=0;
for(int rowid=0;rowid<ROWMAX;rowid++){
for(int colid=0;colid<COLMAX;colid++){
boolean can_gofwd=false, can_godown=false, can_godiag=false, can_revdiag=false;
//find the 3 forward points in same row
if(colid+(WINSEQ-1) < COLMAX)
can_gofwd=true;
//find the 3 downward points in same col
if(rowid+(WINSEQ-1) < ROWMAX)
can_godown=true;
//find the 3 next diag points
if((rowid+(WINSEQ-1) < ROWMAX) && (colid+(WINSEQ-1) < COLMAX) )
can_godiag=true;
//find the 3 next reverse-diag points
if((rowid-(WINSEQ-1) >= MIN) && (colid+(WINSEQ-1) < COLMAX) )
can_revdiag=true;
if(can_gofwd) {
//get foward cells ...
char c1 = cells[rowid][colid];
char c2 = cells[rowid][colid+1];
char c3 = cells[rowid][colid+2];
char c4 = cells[rowid][colid+3];
if((c1==c2)&&(c1==c3)&&(c1==c4)&& (c1!=BLANK)){
if(c1==Player.X.getChar()){
player1Wins+=1;
}else {
player2Wins+=1;
}
}
}
if(can_godown) {
//get downward cells...
char c1 = cells[rowid][colid];
char c2 = cells[rowid+1][colid];
char c3 = cells[rowid+2][colid];
char c4 = cells[rowid+3][colid];
if((c1==c2)&&(c1==c3)&&(c1==c4)&& (c1!=BLANK)){
if(c1==Player.X.getChar()){
player1Wins+=1;
}else {
player2Wins+=1;
}
}
}
if(can_godiag) {
//get diagonal cells...
char c1 = cells[rowid][colid];
char c2 = cells[rowid+1][colid+1];
char c3 = cells[rowid+2][colid+2];
char c4 = cells[rowid+3][colid+3];
if((c1==c2)&& (c1==c3) && (c1==c4) && (c1!=BLANK)){
if(c1==Player.X.getChar()){
player1Wins+=1;
}else {
player2Wins+=1;
}
}
}
if(can_revdiag) {
//get reverse diagonal cells...
char c1 = cells[rowid][colid];
char c2 = cells[rowid-1][colid+1];
char c3 = cells[rowid-2][colid+2];
char c4 = cells[rowid-3][colid+3];
if((c1==c2)&&(c1==c3)&&(c1==c4)&& (c1!=BLANK)){
if(c1==Player.X.getChar()){
player1Wins+=1;
}else {
player2Wins+=1;
}
}
}
}//end cols...
}//end rows...
}
void display(){
System.out.println("-------------------------------");
for(int rowid=0;rowid<ROWMAX;rowid++){
for(int colid=0;colid<COLMAX;colid++){
System.out.print(cells[rowid][colid]);
System.out.print(SPACE);
}
System.out.println();
}
//System.out.println("-------------------------------");
}
boolean isGameOver(){
boolean bretval = false;
for(int rowid=0;rowid<ROWMAX;rowid++){
for(int colid=0;colid<COLMAX;colid++){
if(cells[rowid][colid] == BLANK) {
return false;
}else
bretval = true;
}
}
return bretval;
}
public void setPlayer(Player player){
currentPlayer = player;
}
public Player getPlayer(){
return currentPlayer;
}
}//End Board class
public static void main(String[] args) {
Player player1 = Player.X;
Player player2 = Player.O;
ConnectGame cg = new ConnectGame(player1, player2 );
cg.setCurrentPlayer(player1);
while(!cg.getBoard().isGameOver()){
boolean repeat = true;
while(repeat){
int row = ConnectGame.getRandomRows();
int col = ConnectGame.getRandomCols();
if(cg.getBoard().dropCoin(row, col, cg.getCurrentPlayer())){
repeat = false;
}
}
cg.getBoard().display();//at every iteration...
cg.getBoard().countWins();
//take turns swap player
cg.swapPlayer();
}//GameOver tally results...
cg.getBoard().display();
System.out.println("================================");
System.out.println("Player- " + cg.player1.getChar() + " has " + cg.player1Wins );
System.out.println("Player- " + cg.player2.getChar() + " has " + cg.player2Wins );
System.out.println("================================");
}
}
<file_sep>package interview.earts;
/**
* Given the array with random numbers and a starting index and a target, tell if a player specifying the starting index and target , wins or looses.
* Wins if by taking hops /left or right by the value of the given index can reach the target ....
* @author <EMAIL>
*
*
*/
public class EArts {
static boolean canHop(int[] test , int start , int target){
boolean bretval = false;
boolean move_forward = false;
//find the direction to go
if (start<target) move_forward = true;
int step = start;
if(move_forward){//step forward...
while(step < target){
step+= test[step];
if(step>=target){
bretval=true;
break;
}
else if(step<target && test[step]==0){
bretval = false;
break;
}else
continue;
}
}else{//step backwards...
while(step >target){
step-=test[step];
if(step<=target){
bretval=true;
break;
}else if(step > target && test[step]==0){
bretval=false;
break;
}else continue;
}
}
return bretval;
}
public static void main(String... strings){
int[] test1 = {1,1,1};
int[] test2 = {0,1,1,1,0,0,0,1};
int[] test3 = {0,1,1,4,0,0,0,1};
System.out.println(EArts.canHop(test1 , 1, 2)); //start==1 , target==2
System.out.println(EArts.canHop(test2 , 1, 7)); //start==1 , target==7
System.out.println(EArts.canHop(test3 , 1, 7)); //start==1 , target==7
}
}
<file_sep>package interview.indeed;
import java.util.Stack;
/**
* Given a String with the HTML encodings only revese the words that are not encoded
* Leave the rest of the encodings unreversed...
* @author <EMAIL>
*
*/
public class ReverseSpecial{
private Stack<Character> dataStack;
public ReverseSpecial(){
dataStack = new Stack<Character>();
}
public void addWord(String input_string , boolean escape){
if(!escape){
char[] inputchars = input_string.toCharArray();
for(int i=0;i<inputchars.length ;i++){
dataStack.push(inputchars[i]);
}
}else{
char[] inputchars = input_string.toCharArray();
for(int i=inputchars.length-1;i>=0 ;i--){
dataStack.push(inputchars[i]);
}
}
dataStack.push(' ');//Split the words ...would need a rtrim to restore...
}
public String toString(){
StringBuilder build= new StringBuilder();
while(dataStack.size()>0){
build.append(dataStack.pop());
}
return build.toString();
}
public static void main(String... args){
String test1= "ABCD ;amp;#32; PQRS";
String test2= "PQRS ;amp;#32; ABCD RACECAR";
ReverseSpecial mnode = new ReverseSpecial();
String[] words=test2.split(" ");
for(int w=0;w<words.length;w++){
if((words[w].startsWith(";",0)) && (words[w].endsWith(";")))
mnode.addWord(words[w], true);
else {
mnode.addWord(words[w], false);
}
}
System.out.println(mnode.toString());
}
}
<file_sep>package interview.qualys;
/**
* Given a alphanumeric String convert it over to numeric with an offset
* [A=101, B=102, C=103 ... Z=126 etc ]
* It Assumed the alpha would be caps case only
*
* @author <EMAIL>
*
*/
public class AlphaToNum {
public static String convert(String alphaNum){
char[] chars = alphaNum.toCharArray();
StringBuilder result = new StringBuilder();
for(char c: chars){
if(Character.isLetter(c)){
//character 'A' starts @ decimal 65 / 0x0041 so the offset would be char -65 + 101
result.append((int)c - 0x0041 + 101);
}else if(Character.isDigit(c)){
result.append(c);
}
}
return result.toString();
}
public static void main(String...strings ){
String test = "BRYZR904000Z5";
System.out.println(AlphaToNum.convert(test));
}
}
<file_sep>package interview.qualys;
import java.util.HashSet;
import java.util.Set;
/**
* Given an input integer array remove the duplicates...
* @author <EMAIL>
*
*/
public class Interview {
Set<Integer> unique_entries;
public Interview(int[] input){
unique_entries = new HashSet<Integer>();
for(int ii=0;ii<input.length;ii++){
unique_entries.add(input[ii]);
}
}
public static void main(String args[]){
int[] input = {1,2, 3 ,5, 55, 1, 64,32, 11, 12, 2, 5, 9 , 9 , 5};
Interview inv = new Interview(input);
System.out.println(inv.toString());
}
public String toString(){
return unique_entries.toString();
}
}
<file_sep>package interview.startup;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
public class IsoStrings {
/**
* Used two seperate hashmaps to save the characters to compare keys and value
* @author <EMAIL>
* @param str1
* @param str2
* @return
*/
public static boolean areIsoMorphs(String str1 , String str2){
boolean bretval=false;
if(str1.length()==str2.length()){//reject if both strings aren't identically long...
HashMap<Character,Character> comp1 = new HashMap<Character, Character>();
HashMap<Character,Character> comp2 = new HashMap<Character, Character>();
for(int ii=0;ii<str1.length();ii++){
char key1 = str1.charAt(ii);
char key2 = str2.charAt(ii);
if(comp1.containsKey(key1) && comp2.containsKey(key2)){
if(comp1.get(key1).equals(key2) && comp2.get(key2).equals(key1)){
bretval=true;
}else{
bretval = false; break;
}
}else if(!comp1.containsKey(key1) && !comp2.containsKey(key2)){
comp1.put(key1, key2);
comp2.put(key2, key1);
bretval=true;
}else{
bretval = false; break;
}
}
}
return bretval;
}
public static void main(String[] args) {
System.out.println(IsoStrings.areIsoMorphs("egg", "foo"));//true
System.out.println(IsoStrings.areIsoMorphs("eggs", "fool"));//true
System.out.println(IsoStrings.areIsoMorphs("eggs", "food"));//true
System.out.println(IsoStrings.areIsoMorphs("eggs", "foof"));//false
System.out.println(IsoStrings.areIsoMorphs("eggish", "foolish"));//false
}
}
<file_sep>package interview.tenx;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
/**
* Website access log Entries for a single user
*unique id, start time, end time
*1, 1100, 1200
*2, 1030, 1130
*3, 1420, 1500
*4, 1519, 1700
*Find Sessions - group entries into sessions
*1. If two entries time span overlap, then they belong to the same session.
*2. Or if not overlapping, but gap in between < 30, then they belong to the same session.
*Output
*Session 1: 1, 2
*Session 2: 3, 4
*@author <EMAIL>
*/
public class SessionGroups{
HashMap< String , ArrayList<LogEntry> > sessions = new HashMap<String, ArrayList<LogEntry> > ();
class LogEntry{
int start_time;
int end_time;
int id;
LogEntry(int id, int start_time, int end_time){
this.id = id;
this.start_time= start_time;
this.end_time = end_time;
}
public boolean equals(LogEntry otherEntry){
boolean bretval = false;
if((Math.abs(this.start_time-otherEntry.start_time)<30 ) || (Math.abs(this.end_time-otherEntry.end_time)<30 ))
bretval= true;
return bretval;
}
public String toString(){
return ""+id; //id was numeric :(
}
}
public void addToSessions(int id , int st, int et){
LogEntry le = new LogEntry(id,st,et);
boolean update_flag = false;
Set<Entry<String, ArrayList<LogEntry>>> available_sessions = sessions.entrySet();
Iterator<Entry<String, ArrayList<LogEntry>>> siter = available_sessions.iterator();
while(siter.hasNext() && !update_flag){
Entry<String, ArrayList<LogEntry>> entry = siter.next();
String session_name = entry.getKey();
ArrayList<LogEntry> elogs = entry.getValue();
if(!elogs.isEmpty()){
if(((LogEntry)elogs.get(0)).equals(le)){
//le belongs to this session...
elogs.add(le);
sessions.put(session_name , elogs); // adding to the existing session set.
update_flag = true;
}
}
}//while
if(!update_flag){
//create a new session and add it
ArrayList<LogEntry> entries = new ArrayList<LogEntry>();
entries.add(le);
sessions.put(("Session " + id), entries);
}
}
public void displaySessions(){
Set<Entry<String, ArrayList<LogEntry>>> available_sessions = sessions.entrySet();
Iterator<Entry<String, ArrayList<LogEntry>>> siter = available_sessions.iterator();
while(siter.hasNext()){
Entry<String, ArrayList<LogEntry>> entry = siter.next();
String session_name = entry.getKey();
System.out.print(session_name + ": ");
ArrayList<LogEntry> elogs = entry.getValue();
for(LogEntry ent: elogs){
System.out.print(ent) ;
System.out.print(", ");
}
System.out.println();
}
}
public static void main(String args[]){
SessionGroups grps = new SessionGroups();
grps.addToSessions( 1, 1100, 1200);
grps.addToSessions( 6, 1110, 1200);
grps.addToSessions( 2, 1030, 1130);
grps.addToSessions( 3, 1420, 1500);
grps.addToSessions( 4, 1519, 1700);
grps.displaySessions();
}
}
<file_sep># Archive for my Interview Coding Questions
<file_sep>package interview.startup;
/**
* Find if a substring exists within a String ....
* @author <EMAIL>
*
*/
public class FindSub {
public boolean subString(String source , String sub){
boolean bretval=false;
if((source == null)|| (sub==null))
return bretval;
else {
char[] schars = source.toCharArray();
char[] sbchars = sub.toCharArray();
int jj = 0;
for(int ii=0; ii<schars.length;ii++){
if(sbchars[jj]!= schars[ii]) {
jj=0;
continue;
} else{
if(jj==sbchars.length-1){
bretval = true;
break;
}
jj++;
}
}
}
return bretval;
}
public static void main(String... strings){
String src = "<NAME>ad a Little Lamblasting";
String sub = "Lamb";
System.out.println( new FindSub().subString(src, sub));
}
}
<file_sep>package interview.sift;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
/**
* Coding interview task
* =====================
* The task is to:
* Take the input file (userdata.csv) and parse it into a .dot file that can be read by graphviz (http://www.graphviz.org/ you will may want to download the viewer for this task.
* Alternatively there are online viewers available)
* @author <EMAIL>
* @see https://github.com/muthuk07/interviews
* NOTE: that the comment could also containing DELIM to be handled as well !!
* VALIDATION : Used online graphviz http://www.webgraphviz.com/ and digraph G {} to view and validate the generated result...
*/
public class SiftInterview {
public static final String DELIM =",";
public static final String EDGE ="->";
public static final String EMPTY = "";
HashSet<Record> recordset = new HashSet<Record>();
class Record{
String id = null;
String comment = null;
String fuser = null;
String suser = null;
String dotString = null;
public String toString(){
return "ID: " + id + " Comment: " + comment + " User: " + fuser + " Server: " + suser;
}
public String toDotString(){
//id->comment->fuser->suser;
StringBuilder dots = new StringBuilder();
dots.append(id);
if(comment!=null) {
dots.append(EDGE);
dots.append(comment);
}
if(fuser!=null) {
dots.append(EDGE);
dots.append(fuser);
}
if (suser!=null) {
dots.append(EDGE);
dots.append(suser);
}
return dots.toString();
}
}
public void parseRecord(String filerecord){
if(filerecord.length()>0) {
Record record = new Record();
int datalen = filerecord.length()-DELIM.length();
filerecord = filerecord.substring(0,datalen);//ignoring the last demiliter
record.id = filerecord.substring(0,filerecord.indexOf(DELIM));
int idendidx = record.id.length();
int suserstartidx = filerecord.lastIndexOf(DELIM, (filerecord.length()-DELIM.length()));
record.suser = filerecord.substring(suserstartidx + DELIM.length()) ;
int userstartidx = filerecord.lastIndexOf(DELIM, (filerecord.length() - record.suser.length() - DELIM.length() -DELIM.length())) + DELIM.length();
record.fuser = filerecord.substring(userstartidx , suserstartidx) ;
String comment = filerecord.substring( idendidx+ DELIM.length(),userstartidx-DELIM.length() ) ;
if(comment.length()>0) //ignoring empty comments
record.comment = comment;
recordset.add(record);
}
//ignore the empty lines.
}
public String dotFormat(){
java.util.Iterator<Record> riter = recordset.iterator();
StringBuilder result = new StringBuilder();
while(riter.hasNext()){
result.append(riter.next().toDotString());
result.append(System.lineSeparator());
}
return result.toString();
}
public static void main(String[] args) {
//load file
String fileName ="./src/userdata.csv";
SiftInterview sift = new SiftInterview();
try{
try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {
for(String line; (line = br.readLine()) != null; ) {
if(line.length()>0){
sift.parseRecord(line);
}//ignore empty lines...
}
}
}catch(Exception er){
er.printStackTrace();
}
System.out.println(sift.dotFormat());
}
}
|
14ff389274c2634d62fabc718dd4447648e1e23f
|
[
"Markdown",
"Java"
] | 11
|
Java
|
muthuk07/interviews
|
50d47071eb180dd89537f440451b02737a6d4f80
|
c66c6402809a4e7470a0233c295833111a8dc60c
|
refs/heads/master
|
<repo_name>yhyu13/DigiPen-CS529-PersonalGameProject<file_sep>/CS529_Game/src/Platform/Win32_SDL/WinSDLOpenGLApplication.cpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: WinSDLOpenGLApplication.cpp
Purpose: implementation file of WinSDLOpenGLApplication
Language: c++ 11
Platform: win32 x86
Project: CS529_final_project
Author: <NAME> hang.yu 60001119
Creation date: 10/13/2019
- End Header ----------------------------*/
#include "WinSDLOpenGLApplication.hpp"
#include "Common/Event/EventDispatcher.hpp"
#include "Common/Utility/Utility.hpp"
#include "Common/Entity/GameObjectResourceManager.hpp"
#include "src/Event/MyEvent.hpp"
PFNGLCREATESHADERPROC glCreateShader;
PFNGLSHADERSOURCEPROC glShaderSource;
PFNGLCOMPILESHADERPROC glCompileShader;
PFNGLGETSHADERIVPROC glGetShaderiv;
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;
PFNGLDELETESHADERPROC glDeleteShader;
PFNGLATTACHSHADERPROC glAttachShader;
PFNGLCREATEPROGRAMPROC glCreateProgram;
PFNGLLINKPROGRAMPROC glLinkProgram;
PFNGLVALIDATEPROGRAMPROC glValidateProgram;
PFNGLGETPROGRAMIVPROC glGetProgramiv;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog;
PFNGLUSEPROGRAMPROC glUseProgram;
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays;
PFNGLGENBUFFERSPROC glGenBuffers;
PFNGLBINDVERTEXARRAYPROC glBindVertexArray;
PFNGLBINDBUFFERPROC glBindBuffer;
PFNGLBUFFERDATAPROC glBufferData;
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer;
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray;
PFNGLGENERATEMIPMAPPROC glGenerateMipmap;
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;
PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv;
PFNGLUNIFORM1IPROC glUniform1i;
bool initGLExtensions()
{
glCreateShader = (PFNGLCREATESHADERPROC)SDL_GL_GetProcAddress("glCreateShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)SDL_GL_GetProcAddress("glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)SDL_GL_GetProcAddress("glCompileShader");
glGetShaderiv = (PFNGLGETSHADERIVPROC)SDL_GL_GetProcAddress("glGetShaderiv");
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)SDL_GL_GetProcAddress("glGetShaderInfoLog");
glDeleteShader = (PFNGLDELETESHADERPROC)SDL_GL_GetProcAddress("glDeleteShader");
glAttachShader = (PFNGLATTACHSHADERPROC)SDL_GL_GetProcAddress("glAttachShader");
glCreateProgram = (PFNGLCREATEPROGRAMPROC)SDL_GL_GetProcAddress("glCreateProgram");
glLinkProgram = (PFNGLLINKPROGRAMPROC)SDL_GL_GetProcAddress("glLinkProgram");
glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)SDL_GL_GetProcAddress("glValidateProgram");
glGetProgramiv = (PFNGLGETPROGRAMIVPROC)SDL_GL_GetProcAddress("glGetProgramiv");
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)SDL_GL_GetProcAddress("glGetProgramInfoLog");
glUseProgram = (PFNGLUSEPROGRAMPROC)SDL_GL_GetProcAddress("glUseProgram");
glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)SDL_GL_GetProcAddress("glGenVertexArrays");
glGenBuffers = (PFNGLGENBUFFERSPROC)SDL_GL_GetProcAddress("glGenBuffers");
glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)SDL_GL_GetProcAddress("glBindVertexArray");
glBindBuffer = (PFNGLBINDBUFFERPROC)SDL_GL_GetProcAddress("glBindBuffer");
glBufferData = (PFNGLBUFFERDATAPROC)SDL_GL_GetProcAddress("glBufferData");
glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)SDL_GL_GetProcAddress("glVertexAttribPointer");
glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)SDL_GL_GetProcAddress("glEnableVertexAttribArray");
glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)SDL_GL_GetProcAddress("glGenerateMipmap");
glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)SDL_GL_GetProcAddress("glGetUniformLocation");
glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)SDL_GL_GetProcAddress("glUniformMatrix3fv");
glUniform1i = (PFNGLUNIFORM1IPROC)SDL_GL_GetProcAddress("glUniform1i");
return glCreateShader && glShaderSource && glCompileShader && glGetShaderiv &&
glGetShaderInfoLog && glDeleteShader && glAttachShader && glCreateProgram &&
glLinkProgram && glValidateProgram && glGetProgramiv && glGetProgramInfoLog &&
glUseProgram && glGenVertexArrays && glGenBuffers && glBindVertexArray && glBindBuffer &&
glBufferData && glVertexAttribPointer && glEnableVertexAttribArray && glGenerateMipmap &&
glGetUniformLocation && glUniformMatrix3fv && glUniform1i;
}
GLuint compileShader(const char* source, GLuint shaderType) {
DEBUG_PRINT("Compiling shader:" << std::endl << source << std::endl);
// Create ID for shader
GLuint result = glCreateShader(shaderType);
// Define shader text
glShaderSource(result, 1, &source, nullptr);
// Compile shader
glCompileShader(result);
//Check vertex shader for errors
GLint shaderCompiled = GL_FALSE;
glGetShaderiv(result, GL_COMPILE_STATUS, &shaderCompiled);
if (shaderCompiled != GL_TRUE) {
PRINT("Error in compiling: " << result << "!" << std::endl);
GLint logLength;
glGetShaderiv(result, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0)
{
GLchar* log = (GLchar*)malloc(logLength);
glGetShaderInfoLog(result, logLength, &logLength, log);
DEBUG_PRINT("Shader compile log:" << log << std::endl);
free(log);
}
glDeleteShader(result);
result = 0;
}
else {
DEBUG_PRINT("Shader compilation success. Id = " << result << std::endl);
}
return result;
}
GLuint compileProgram(const char* vtxFile, const char* fragFile) {
GLuint programId = 0;
GLuint vtxShaderId, fragShaderId;
programId = glCreateProgram();
std::ifstream f(vtxFile);
std::string source((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
vtxShaderId = compileShader(source.c_str(), GL_VERTEX_SHADER);
f = std::ifstream(fragFile);
source = std::string((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
fragShaderId = compileShader(source.c_str(), GL_FRAGMENT_SHADER);
if (vtxShaderId && fragShaderId) {
// Associate shader with program
glAttachShader(programId, vtxShaderId);
glAttachShader(programId, fragShaderId);
glLinkProgram(programId);
glValidateProgram(programId);
// Check the status of the compile/link
GLint logLen;
glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &logLen);
if (logLen > 0) {
char* log = (char*)malloc(logLen * sizeof(char));
// Show any errors as appropriate
glGetProgramInfoLog(programId, logLen, &logLen, log);
DEBUG_PRINT("Prog Info Log: " << std::endl << log << std::endl);
free(log);
}
}
if (vtxShaderId) {
glDeleteShader(vtxShaderId);
}
if (fragShaderId) {
glDeleteShader(fragShaderId);
}
return programId;
}
void presentBackBuffer(SDL_Renderer* renderer, SDL_Window* win, SDL_Texture* backBuffer, GLuint programId, int W, int H) {
GLint oldProgramId;
SDL_SetRenderTarget(renderer, nullptr);
SDL_RenderClear(renderer);
SDL_GL_BindTexture(backBuffer, nullptr, nullptr);
if (programId != 0) {
glGetIntegerv(GL_CURRENT_PROGRAM, &oldProgramId);
glUseProgram(programId);
}
GLfloat minx, miny, maxx, maxy;
GLfloat minu, maxu, minv, maxv;
minx = 0.0f;
miny = 0.0f;
maxx = static_cast<GLfloat>(W);
maxy = static_cast<GLfloat>(H);
minu = 0.0f;
maxu = 1.0f;
minv = 0.0f;
maxv = 1.0f;
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(minu, minv);
glVertex2f(minx, miny);
glTexCoord2f(maxu, minv);
glVertex2f(maxx, miny);
glTexCoord2f(minu, maxv);
glVertex2f(minx, maxy);
glTexCoord2f(maxu, maxv);
glVertex2f(maxx, maxy);
glEnd();
SDL_GL_SwapWindow(win);
if (programId != 0) {
glUseProgram(oldProgramId);
}
}
/*Init Tick Final***************************************************************************************************************/
int My::WinSDLOpenGLApplication::Initialize()
{
// 1. SDL init
if ((SDL_Init(SDL_INIT_EVERYTHING | SDL_VIDEO_OPENGL)) < 0)
{
printf("Couldn't initialize SDL, error %s\n", SDL_GetError());
exit(-1);
}
//Initialize SDL_mixer
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
{
printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
exit(-1);
}
// 2. SDL window init
std::wstring w_title(m_config.appName);
std::string t(w_title.begin(), w_title.end());
m_pWindow = SDL_CreateWindow(t.c_str(), // window title
SDL_WINDOWPOS_UNDEFINED, // initial x position
SDL_WINDOWPOS_UNDEFINED, // initial y position
m_config.screenWidth, // width, in pixels
m_config.screenHeight, // height, in pixels
SDL_WINDOW_OPENGL);
// Check that the window was successfully made
if (nullptr == m_pWindow)
{
// In the event that the window could not be made...
printf("Could not create window: %s\n", SDL_GetError());
exit(-1);
}
// 3. SDL opengl init
//Create context
m_gContext = SDL_GL_CreateContext(m_pWindow);
if (m_gContext == nullptr)
{
printf("OpenGL context could not be created! SDL Error: %s\n", SDL_GetError());
exit(-1);
}
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl");
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetSwapInterval(-1);
// 4. Create renderer
m_renderer = SDL_CreateRenderer(m_pWindow, -1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE);
// 5. Init OpenGL
SDL_RendererInfo rendererInfo;
SDL_GetRendererInfo(m_renderer, &rendererInfo);
if (!strncmp(rendererInfo.name, "opengl", 6)) {
PRINT("Init OpenGL! " + Str(rendererInfo.name) + "\n");
// If you want to use GLEW or some other GL extension handler, do it here!
if (!initGLExtensions()) {
PRINT("Couldn't init GL extensions!\n" << std::endl);
exit(-1);
}
// Compile shader
m_programId = compileProgram("./Resource/Shader/std.vertex", "./Resource/Shader/std.fragment");
PRINT("programId = " << m_programId << "\n");
}
else
{
PRINT("Can't init OpenGL! Exit!\n");
exit(-1);
}
// https://gamedev.stackexchange.com/questions/119414/resolution-scaling
// 6. Enable SDL Logical Scaling for everything managed by m_renderer with the resolution that UI and sprites are designed for.
if (0 != SDL_RenderSetLogicalSize(m_renderer, m_config.screenWidth, m_config.screenHeight))
{
printf("Could not set logical size for renderer: %s\n", SDL_GetError());
exit(-1);
}
// 7. Make a target texture to render too
m_texTarget = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET, m_config.screenWidth, m_config.screenHeight);
// 8. Reset render color
SDL_SetRenderDrawColor(m_renderer, 255, 255, 255, 255);
return 0;
}
int My::WinSDLOpenGLApplication::Tick(double deltaTime)
{
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
//User requests quit
switch (e.type)
{
// Event quit
case SDL_QUIT:
BaseApplication::SetQuit(true);
return 1;
// Event mouse click
case SDL_MOUSEBUTTONDOWN:
{
if (e.button.button == SDL_BUTTON_LEFT)
{
DEBUG_PRINT(Str(e.button.x) + ", " + Str(e.button.y) + " Mouse left button down. (OnMouseClick event broadcasted)\n");
auto event = std::make_shared<Events::MouseClickEvent>(e.button.x, e.button.y);
for (auto& ptr : g_pGameObjectResourceManager->FindAllResourcesByName("UI"))
{
event->AddSubscriber(ptr);
}
g_pEventDispatcher->DispatchToSubscribers(-1.0f, event);
}
}
break;
case SDL_MOUSEMOTION:
{
DEBUG_PRINT(Str(e.motion.x) + ", " + Str(e.motion.y) + "\n");
auto event = std::make_shared<Events::MouseMotionEvent>(e.motion.x, e.motion.y);
for (auto& ptr : g_pGameObjectResourceManager->FindAllResourcesByName("UI"))
{
event->AddSubscriber(ptr);
}
g_pEventDispatcher->DispatchToSubscribers(-1.0f, event);
}
break;
default:
break;
}
}
IRunTimeModule::Tick(deltaTime); // Execute additional callback functions added to the application.
return 0;
}
int My::WinSDLOpenGLApplication::Finalize()
{
glDeleteShader(m_programId);
SDL_DestroyTexture(m_texTarget);
SDL_DestroyRenderer(m_renderer);
SDL_GL_DeleteContext(m_gContext);
SDL_DestroyWindow(m_pWindow);
Mix_Quit();
IMG_Quit();
SDL_Quit();
return 0;
}
/*Draw***************************************************************************************************************/
int My::WinSDLOpenGLApplication::BeginDraw()
{
//Render to the texture
SDL_SetRenderTarget(m_renderer, m_texTarget);
SDL_RenderClear(m_renderer);
return 0;
}
int My::WinSDLOpenGLApplication::OnDraw()
{
// Process OnDrawCallback
for (auto& func : m_OnDrawCallbacks) { func(); };
return 0;
}
int My::WinSDLOpenGLApplication::EndDraw()
{
int SCREEN_WIDTH, SCREEN_HEIGHT;
SDL_GetWindowSize(m_pWindow, &SCREEN_WIDTH, &SCREEN_HEIGHT);
presentBackBuffer(m_renderer, m_pWindow, m_texTarget, m_programId, SCREEN_WIDTH, SCREEN_HEIGHT);
return 0;
}
/*Setter Getter***************************************************************************************************************/
void My::WinSDLOpenGLApplication::ShowMessage(const std::wstring& title, const std::wstring& message)
{
std::string t(title.begin(), title.end());
std::string m(message.begin(), message.end());
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, t.c_str(), m.c_str(), m_pWindow);
}
SDL_Window* My::WinSDLOpenGLApplication::GetWindow() noexcept
{
return (m_pWindow) ? m_pWindow : nullptr;
}
SDL_Renderer* My::WinSDLOpenGLApplication::GetRenderer() noexcept
{
return m_renderer;
}
void My::WinSDLOpenGLApplication::SetConfig(const GfxConfiguration& config) noexcept
{
GfxConfiguration old_config(m_config);
m_config = config;
// Reset window size and render target size if configuration has changed.
if (old_config.screenWidth != m_config.screenWidth || old_config.screenHeight != m_config.screenHeight)
{
SDL_SetWindowSize(m_pWindow, m_config.screenWidth, m_config.screenHeight);
SDL_DestroyTexture(m_texTarget);
//Make a target texture to render too
m_texTarget = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET, m_config.screenWidth, m_config.screenHeight);
}
}
<file_sep>/CS529_Game/src/Component/Logic/AIController.cpp
#include <SDL.h>
#include "AIController.hpp"
#include "Common/Entity/GameObjectResourceManager.hpp"
#include "Common/Utility/Utility.hpp"
#include "Common/Component/ComponentManager.hpp"
#include "Common/Component/Physics/Body.hpp"
#include "Common/Event/EventDispatcher.hpp"
#include "src/Event/MyEvent.hpp"
My::Component::AIController::AIController(void* owner, std::string name)
:
IComponent((COMPONENT_TYPE::AICONTROLLER), owner, name),
switched_event_sent(false),
fire_period(0.0),
fire_period_timer(0.0),
bullet_id(0),
motion_mode(0),
motion_mode2(0),
motion_mode3(0),
fire_mode(0),
fire_mode2(0),
fire_mode3(0),
m_phase(RAND_F(0.0f, PI)),
m_amplitude(RAND_F(1.0f, 2.0f)),
m_right(RAND_F(-1.0f, 1.0f))
{
if (m_right >= -.25f && m_right <= 0.0f)
{
m_right = RAND_F(-1.0f, -.25f);
}
else if (m_right <= .25f && m_right >= 0.0f)
{
m_right = RAND_F(.25f, 1.0f);
}
m_destination.x = 0;
m_destination.y = 0;
}
void My::Component::AIController::Update(double deltaTime)
{
UpdateMotion(deltaTime);
UpdateFire(deltaTime);
}
void My::Component::AIController::Serialize(std::wostream& wostream)
{
wostream << "[Component : AIController] ";
}
void My::Component::AIController::Serialize(std::ifstream& fstream)
{
for (std::string line; getline(fstream, line);)
{
if (line[0] == ']')
{
return;
}
if (2 == sscanf_s(line.c_str(), "p (%f,%f) ", &m_destination.x, &m_destination.y))
{
continue;
}
if (0 < sscanf_s(line.c_str(), "motion mode %d %d %d ", &motion_mode, &motion_mode2, &motion_mode3))
{
continue;
}
if (0 < sscanf_s(line.c_str(), "fire mode %d %d %d ", &fire_mode, &fire_mode2, &fire_mode3))
{
continue;
}
}
}
void My::Component::AIController::UpdateMotion(double deltaTime)
{
auto owner = static_cast<ComponentManager*>(GetOwner());
auto temp_body = owner->GetComponent(COMPONENT_TYPE::BODY);
if (temp_body)
{
auto p_bodyCom = static_cast<Component::Body*>(temp_body);
if (motion_mode == 0)
{
{
std::lock_guard<std::mutex> lock(p_bodyCom->m_mutex);
// target is active
Vector2D forward, diff;
Vector2D target_pos = m_destination;
Vector2DSub(&diff, &target_pos, &p_bodyCom->m_position);
// Switch to stationary mode
if (Vector2DLength(&diff) <= 100.0f)
{
motion_mode = 1;
return;
}
Vector2DNormalize(&forward, &p_bodyCom->m_velocity);
float diff_angle = acosf(Vector2DDotProduct(&forward, &diff) / Vector2DLength(&diff));
float possible_angle = p_bodyCom->m_angle+diff_angle; // Pick an angle, here I choose to add diff_angle from mAngle
Vector2DSet(&forward, cosf(possible_angle), sinf(possible_angle));
float dot = Vector2DDotProduct(&forward, &diff) / Vector2DLength(&diff); // Calculate the dot product value
if (fabs(dot - 1.0f) < 0.01f) // The picked angle, after adding to the current angle points to the target. Success.
{
diff_angle = (diff_angle > UFO_ROT_SPEED) ? UFO_ROT_SPEED : diff_angle; // Limit rotaional speed
}
else
{
diff_angle *= -1.0f;
diff_angle = (diff_angle < -UFO_ROT_SPEED) ? -UFO_ROT_SPEED : diff_angle;
}
p_bodyCom->m_angle += diff_angle * static_cast<float>(deltaTime) * 5.0f;
p_bodyCom->m_velocity.x = UFO_SPEED_1 * cosf(p_bodyCom->m_angle);
p_bodyCom->m_velocity.y = UFO_SPEED_1 * sinf(p_bodyCom->m_angle);
}
}
if (motion_mode == 1)
{
Vector2D Up(0.0f, -100.0f);
Vector2D Right(100.0f, 0.0f);
// Going up and down in a way of sine curve.
m_phase += static_cast<float>(deltaTime) * 2.0f * PI * m_amplitude;
m_phase = fmodf(m_phase, 2 * PI);
{
std::lock_guard<std::mutex> lock(p_bodyCom->m_mutex);
// Reset velocity
Vector2DZero(&p_bodyCom->m_velocity);
Vector2DScaleAdd(&p_bodyCom->m_velocity, &Up, &p_bodyCom->m_velocity, sinf(m_phase));
if (p_bodyCom->m_position.x <= 50 || p_bodyCom->m_position.x >= 550)
{
m_right = -m_right;
}
Vector2DScaleAdd(&p_bodyCom->m_velocity, &Right, &p_bodyCom->m_velocity, m_right);
p_bodyCom->m_angle = 0.0f;
}
}
}
}
void My::Component::AIController::UpdateFire(double deltaTime)
{
auto owner = static_cast<ComponentManager*>(GetOwner());
auto p_owner_transformCom = static_cast<Component::Body*>(owner->GetComponent(COMPONENT_TYPE::BODY));
if (fire_mode == 0)
{
fire_period = UFO_FIRE_MODE_1_FIRE_PERIOD;
std::string name = "UFOBullet";
if ((fire_period_timer += deltaTime) >= fire_period)
{
fire_period_timer = 0.0;
auto pNewObject = SpawnBullet(name,1);
auto p_new_transformCom = static_cast<Component::Body*>(pNewObject->GetComponent(COMPONENT_TYPE::BODY));
{
Vector2D v(RAND_F(-100.0f, 100.0f), 200.0f);
std::lock_guard<std::mutex> lock1(p_owner_transformCom->m_mutex);
std::lock_guard<std::mutex> lock2(p_new_transformCom->m_mutex);
Vector2DSet(&p_new_transformCom->m_position, &p_owner_transformCom->m_position);
Vector2DSet(&p_new_transformCom->m_velocity, &v);
}
}
if (fire_mode2 != 0 && !switched_event_sent)
{
switched_event_sent = true;
g_pEventDispatcher->DispatchToGameObject(6.0, std::make_shared<Events::AISwitchFireModeEvent>(fire_mode2), static_cast<IGameObject*>(owner->GetOwner()));
}
}
else if (fire_mode == 1)
{
fire_period = UFO_FIRE_MODE_2_FIRE_PERIOD;
std::string name = "UFOBullet";
if ((fire_period_timer += deltaTime) >= fire_period)
{
fire_period_timer = 0.0;
float vx = -100.0f;
for (int i = 0; i < 10; ++i)
{
auto pNewObject = SpawnBullet(name, 2);
auto p_new_transformCom = static_cast<Component::Body*>(pNewObject->GetComponent(COMPONENT_TYPE::BODY));
{
Vector2D v(vx - i * vx / 5, 200.0f);
std::lock_guard<std::mutex> lock1(p_owner_transformCom->m_mutex);
std::lock_guard<std::mutex> lock2(p_new_transformCom->m_mutex);
Vector2DSet(&p_new_transformCom->m_position, &p_owner_transformCom->m_position);
Vector2DSet(&p_new_transformCom->m_velocity, &v);
}
}
}
if (fire_mode3 != 0 && !switched_event_sent)
{
switched_event_sent = true;
g_pEventDispatcher->DispatchToGameObject(4.0, std::make_shared<Events::AISwitchFireModeEvent>(RAND_I(0,3)), static_cast<IGameObject*>(owner->GetOwner()));
}
}
else if (fire_mode == 2)
{
fire_period = UFO_FIRE_MODE_3_FIRE_PERIOD;
std::string name = "UFOBullet";
float vx = -100.0f;
float angle = PI / 4.0f;
static int i = 0;
if ((fire_period_timer += deltaTime) >= fire_period)
{
fire_period_timer = 0.0;
if (++i > 10)
{
i = 0;
}
auto pNewObject = SpawnBullet(name,3);
auto p_new_transformCom = static_cast<Component::Body*>(pNewObject->GetComponent(COMPONENT_TYPE::BODY));
{
Vector2D v(vx - i * vx / 5, 200.0f);
std::lock_guard<std::mutex> lock1(p_owner_transformCom->m_mutex);
std::lock_guard<std::mutex> lock2(p_new_transformCom->m_mutex);
Vector2DSet(&p_new_transformCom->m_position, &p_owner_transformCom->m_position);
Vector2DSet(&p_new_transformCom->m_velocity, &v);
p_new_transformCom->m_angle = angle - i * angle / 5;
}
}
if (!switched_event_sent)
{
switched_event_sent = true;
g_pEventDispatcher->DispatchToGameObject(4.0, std::make_shared<Events::AISwitchFireModeEvent>(RAND_I(0, 3)), static_cast<IGameObject*>(owner->GetOwner()));
}
}
}
void My::Component::AIController::SetFireMode(int mode)
{
fire_mode = mode;
}
IWeapon* My::Component::AIController::SpawnBullet(std::string weaponType, int lvl)
{
auto owner = static_cast<ComponentManager*>(GetOwner());
auto name = static_cast<IMyGameObject*>(owner->GetOwner())->GetName();
std::string weaponName(name + Str(bullet_id++));
// Serialize the game object and set its owner to be the root object.
if (g_weaponSerializationMap.find(weaponType) != g_weaponSerializationMap.end())
{
auto pNewObject = LoadIWeaponFromFile(this, weaponType.c_str(), weaponName);
// Add game object under the resource manager.
if (1 == g_pGameObjectResourceManager->AddResource(pNewObject, weaponName))
{
std::string msg("Adding resource : '" + std::string(weaponName) + "' has failed.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
// Set bullet to the current weapon level
pNewObject->SetUpgradeLevel(lvl);
return pNewObject;
}
else
{
std::string msg("File does not provide a valid game object of type: " + std::string(weaponType));
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
<file_sep>/GameEngine/Common/Geommath/2D/Vector2D.hpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: Vector2D
Purpose: header file of Vector2D
Language: c++ 11
Platform: win32 x86
Project: CS529_project_2
Author: <NAME> hang.yu 60001119
Creation date: 10/10/2019
- End Header ----------------------------*/
#pragma once
#include "Math.hpp"
namespace My {
typedef struct Vector2D
{
float x, y;
Vector2D() : x(0.0f), y(0.0f) {};
Vector2D(float _x, float _y) : x(_x), y(_y) {};
Vector2D(const Vector2D & vec) : x(vec.x), y(vec.y) {};
}Vector2D;
/*
This function sets the coordinates of the 2D vector (pResult) to 0
*/
void Vector2DZero(Vector2D* pResult);
/*
This function sets the coordinates of the 2D vector (pResult) to pVec0
*/
void Vector2DSet(Vector2D* pResult, Vector2D* pVec0);
/*
This function sets the coordinates of the 2D vector (pResult) to pVec0
*/
void Vector2DSet(Vector2D* pResult, const Vector2D* pVec0);
/*
This function sets the coordinates of the 2D vector (pResult) to x &y
*/
void Vector2DSet(Vector2D* pResult, float x, float y);
/*
In this function, pResult will be set to the opposite of pVec0
*/
void Vector2DNeg(Vector2D* pResult, Vector2D* pVec0);
/*
In this function, pResult will be the sum of pVec0 and pVec1
*/
void Vector2DAdd(Vector2D* pResult, Vector2D* pVec0, Vector2D* pVec1);
/*
In this function, pResult will be the difference between pVec0 *pVec1: pVec0 - pVec1
*/
void Vector2DSub(Vector2D* pResult, Vector2D* pVec0, Vector2D* pVec1);
/*
In this function, pResult will be the unit vector of pVec0
*/
void Vector2DNormalize(Vector2D* pResult, Vector2D* pVec0);
/*
In this function, pResult will be the vector pVec0 scaled by the value c
*/
void Vector2DScale(Vector2D* pResult, Vector2D* pVec0, float c);
/*
In this function, pResult will be the vector pVec0 scaled by c and added to pVec1
*/
void Vector2DScaleAdd(Vector2D* pResult, Vector2D* pVec0, Vector2D* pVec1, float c);
/*
In this function, pResult will be the vector pVec0 scaled by c and pVec1 will be subtracted from it
*/
void Vector2DScaleSub(Vector2D* pResult, Vector2D* pVec0, Vector2D* pVec1, float c);
/*
This function returns the length of the vector pVec0
*/
float Vector2DLength(Vector2D* pVec0);
/*
This function returns the square of pVec0's length. Avoid the square root
*/
float Vector2DSquareLength(Vector2D* pVec0);
/*
In this function, pVec0 and pVec1 are considered as 2D points.
The distance between these 2 2D points is returned
*/
float Vector2DDistance(Vector2D* pVec0, Vector2D* pVec1);
/*
In this function, pVec0 and pVec1 are considered as 2D points.
The squared distance between these 2 2D points is returned. Avoid the square root
*/
float Vector2DSquareDistance(Vector2D* pVec0, Vector2D* pVec1);
/*
This function returns the dot product between pVec0 and pVec1
*/
float Vector2DDotProduct(Vector2D* pVec0, Vector2D* pVec1);
/*
This function computes the coordinates of the vector represented by the angle "angle", which is in Degrees
*/
void Vector2DFromAngleDeg(Vector2D* pResult, float angle);
/*
This function computes the coordinates of the vector represented by the angle "angle", which is in Radian
*/
void Vector2DFromAngleRad(Vector2D* pResult, float angle);
/*
This function computes the theta value of the vector in polar coordinate system in radians.
*/
float Vector2DAngleFromVec2(Vector2D* pVec);
Vector2D operator-(Vector2D& vec1, Vector2D& vec2);
Vector2D operator+(Vector2D& vec1, Vector2D& vec2);
}<file_sep>/CS529_Game/src/Entity/Gameplay/Objects/UFO.hpp
#pragma once
#include "src/Entity/Gameplay/Interface/IMyGameObject.hpp"
#include "src/Event/MyEvent.hpp"
namespace My
{
namespace Entity
{
class UFO : public IMyGameObject
{
public:
UFO() = delete;
explicit UFO(void* owner, std::string name) noexcept : IMyGameObject(MYGAMEOBJECT_TYPE::UFO, owner, name)
{
m_eventManager.AddEventRegistry(EventType::ON_COMPONENTHIT);
m_eventManager.AddEventRegistry(EventType::ON_TELEPORT);
// set random seed at current time
std::map<double, int> cumulative;
typedef std::map<double, char>::iterator It;
cumulative[PACK_HP_THRESHOLD] = PACK_HP_INDEX;
cumulative[PACK_UPGRADE_THRESHOLD] = PACK_UPGRADE_INDEX;
cumulative[PACK_SHIELD_THRESHOLD] = PACK_SHIELD_INDEX;
cumulative[1.00] = 0;
const int numTests = 2;
for (int i = 0; i != numTests; ++i)
{
double linear = rand() * 1.0 / RAND_MAX;
m_drop_list.push_back(cumulative.upper_bound(linear)->second);
}
}
virtual int Tick(double deltaTime) override;
virtual int Draw() override;
virtual void HandleEvent(std::weak_ptr<Event> e)
{
if (IsActive())
{
std::shared_ptr<Event> _e = e.lock();
switch (_e->GetType())
{
case EventType::ON_COMPONENTHIT:
OnComponentHit(_e);
break;
case EventType::ON_TELEPORT:
OnSwitchFireMode(_e);
break;
default:
break;
}
}
}
void OnComponentHit(std::weak_ptr<Event> e);
void OnSwitchFireMode(std::weak_ptr<Event> e);
void DropPack();
private:
std::vector<int> m_drop_list;
};
}
class UFOObjectCreator : public IMyGameObjectCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IMyGameObject* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "UFO0") override
{
if (pool)
{
return pool->New<Entity::UFO>(owner, name);
}
else
{
return new Entity::UFO(owner, name);
}
}
};
}<file_sep>/CS529_Game/src/Entity/Gameplay/UI/Button.hpp
#pragma once
#include "src/Entity/Gameplay/Interface/IMyGameObject.hpp"
namespace My
{
namespace Entity
{
class UI_Button : public IMyGameObject
{
public:
UI_Button() = delete;
explicit UI_Button(void* owner, std::string name) noexcept
:
IMyGameObject(MYGAMEOBJECT_TYPE::UI_Button, owner, name),
b_isShown(true)
{
m_eventManager.AddEventRegistry(EventType::ON_MOUSECLICK);
m_eventManager.AddEventRegistry(EventType::ON_MOUSEMOTION);
}
virtual int Draw() override;
virtual void HandleEvent(std::weak_ptr<Event> e) override
{
if (GetIsShown() && IsActive())
{
std::shared_ptr<Event> _e = e.lock();
switch (_e->GetType())
{
case EventType::ON_MOUSECLICK:
OnClick(_e);
break;
case EventType::ON_MOUSEMOTION:
OnHover(_e);
break;
default:
break;
}
}
}
// Custom events
void OnClick(std::weak_ptr<Event> e);
void OnHover(std::weak_ptr<Event> e);
void SetIsShown(bool v);
bool GetIsShown();
private:
bool b_isShown;
};
}
class UI_ButtonObjectCreator : public IMyGameObjectCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IMyGameObject* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "UI_Button0") override
{
if (pool)
{
return pool->New<Entity::UI_Button>(owner, name);
}
else
{
return new Entity::UI_Button(owner, name);
}
}
};
namespace Entity
{
class UI_Volume_Button : public IMyGameObject
{
public:
UI_Volume_Button() = delete;
explicit UI_Volume_Button(void* owner, std::string name) noexcept
:
IMyGameObject(MYGAMEOBJECT_TYPE::UI_Volume_Button, owner, name)
{
m_eventManager.AddEventRegistry(EventType::ON_MOUSECLICK);
}
virtual int Tick(double deltaTime) override;
virtual int Draw() override;
virtual void HandleEvent(std::weak_ptr<Event> e) override
{
if (IsActive())
{
std::shared_ptr<Event> _e = e.lock();
switch (_e->GetType())
{
case EventType::ON_MOUSECLICK:
OnClick(_e);
break;
default:
break;
}
}
}
// Custom events
void OnClick(std::weak_ptr<Event> e);
private:
static int mode;
};
}
class UI_Volume_ButtonObjectCreator : public IMyGameObjectCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IMyGameObject* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "UI_Volume_Button0") override
{
if (pool)
{
return pool->New<Entity::UI_Volume_Button>(owner, name);
}
else
{
return new Entity::UI_Volume_Button(owner, name);
}
}
};
}<file_sep>/GameEngine/Common/Utility/Timer.hpp
#pragma once
#include <chrono>
#include "EngineException.hpp"
using namespace std::chrono;
namespace My
{
class Timer
{
public:
Timer();
void Reset() noexcept;
double Mark() noexcept;
private:
std::chrono::steady_clock::time_point last;
};
}<file_sep>/GameEngine/Common/Utility/Scheduler.hpp
#pragma once
#include <future>
#include "Common/Utility/Timer.hpp"
#include "Common/BaseApplication.hpp"
namespace My
{
extern std::shared_ptr<BaseApplication> g_pBaseApplication;
template< class Function, class... Args>
int Run(Function&& f, Args&& ... args)
{
try
{
f(args...);
}
catch (const EngineException& e)
{
BaseApplication::SetQuit(true);
const std::wstring eMsg = e.GetFullMessage() +
L"\n\nEngineException caught.";
g_pBaseApplication->ShowMessage(e.GetExceptionType(), eMsg);
}
catch (const std::exception& e)
{
BaseApplication::SetQuit(true);
// need to convert std::exception what() string from narrow to wide string
const std::string whatStr(e.what());
const std::wstring w_whatStr(whatStr.begin(), whatStr.end());
const std::wstring eMsg = std::wstring(whatStr.begin(), whatStr.end()) +
L"\n\nException caught.";
g_pBaseApplication->ShowMessage(w_whatStr, eMsg);
}
catch( ... )
{
BaseApplication::SetQuit(true);
g_pBaseApplication->ShowMessage( L"Unhandled Non-STL Exception",L"Exception caught at Run." );
}
return 0;
}
template<class Function, class... Args>
int GameLoopUpdate(double waitTime, Function&& f, Args&& ... args)
{
Timer drawTimer;
try
{
while (!g_pBaseApplication->IsQuit())
{
drawTimer.Reset();
f(args...);
while (drawTimer.Mark() < waitTime) {};
BaseApplication::frametime = drawTimer.Mark();
}
}
catch (const EngineException& e)
{
BaseApplication::SetQuit(true);
const std::wstring eMsg = e.GetFullMessage() +
L"\n\nException caught at Windows message loop.";
g_pBaseApplication->ShowMessage(e.GetExceptionType(), eMsg);
}
catch (const std::exception& e)
{
BaseApplication::SetQuit(true);
// need to convert std::exception what() string from narrow to wide string
const std::string whatStr(e.what());
const std::wstring eMsg = std::wstring(whatStr.begin(), whatStr.end()) +
L"\n\nException caught at Windows message loop.";
g_pBaseApplication->ShowMessage(L"Unhandled STL Exception", eMsg);
}
catch( ... )
{
BaseApplication::SetQuit(true);
g_pBaseApplication->ShowMessage( L"Unhandled Non-STL Exception",L"Exception caught at GameLoopUpdate." );
}
return 0;
}
}<file_sep>/CS529_Game/src/Entity/Gameplay/Weapon/Lazer.hpp
#pragma once
#include "Common/Event/Event.hpp"
#include "src/Entity/Gameplay/Interface/IWeapon.hpp"
#include "src/Event/MyEvent.hpp"
namespace My
{
namespace Entity
{
class Lazer : public IWeapon
{
public:
Lazer() = delete;
explicit Lazer(void* owner, std::string name) noexcept
:
IWeapon(WEAPON_TYPE::WEAPON_LAZER, owner, name),
bullet_id(0),
fire_period(WEAPON_LAZER_FIRE_PERIOD),
fire_period_timer(WEAPON_LAZER_FIRE_PERIOD)
{
m_eventManager.AddEventRegistry(EventType::ON_COMPONENTHIT);
}
virtual int Tick(double deltaTime) override;
virtual void HandleEvent(std::weak_ptr<Event> e) override
{
if (IsActive())
{
std::shared_ptr<Event> _e = e.lock();
switch (_e->GetType())
{
case EventType::ON_COMPONENTHIT:
OnComponentHit(_e);
break;
default:
break;
}
}
}
/*
Hitting UFO:
Shrink the lazer to the colliding object
*/
void OnComponentHit(std::weak_ptr<Event> e);
void ResetSize();
IWeapon* SpawnBullet();
void SpawnBullet1();
void SpawnBullet2();
void SpawnBullet3();
private:
uint64_t bullet_id;
double fire_period;
double fire_period_timer;
};
}
class LazerObjectCreator : public IWeaponCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IWeapon* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "Lazer0") override
{
if (pool)
{
return pool->New<Entity::Lazer>(owner, name);
}
else
{
return new Entity::Lazer(owner, name);
}
}
};
}<file_sep>/CS529_Game/src/Entity/Gameplay/Interface/IWeapon.hpp
#pragma once
#include "WeaponType.hpp"
#include "src/Entity/Gameplay/Interface/IMyGameObject.hpp"
namespace My
{
/**
Comment :
To create a custom weapon
1. Add a new element to the enum type in the weapon type header
2. Create a derived class which inherits from IWeapon
3. Create a derived class which inherits from IWeaponCreator
4. RegisterSerialization (g_weaponSerializationMap) in your initializer
5. RegisterCreator (g_weaponCreatorMap) in your initializer
*/
class IWeapon : public IMyGameObject
{
public:
IWeapon(const IWeapon&) = delete;
IWeapon& operator=(const IWeapon&) = delete;
explicit IWeapon(WEAPON_TYPE type, void* owner, std::string name) noexcept;
// Virtual destructor is needed since we will use IWeapon* (the base class pointer)
virtual ~IWeapon() {};
virtual int Tick(double deltaTime) override;
virtual int Draw() override;
virtual void Serialize(std::wostream& wostream) override;
WEAPON_TYPE GetType() const noexcept;
void UpgradeWeapons();
void DowngradeWeapons();
void SetUpgradeLevel(int lvl);
protected:
WEAPON_TYPE m_type;
int m_level;
public:
static int max_level;
};
class IWeaponCreator
{
public:
/* owner = g_pRootObject.get(), pool = g_pMemoryManager.get() */
virtual IWeapon* Create(void* owner, MemoryManager* pool, std::string name) = 0;
};
// TODO : Initialize in your application
extern std::map<std::string, WEAPON_TYPE> g_weaponSerializationMap;
extern std::map<WEAPON_TYPE, std::shared_ptr<IWeaponCreator>> g_weaponCreatorMap;
IWeapon* LoadIWeaponFromFile(void* owner, const char* file_path, std::string name);
}<file_sep>/CS529_Game/src/Entity/Gameplay/Interface/IWeapon.cpp
#include "IWeapon.hpp"
#include "src/SerializedLoader.hpp"
int My::IWeapon::max_level = MAX_WEAPON_LVL;
My::IWeapon::IWeapon(WEAPON_TYPE type, void* owner, std::string name) noexcept
:
IMyGameObject(MYGAMEOBJECT_TYPE::WEAPON, owner, name),
m_type(type),
m_level(1)
{
}
int My::IWeapon::Tick(double deltaTime)
{
if (deltaTime != 0.0)
{
auto temp = GetComponent(COMPONENT_TYPE::SPRITE);
if (temp)
{
auto p_spriteCom = static_cast<Component::Sprite*>(temp);
switch (m_level)
{
case 1:
p_spriteCom->SetCurrentSpriteByName("lvl1");
break;
case 2:
p_spriteCom->SetCurrentSpriteByName("lvl2");
break;
case 3:
p_spriteCom->SetCurrentSpriteByName("lvl3");
break;
default:
break;
}
}
}
IMyGameObject::Tick(deltaTime);
return 0;
}
int My::IWeapon::Draw()
{
if (IsActive())
{
if (auto sceneCom = GetComponent(COMPONENT_TYPE::SCENECOMPONENT))
{
static_cast<Component::SceneComponent*>(sceneCom)->Draw();
}
}
return 0;
}
void My::IWeapon::Serialize(std::wostream& wostream)
{
wostream << str2wstr("Weapon : " + m_name + "\n");
m_componentManager.Serialize(wostream);
wostream << "\n";
for (auto& child : m_children)
{
child->Serialize(wostream);
}
}
My::WEAPON_TYPE My::IWeapon::GetType() const noexcept
{
return m_type;
}
void My::IWeapon::UpgradeWeapons()
{
if (m_level < max_level) m_level++;
}
void My::IWeapon::DowngradeWeapons()
{
if (m_level > 1) m_level--;
}
void My::IWeapon::SetUpgradeLevel(int lvl)
{
m_level = lvl;
}
namespace My
{
IWeapon* LoadIWeaponFromFile(void* owner,const char* file_path, std::string name)
{
if (g_gameObjectConfigurationIfstreamMap.find(Str(file_path)) == g_gameObjectConfigurationIfstreamMap.end())
{
std::string msg("The configuration file of game object " + Str(file_path) + " is not registered.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
IWeapon* pNewObject = nullptr;
std::ifstream& input(g_gameObjectConfigurationIfstreamMap[Str(file_path)]);
if (!input.is_open())
{
std::string msg("Can't open object file: " + std::string(file_path) + ".");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
else
{
std::string line; getline(input, line);
char objectType[256] = { 0 };
if (1 == sscanf_s(line.c_str(), "#%s", objectType, 256))
{
// Serialize the game object and set its owner to be the root object.
if (g_weaponSerializationMap.find(objectType) != g_weaponSerializationMap.end())
{
/* owner = g_pRootObject.get(), pool = g_pMemoryManager.get() */
pNewObject = g_weaponCreatorMap[g_weaponSerializationMap[objectType]]->Create(owner, g_pMemoryManager.get(), name);
/* Assign call backs */
if (g_globalCallBackSerializationMap.find(name) != g_globalCallBackSerializationMap.end())
{
auto callback_map = g_globalCallBackSerializationMap[name];
for (auto it = callback_map.begin(); it != callback_map.end(); ++it)
{
pNewObject->AddCallBacks(it->first, it->second);
}
}
}
else
{
print_fstream(input);
std::string msg(std::string(file_path) + " does not provide a valid game object of type: " + std::string(objectType) + " at line : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
else
{
print_fstream(input);
std::string msg(std::string(file_path) + " does not contain a valid object type in the form #~ : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
for (std::string line; getline(input, line);)
{
char componentType[256] = { 0 };
char componentName[256] = { 0 };
if (0 < sscanf_s(line.c_str(), "[%s %s", componentType, 256, componentName, 256))
{
// Serialize the game object component
if (g_componentSerializationMap.find(componentType) != g_componentSerializationMap.end())
{
// Add component
auto component = pNewObject->AddComponent(g_componentSerializationMap[componentType]);
component->Serialize(input);
// Set name if given
if (componentName[0] != 0)
{
component->SetName(name + componentName);
}
else
{
component->SetName(name + component->GetName());
}
if (g_componentSerializationMap[componentType] == COMPONENT_TYPE::BODY)
{
/* Adding body component under the management of the physics resource manager */
if (1 == g_pBodyResourceManager->AddResource(reinterpret_cast<Component::Body*>(component), name))
{
std::string msg("Adding resource : '" + component->GetName() + "' has failed.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
else
{
print_fstream(input);
std::string msg(std::string(file_path) + " does not provide a valid component type for object type " + std::string(objectType) + " at line : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
else
{
print_fstream(input);
std::string msg(std::string(file_path) + " does not contain a valid component type in the form [~ : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
rewind_fstream(input);
return pNewObject;
}
}
}<file_sep>/CS529_Game/src/Entity/Gameplay/Objects/Background.cpp
#include "Background.hpp"
int My::Entity::Background::Draw()
{
// The scrolling background is also a player object
if (auto sceneCom = m_componentManager.GetComponent(COMPONENT_TYPE::SCENECOMPONENT))
{
static_cast<Component::SceneComponent*>(sceneCom)->Draw();
}
return 0;
}<file_sep>/CS529_Game/src/Entity/Gameplay/Pack/Pack_HP.cpp
#include "Pack_HP.hpp"
#include "src/Platform/Win32_SDL/WinSDLAudioManager.hpp"
int My::Entity::Pack_HP::Tick(double deltaTime)
{
if ((life_time -= deltaTime) <= 0.0)
{
SetGCToTrue();
}
IMyGameObject::Tick(deltaTime);
return 0;
}
int My::Entity::Pack_HP::Draw()
{
auto temp = GetComponent(COMPONENT_TYPE::SCENECOMPONENT);
if (temp)
{
static_cast<Component::SceneComponent*>(temp)->Draw();
return 0;
}
return 1;
}
void My::Entity::Pack_HP::OnComponentHit(std::weak_ptr<Event> e)
{
std::shared_ptr<Event> _e = e.lock();
auto event = static_cast<Events::ComponentHitEvent*>(_e.get());
auto other = static_cast<IMyGameObject*>(event->other);
if (other->GetType() == MYGAMEOBJECT_TYPE::PLAYER)
{
SetGCToTrue();
g_pAudioManager->PlayChunck("HPRestore");
}
}
<file_sep>/GameEngine/Common/Event/EventType.h
#pragma once
namespace My {
enum class EventType
{
ON_COMPONENTHIT = 0,
ON_DEATH,
ON_LOCKHP,
ON_UNLOCKHP,
ON_TELEPORT,
ON_SET_VELOCITY,
ON_SET_POSITION,
ON_SET_ACCELERATION,
ON_MOUSECLICK,
ON_MOUSEMOTION,
NUM
};
}<file_sep>/GameEngine/Common/Entity/IGameObject.cpp
#include "IGameObject.hpp"
My::IGameObject::IGameObject(GAMEOBJECT_TYPE type, void* owner, std::string name) noexcept
:
m_type(type),
m_owner(owner),
m_active(true),
m_gc(false),
m_name(name)
{
m_eventManager.SetOwner(this);
m_componentManager.SetOwner(this);
}
int My::IGameObject::Initialize()
{
return 0;
}
int My::IGameObject::Tick(double deltaTime)
{
m_eventManager.Tick(deltaTime);
m_componentManager.Tick(deltaTime);
return 0;
}
int My::IGameObject::Finalize()
{
return 0;
}
int My::IGameObject::Draw()
{
return 0;
}
void My::IGameObject::Serialize(std::wostream& wostream)
{
wostream << str2wstr("Game object : " + m_name + "\n");
m_componentManager.Serialize(wostream);
wostream << "\n";
for (auto& child : m_children)
{
child->Serialize(wostream);
}
}
void My::IGameObject::AddEvent(std::weak_ptr<Event> e)
{
m_eventManager.AddEvent(e);
}
My::IComponent* My::IGameObject::AddComponent(COMPONENT_TYPE type)
{
return m_componentManager.AddComponent(type);
}
My::IComponent* My::IGameObject::GetComponent(COMPONENT_TYPE type)
{
return m_componentManager.GetComponent(type);
}
std::vector<My::IGameObject*>& My::IGameObject::GetChildren()
{
return m_children;
}
void My::IGameObject::AddChildren(IGameObject* child)
{
m_children.push_back(child);
}
std::map<std::string, std::function<void(void)>>& My::IGameObject::GetCallBacks()
{
return m_callBacks;
}
void My::IGameObject::AddCallBacks(std::string name, std::function<void(void)> func)
{
m_callBacks[name] = func;
}
My::GAMEOBJECT_TYPE My::IGameObject::GetType() const noexcept { return m_type; }
void My::IGameObject::SetName(std::string name) noexcept
{
m_name = name;
}
const std::string& My::IGameObject::GetName() const noexcept
{
return m_name;
}
void My::IGameObject::SetOwner(void* owner) noexcept
{
m_owner = owner;
}
void* My::IGameObject::GetOwner() const noexcept
{
return m_owner;
}
bool My::IGameObject::IsActive() const noexcept
{
return m_active;
}
void My::IGameObject::SetActive(bool v) noexcept
{
m_active = v;
}
bool My::IGameObject::IsGC() const noexcept
{
return m_gc;
}
void My::IGameObject::SetGCToTrue() noexcept
{
m_active = false;
m_gc = true;
}
My::RootObject::RootObject() : IGameObject(GAMEOBJECT_TYPE::NUM, nullptr, "RootObject") {}
int My::RootObject::Initialize() { return 0; }
int My::RootObject::Tick(double deltaTime) { for (auto& child : m_children) { child->Tick(deltaTime); } return 0; }
int My::RootObject::Draw() { for (auto& child : m_children) { child->Draw(); } return 0; }
int My::RootObject::Finalize() { return 0; }
void My::RootObject::Serialize(std::wostream& wostream) { for (auto& child : m_children) { child->Serialize(wostream); } }<file_sep>/GameEngine/Common/Geommath/Shape/Shape.hpp
#pragma once
#include <string>
#include <fstream>
#include "ShapeType.h"
#include "Common/MemoryManager.hpp"
#include "Common/ResourceManager.hpp"
#include "Common/Geommath/2D/Math2D.hpp"
/*
Collision bounding box
*/
namespace My
{
/*
Base Collision
*/
namespace Collision
{
class Shape
{
public:
Shape() = delete;
explicit Shape(SHAPE_TYPE type, void* owner);
virtual ~Shape();;
virtual void Serialize(std::ifstream& fstream) = 0;
SHAPE_TYPE GetType() const noexcept;
void SetOwner(void* owner) noexcept;
void* GetOwner() const noexcept;
bool IsActive() const noexcept;
void SetActive(bool v) noexcept;
private:
SHAPE_TYPE m_type;
void* m_owner;
bool m_active;
};
}
class ShapeCreator
{
public:
/* owner = g_pRootObject.get(), pool = g_pMemoryManager.get() */
virtual Collision::Shape* Create(void* owner = nullptr, MemoryManager* pool = nullptr) = 0;
};
// TODO : Initialize in your application
extern std::map<std::string, SHAPE_TYPE> g_shapeSerializationMap;
extern std::map<SHAPE_TYPE, std::shared_ptr<ShapeCreator>> g_shapeCreatorMap;
/*
Circle
*/
namespace Collision
{
class Circle : public Shape
{
public:
Circle() = delete;
explicit Circle(void* owner);;
virtual void Serialize(std::ifstream& fstream) override;
public:
float m_radius;
};
}
class CircleCreator : public ShapeCreator
{
public:
/* owner = g_pRootObject.get(), pool = g_pMemoryManager.get() */
virtual Collision::Shape* Create(void* owner = nullptr, MemoryManager* pool = nullptr)
{
if (pool)
{
return pool->New<Collision::Circle>(owner);
}
else
{
return new Collision::Circle(owner);
}
}
};
/*
Rectangle
*/
namespace Collision
{
class Rectangle : public Shape
{
public:
Rectangle() = delete;
explicit Rectangle(void* owner);;
virtual void Serialize(std::ifstream& fstream) override;
public:
float m_width;
float m_height;
};
}
class RectangleCreator : public ShapeCreator
{
public:
/* owner = g_pRootObject.get(), pool = g_pMemoryManager.get() */
virtual Collision::Shape* Create(void* owner = nullptr, MemoryManager* pool = nullptr)
{
if (pool)
{
return pool->New<Collision::Rectangle>(owner);
}
else
{
return new Collision::Rectangle(owner);
}
}
};
}<file_sep>/GameEngine/Common/Entity/IGameObject.hpp
#pragma once
#include "GameObjectType.h"
#include "Common/Component/ComponentManager.hpp"
#include "Common/MemoryManager.hpp"
#include "Common/ResourceManager.hpp"
#include "Common/Event/EventManager.hpp"
/**
Comment :
To create a custom game object
1. Add a new element to the enum type in the game object type header
2. Create a derived class which inherits from IGameObject
3. Create a derived class which inherits from IGameObjectCreator
4. RegisterSerialization in your initializer
5. RegisterCreator in your initializer
*/
namespace My
{
/**
* IGameObject is a combination of these two interfaces: IRunTimeModule, IComponent but only inherits from IRunTimeModule.
*/
class IGameObject : public IRunTimeModule
{
public:
IGameObject(const IGameObject&) = delete;
IGameObject& operator=(const IGameObject&) = delete;
explicit IGameObject(GAMEOBJECT_TYPE type, void* owner, std::string name) noexcept;
// Virtual destructor is needed since we will use IGameObject* (the base class pointer)
virtual ~IGameObject() {};
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
virtual int Draw();
virtual void Serialize(std::wostream& wostream) override;
std::vector<IGameObject*>& GetChildren();
void AddChildren(IGameObject* child);
std::map<std::string, std::function<void(void)>>& GetCallBacks();
void AddCallBacks(std::string name, std::function<void(void)> func);
/* Queued process of a event*/
void AddEvent(std::weak_ptr<Event> e);
/* Immediate process of a event */
virtual void HandleEvent(std::weak_ptr<Event> e) {};
/* Create a new component of specific type and add to the game object */
IComponent* AddComponent(COMPONENT_TYPE type);
IComponent* GetComponent(COMPONENT_TYPE type);
GAMEOBJECT_TYPE GetType() const noexcept;
void SetName(std::string name) noexcept;
const std::string& GetName() const noexcept;
void SetOwner(void* owner) noexcept;
void* GetOwner() const noexcept;
/* Is this object active for collision, drawing, etc. */
bool IsActive() const noexcept;
/* Set this object active for collision, drawing, etc. */
void SetActive(bool v) noexcept;
/* Is this object to be GC */
bool IsGC() const noexcept;
/* Set this object to be GC, calling this function also calls SetActive(flase) */
void SetGCToTrue() noexcept;
protected:
bool m_active;
bool m_gc;
GAMEOBJECT_TYPE m_type;
void* m_owner;
EventManager m_eventManager;
ComponentManager m_componentManager;
std::string m_name;
/* Child array */
std::vector<IGameObject*> m_children;
/* Call back maps */
std::map<std::string, std::function<void(void)>> m_callBacks;
};
class IGameObjectCreator
{
public:
/* owner = g_pRootObject.get(), pool = g_pMemoryManager.get() */
virtual IGameObject* Create(void* owner, MemoryManager* pool, std::string name) = 0;
};
// Using a root object to update all IGameObject (deprecated)
class RootObject : public IGameObject
{
public:
RootObject();
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Draw() override;
virtual int Finalize() override;
virtual void Serialize(std::wostream& wostream) override;
};
// TODO : Initialize in your application
extern std::shared_ptr<RootObject> g_pRootObject;
}<file_sep>/CS529_Game/src/Component/Gameplay/WeaponarySystem.cpp
#include "WeaponarySystem.hpp"
#include "Common/Utility/Utility.hpp"
#include "Common/Entity/GameObjectResourceManager.hpp"
My::Component::WeaponarySystem::WeaponarySystem(void* owner, std::string name)
:
IComponent((COMPONENT_TYPE::WEAPONARYSYSTEM), owner, name),
m_maxWeapons(0)
{
}
void My::Component::WeaponarySystem::Update(double deltaTime)
{
}
My::Component::WeaponarySystem::~WeaponarySystem()
{
for (auto& map : m_weaponMaps)
{
for (auto it = map.begin(); it != map.end(); ++it)
{
it->second->SetGCToTrue();
}
}
}
void My::Component::WeaponarySystem::Serialize(std::ifstream& fstream)
{
for (std::string line; getline(fstream, line);)
{
int id = 0;
char weaponName[256] = { 0 };
char weaponType[256] = { 0 };
if (1 == sscanf_s(line.c_str(), "Max %d", &m_maxWeapons))
{
for (int i = 0; i < m_maxWeapons; ++i)
{
m_currentWeapons.push_back(nullptr);
m_weaponMaps.push_back(std::map<std::string, IWeapon*>());
}
}
else if (3 == sscanf_s(line.c_str(), "%d %s %s", &id, &weaponType, 256,&weaponName, 256))
{
if (id-- > m_maxWeapons)
{
print_fstream(fstream);
std::string msg("File does not provide a valid weapon id (max :" + Str(m_maxWeapons) + ") " + std::string(weaponType) + " at line : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
// Serialize the game object and set its owner to be the root object.
if (g_weaponSerializationMap.find(weaponType) != g_weaponSerializationMap.end())
{
auto pNewObject = LoadIWeaponFromFile(this, weaponType, weaponName);
m_weaponMaps[id][weaponName] = pNewObject;
if (m_currentWeapons[id]) m_currentWeapons[id]->SetActive(false);
m_currentWeapons[id] = pNewObject;
m_currentWeapons[id]->SetActive(true);
// Add game object under the resource manager.
if (1 == g_pGameObjectResourceManager->AddResource(pNewObject, weaponName))
{
std::string msg("Adding resource : '" + std::string(weaponName) + "' has failed.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
else
{
print_fstream(fstream);
std::string msg("File does not provide a valid game object of type: " + std::string(weaponName) + " at line : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
else if (line[0] == ']')
{
return;
}
else
{
print_fstream(fstream);
std::string msg("WeaponSystem serialization has failed at line " + line + ".");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
void My::Component::WeaponarySystem::Serialize(std::wostream& wostream)
{
wostream << "[Component : WeaponSystem ";
for (int i = 0; i < m_maxWeapons; ++i)
{
for (auto it = m_weaponMaps[i].begin(); it != m_weaponMaps[i].end(); ++it)
{
wostream << str2wstr("Weapon : " + Str(i) + " " + it->first + "\n");
}
}
wostream << "] ";
}
void My::Component::WeaponarySystem::UpgradeWeapons()
{
for (auto& map : m_weaponMaps)
{
for (auto it = map.begin(); it != map.end(); ++it)
{
it->second->UpgradeWeapons();
}
}
}
void My::Component::WeaponarySystem::DowngradeWeapons()
{
for (auto& map : m_weaponMaps)
{
for (auto it = map.begin(); it != map.end(); ++it)
{
it->second->DowngradeWeapons();
}
}
}
void My::Component::WeaponarySystem::ChangeWeapon(int id, std::string name)
{
if (id < 1 && id > m_maxWeapons)
{
std::string msg("Trying to change weapon out of range: " + Str(id) + "/" + Str(m_maxWeapons));
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
else
{
id--;
for (auto it = m_weaponMaps[id].begin(); it != m_weaponMaps[id].end(); ++it)
{
if ((*it).first.find(name) != std::string::npos)
{
if (m_currentWeapons[id]) m_currentWeapons[id]->SetActive(false);
m_currentWeapons[id] = (*it).second;
m_currentWeapons[id]->SetActive(true);
return;
}
}
std::string msg("Can not find weapon " + name + " in " + Str(id));
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
<file_sep>/GameEngine/Common/MemoryPool.cpp
#include "MemoryPool.hpp"
const size_t My::MemoryPool::kPageSize = 1024;
My::MemoryPool::MemoryPool()
{
m_PoolSize = 0;
m_PoolMaxSize = kPageSize;
m_pPoolHead = reinterpret_cast<uint8_t*>(malloc(m_PoolMaxSize));
m_pPoolTail = m_pPoolHead;
if (m_pPoolTail == nullptr)
{
std::string msg("Memory pool initialization has failed.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
My::MemoryPool::~MemoryPool()
{
Reset();
}
void* My::MemoryPool::Allocate(size_t size)
{
if ((m_PoolSize + size) > m_PoolMaxSize) { ResizePool(2); }
void* ret = reinterpret_cast<void*>(m_pPoolTail);
/* Update book keeping pointer */
m_bookkeeper.push_back(ret);
/* Update m_pPoolTail */
m_pPoolTail += size;
m_PoolSize += size;
return ret;
}
void My::MemoryPool::Reset()
{
if (m_pPoolHead) free(m_pPoolHead);
m_pPoolHead = nullptr;
}
const std::vector<void*>& My::MemoryPool::GetBookKeeper()
{
return m_bookkeeper;
}
void My::MemoryPool::ResizePool(size_t scalar)
{
if (scalar > 1)
{
m_PoolMaxSize += kPageSize;
uint8_t* temp = reinterpret_cast<uint8_t*>(realloc(m_pPoolHead, m_PoolMaxSize));
if (!temp)
{
Reset();
std::string msg("Realloc has failed.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
/* Update book keeping pointers */
size_t shift = temp - m_pPoolHead;
for (auto& ptr : m_bookkeeper)
{
ptr = reinterpret_cast<uint8_t*>(ptr) + shift;
}
/* Update m_pPoolHead && m_pPoolTail */
size_t diff = m_pPoolTail - m_pPoolHead;
m_pPoolHead = temp;
m_pPoolTail = m_pPoolHead + diff;
}
}
<file_sep>/Test_GameEngine/Test_GameEngine.cpp
#include "pch.h"
#include "CppUnitTest.h"
#include "Common/Geommath/2D/Math2D.hpp"
#include "Common/MemoryPool.hpp"
#include "Common/MemoryManager.hpp"
#include "Common/Utility/Utility.hpp"
#include "Common/Utility/Timer.hpp"
using namespace std;
using namespace My;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace TestGameEngine
{
TEST_CLASS(TestGameEngine)
{
public:
TEST_METHOD(TestMethod1)
{
Logger::WriteMessage("TestMethod1 : Memory pool Test.");
MemoryPool pool;
pool.New<int>(4);
pool.New<int>(4);
pool.New<int>(4);
for (auto& ptr : pool.GetBookKeeper())
{
int temp = *(static_cast<int*>(ptr));
Assert::AreEqual(temp, 4);
Logger::WriteMessage((Str(temp) + ", 4").c_str());
}
Logger::WriteMessage("Resize pool.");
pool.Allocate(1024);
pool.Allocate(1025);
int i = 0;
for (auto& ptr : pool.GetBookKeeper())
{
int temp = *(static_cast<int*>(ptr));
Assert::AreEqual(temp, 4);
Logger::WriteMessage((Str(temp) + ", 4").c_str());
if (++i == 3) break;
}
Logger::WriteMessage("TestMethod1 Success.");
}
TEST_METHOD(TestMethod2)
{
Logger::WriteMessage("TestMethod2 : Memory manager Test.");
MemoryManager* g_pMemoryManager = new MemoryManager();
g_pMemoryManager->Initialize();
auto timer = Timer();
for (int i = 0; i < 10000; i++)
{
int* a = g_pMemoryManager->New<int>(30);
g_pMemoryManager->Delete(a);
}
Logger::WriteMessage(("MyMemoryManager Score (int): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 10000; i++)
{
int* a = new int(30);
delete a;
}
Logger::WriteMessage(("C++NativeMalloc Score (int): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 10000; i++)
{
char* space = (char*)g_pMemoryManager->Allocate(1024);
g_pMemoryManager->Free(space, 1024);
}
Logger::WriteMessage(("MyMemoryManager Score (1kb): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 10000; i++)
{
char* space = (char*)malloc(1024);
free(space);
}
Logger::WriteMessage(("C++NativeMalloc Score (1kb): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 10000; i++)
{
char* space = (char*)g_pMemoryManager->Allocate(4096);
g_pMemoryManager->Free(space, 4096);
}
Logger::WriteMessage(("MyMemoryManager Score (4kb): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 10000; i++)
{
char* space = (char*)malloc(4096);
free(space);
}
Logger::WriteMessage(("C++NativeMalloc Score (4kb): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 10000; i++)
{
Vector2D* vec = g_pMemoryManager->New<Vector2D>();
g_pMemoryManager->Delete(vec);
}
Logger::WriteMessage(("MyMemoryManager Score (Vector2D): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 10000; i++)
{
Vector2D* vec = new Vector2D();
delete vec;
}
Logger::WriteMessage(("C++NativeMalloc Score (Vector2D): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 100; i++)
{
//std::vector<int, My::allocator<int>> vec2;
MyVector(int) vec2;
for (int j = 0; j < 1000; j++)
vec2.push_back(1);
}
Logger::WriteMessage(("MyMemoryManager Score (vec int): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 100; i++)
{
std::vector<int> vec2;
for (int j = 0; j < 1000; j++)
vec2.push_back(1);
}
Logger::WriteMessage(("C++NativeMalloc Score (vec int): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 100; i++)
{
MyVector(Vector2D) vec2;
for (int j = 0; j < 1000; j++)
vec2.push_back(Vector2D());
}
Logger::WriteMessage(("MyMemoryManager Score (vec Vector2D): " + Str(timer.Mark()) + "s").c_str());
timer.Reset();
for (int i = 0; i < 100; i++)
{
std::vector<Vector2D> vec2;
for (int j = 0; j < 1000; j++)
vec2.push_back(Vector2D());
}
Logger::WriteMessage(("C++NativeMalloc Score (vec Vector2D): " + Str(timer.Mark()) + "s").c_str());
char* space1 = (char*)g_pMemoryManager->Allocate(11);
char* temp = space1;
for (int j = 0; j < 10; j++)
{
*temp = ('0' + j);
temp++;
}
*temp = '\0';
wcout << space1 << endl;
g_pMemoryManager->Delete(space1);
g_pMemoryManager->Finalize();
delete g_pMemoryManager;
Logger::WriteMessage("TestMethod2 Success.");
}
};
}
<file_sep>/GameEngine/Common/Component/Physics/BodyResourceManager.cpp
#include "BodyResourceManager.hpp"
#include "Common/Utility/Utility.hpp"
#include "Common/Component/ComponentManager.hpp"
#include "Common/Entity/IGameObject.hpp"
#include "Common/Event/Event.hpp"
int My::BodyResourceManager::Initialize()
{
Shape2DCollisionFunction[static_cast<size_t>(SHAPE_TYPE::CIRCLE)][static_cast<size_t>(SHAPE_TYPE::CIRCLE)] = Collision::Circle2Circle;
Shape2DCollisionFunction[static_cast<size_t>(SHAPE_TYPE::CIRCLE)][static_cast<size_t>(SHAPE_TYPE::RECTANGLE)] = Collision::Circle2Rectangle;
Shape2DCollisionFunction[static_cast<size_t>(SHAPE_TYPE::RECTANGLE)][static_cast<size_t>(SHAPE_TYPE::CIRCLE)] = Collision::Rectangle2Circle;
Shape2DCollisionFunction[static_cast<size_t>(SHAPE_TYPE::RECTANGLE)][static_cast<size_t>(SHAPE_TYPE::RECTANGLE)] = Collision::Rectangle2Rectangle;
return 0;
}
int My::BodyResourceManager::PhysicsUpdate(double deltaTime)
{
for (auto it = m_resourceMap.begin(); it != m_resourceMap.end(); ++it)
{
it->second->PhysicsUpdate(deltaTime);
}
return 0;
}
int My::BodyResourceManager::CollisionUpdate(double deltaTime)
{
if (deltaTime != 0.0)
{
for (auto it1 = m_resourceMap.begin(); it1 != m_resourceMap.end(); ++it1)
{
auto body_com = it1->second;
auto actor1 = reinterpret_cast<IGameObject*>(reinterpret_cast<ComponentManager*>(it1->second->GetOwner())->GetOwner());
if (body_com->IsActive() && actor1->IsActive())
{
for (auto it2 = std::next(it1); it2 != m_resourceMap.end(); ++it2)
{
auto body_com2 = it2->second;
auto actor2 = reinterpret_cast<IGameObject*>(reinterpret_cast<ComponentManager*>(it2->second->GetOwner())->GetOwner());
if (body_com2->IsActive() && actor2->IsActive() && it1->second->m_shape && it2->second->m_shape)
{
if (Shape2DCollisionFunction[static_cast<size_t>(it1->second->m_shape->GetType())][static_cast<size_t>(it2->second->m_shape->GetType())](body_com, body_com2))
{
// Collision has happened.
actor1->AddEvent(std::make_shared<Events::ComponentHitEvent>(actor2));
actor2->AddEvent(std::make_shared<Events::ComponentHitEvent>(actor1));
}
}
}
}
}
}
return 0;
}
bool My::Collision::Circle2Circle(Component::Body* body1, Component::Body* body2)
{
auto _shape1 = reinterpret_cast<Collision::Circle*>(body1->m_shape);
auto _shape2 = reinterpret_cast<Collision::Circle*>(body2->m_shape);
return StaticCircleToStaticCircle(&body1->m_position, _shape1->m_radius, &body2->m_position, _shape2->m_radius);
}
bool My::Collision::Circle2Rectangle(Component::Body* body1, Component::Body* body2)
{
auto _shape1 = reinterpret_cast<Collision::Circle*>(body1->m_shape);
auto _shape2 = reinterpret_cast<Collision::Rectangle*>(body2->m_shape);
return StaticRectToStaticRect(&body1->m_position, _shape1->m_radius, _shape1->m_radius, &body2->m_position, _shape2->m_width, _shape2->m_height);
}
bool My::Collision::Rectangle2Circle(Component::Body* body1, Component::Body* body2)
{
return Circle2Rectangle(body2, body1);
}
bool My::Collision::Rectangle2Rectangle(Component::Body* body1, Component::Body* body2)
{
auto _shape1 = reinterpret_cast<Collision::Rectangle*>(body1->m_shape);
auto _shape2 = reinterpret_cast<Collision::Rectangle*>(body2->m_shape);
return StaticRectToStaticRect(&body1->m_position, _shape1->m_width, _shape1->m_height, &body2->m_position, _shape2->m_width, _shape2->m_height);
}
<file_sep>/CS529_Game/src/SerializedLoader.cpp
#include "SerializedLoader.hpp"
namespace My
{
/**
Comment :
Serialization of level config.
Sample game object configuration file level1.txt:
[Screen_width 800 ]
[Screen_height 600 ]
[MAX_FPS 60 ]
*/
int LoadLevelConfigFromFile(const char* file_path, GfxConfiguration& config)
{
std::map<std::string, int> config_dict;
std::ifstream& input(g_gameObjectConfigurationIfstreamMap[Str(file_path)]);
if (!input.is_open())
{
std::string msg(std::string(file_path) + " could not be opened.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
else
{
for (std::string line; getline(input, line);)
{
char key[256] = { 0 };
int value = 0;
if (2 == sscanf_s(line.c_str(), "[%s %d", key, 256, &value))
{
config_dict[key] = value;
}
}
if (config_dict.find("Screen_width") != config_dict.end())
{
config.screenWidth = config_dict["Screen_width"];
}
if (config_dict.find("Screen_height") != config_dict.end())
{
config.screenHeight = config_dict["Screen_height"];
}
if (config_dict.find("MAX_FPS") != config_dict.end())
{
config.maxfps = config_dict["MAX_FPS"];
}
rewind_fstream(input);
g_pBaseApplication->SetConfig(config);
return 0;
}
}
/**
Comment :
Load game object from file_path and set it with name
Serialization of game object.
Sample game object configuration file Player.txt:
#Player // Object type -> initiate object creator
[Transform // Component Transform
p (0,0) v (0,0) a (0,0) // initiate component creator
]
[Sprite // Component Sprite
~Player.bmp // initiate component creator
]
[PlayerController // Component PlayerController
]
[SceneComponet // Component scene (This makes the object visible in the scene)
]
*/
IMyGameObject* LoadIGameObjectFromFile(const char* file_path, std::string name)
{
if (g_gameObjectConfigurationIfstreamMap.find(Str(file_path)) == g_gameObjectConfigurationIfstreamMap.end())
{
std::string msg("The configuration file of game object " + Str(file_path) + " is not registered.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
IMyGameObject* pNewObject = nullptr;
std::ifstream &input(g_gameObjectConfigurationIfstreamMap[Str(file_path)]);
if (!input.is_open())
{
std::string msg("Can't open object file: " + std::string(file_path) + ".");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
else
{
std::string line; getline(input, line);
char objectType[256] = { 0 };
if (1 == sscanf_s(line.c_str(), "#%s", objectType, 256))
{
// Serialize the game object and set its owner to be the root object.
if (g_myGameObjectSerializationMap.find(objectType) != g_myGameObjectSerializationMap.end())
{
/* owner = g_pRootObject.get(), pool = g_pMemoryManager.get() */
pNewObject = g_myGameObjectCreatorMap[g_myGameObjectSerializationMap[objectType]]->Create(nullptr, g_pMemoryManager.get(), name);
/* Assign call backs */
if (g_globalCallBackSerializationMap.find(name) != g_globalCallBackSerializationMap.end())
{
auto callback_map = g_globalCallBackSerializationMap[name];
for (auto it = callback_map.begin(); it != callback_map.end(); ++it)
{
pNewObject->AddCallBacks(it->first, it->second);
}
}
}
else
{
print_fstream(input);
std::string msg(std::string(file_path) + " does not provide a valid game object of type: " + std::string(objectType) + " at line : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
else
{
print_fstream(input);
std::string msg(std::string(file_path) + " does not contain a valid object type in the form #~ : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
for (std::string line; getline(input, line);)
{
char componentType[256] = { 0 };
char componentName[256] = { 0 };
if (0 < sscanf_s(line.c_str(), "[%s %s", componentType, 256, componentName, 256))
{
// Serialize the game object component
if (g_componentSerializationMap.find(componentType) != g_componentSerializationMap.end())
{
// Add component
auto component = pNewObject->AddComponent(g_componentSerializationMap[componentType]);
component->Serialize(input);
// Set name if given
if (componentName[0] != 0)
{
component->SetName(name + componentName);
}
else
{
component->SetName(name + component->GetName());
}
if (g_componentSerializationMap[componentType] == COMPONENT_TYPE::BODY)
{
/* Adding body component under the management of the physics resource manager */
if (1 == g_pBodyResourceManager->AddResource(reinterpret_cast<Component::Body*>(component), name))
{
std::string msg("Adding resource : '" + component->GetName() + "' has failed.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
else
{
print_fstream(input);
std::string msg(std::string(file_path) + " does not provide a valid component type for object type " + std::string(objectType) + " at line : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
else
{
print_fstream(input);
std::string msg(std::string(file_path) + " does not contain a valid component type in the form [~ : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
rewind_fstream(input);
return pNewObject;
}
}
/**
Comment :
Sample game object configuration file level1.txt:
#./Resource/Configuration/Background.txt Back
[Transform
p(0, 0) v(-200, 0) a(0, 0) // One more comment
]
// This is a comment : Create a player object with name "Player"
#./Resource/Configuration/Player.txt Player // This is a comment, too
[Transform
p(100, 100) v(0, 0) a(0,0)
]
// This is the third comment : Create a UFO object with name "Enemy1"
#./Resource/Configuration/UFO.txt Enemy1
[Transform
p(300, 100) v(0, 0) a(0, 0) // One more comment
]
#./Resource/Configuration/UFO.txt Enemy2
[Transform
p(400, 500) v(0, 0) a(0, 0) // One more comment
]
#./Resource/Configuration/UFO.txt Enemy3
[Transform
p(100, 400) v(0, 0) a(0, 0) // One more comment
]
*/
int LoadLevelObjectFromFile(const char* file_path)
{
std::ifstream& input(g_gameObjectConfigurationIfstreamMap[Str(file_path)]);
if (!input.is_open())
{
std::string msg("Can't open level file: " + std::string(file_path) + ".");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
else
{
for (std::string line; getline(input, line);)
{
// Load game object from file
IMyGameObject* pNewObject = nullptr;
char objectPath[256] = { 0 };
char objectName[256] = { 0 };
if (2 == sscanf_s(line.c_str(), "#%s %s", objectPath, 256, objectName, 256))
{
pNewObject = LoadIGameObjectFromFile(objectPath, objectName);
// Add game object under the resource manager.
if (1 == g_pGameObjectResourceManager->AddResource(pNewObject, objectName))
{
std::string msg("Adding resource : '" + std::string(objectName) + "' has failed.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
for (std::string line; getline(input, line);)
{
char componentType[256] = { 0 };
if (1 == sscanf_s(line.c_str(), "[%s", componentType, 256))
{
// Serialize the game object component
if (g_componentSerializationMap.find(componentType) != g_componentSerializationMap.end())
{
// Add component
auto component = pNewObject->AddComponent(g_componentSerializationMap[componentType]);
component->Serialize(input);
}
else
{
print_fstream(input);
std::string msg(std::string(file_path) + " does not provide a valid component type for object type " + std::string(objectPath) + " at line : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
else
{
break;
}
}
}
}
rewind_fstream(input);
return 0;
}
}
}<file_sep>/GameEngine/Common/ResourceManager.hpp
#pragma once
#include <map>
#include <string>
#include "Common/Interface/IRunTimeModule.hpp"
#include "Common/MemoryManager.hpp"
namespace My
{
template<class T>
class ResourceManager : public IRunTimeModule
{
public:
ResourceManager() noexcept {};
ResourceManager(const ResourceManager&) = delete;
ResourceManager& operator=(const ResourceManager&) = delete;
virtual int Initialize() override { return 0; };
virtual int Tick(double deltaTime) override { return 0; };
virtual int Finalize() override { return 0; };
/* clear the map struct managed by the resource manager.*/
virtual int Clear()
{
m_resourceMap.clear();
return 0;
}
/* Use Memory Manager's Delete function to free all allocated objects (useful for game objects). */
int FreeByNameWithMemoryManager(std::string name)
{
T* ret = GetResourceByName(name);
if (!ret)
{
return 1;
}
g_pMemoryManager->Delete(ret);
m_resourceMap.erase(name);
return 0;
}
/* Remove the key value without freeing resources (useful for components). */
int FreeByNameWithDefault(std::string name)
{
T* ret = GetResourceByName(name);
if (!ret)
{
return 1;
}
m_resourceMap.erase(name);
return 0;
}
/**
* \brief AddResource: Add a resource pointer to the resource map. If the name already existed, no resouce is added.
*
* std::string msg("Adding resource : '" + name + "' has failed.");
* throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
* \author <NAME>
* \date 10/13/2019
* \return 0 on success,1 on faliure.
* \exception Should throw by the client on faliure.
* @param name Name of the resource is a nullptr pointer.
* @param resource Pointer to the resource.
*/
int AddResource(T* resource, std::string name)
{
if (resource)
{
if (m_resourceMap.find(name) != m_resourceMap.end())
{
return 1;
}
m_resourceMap[name] = resource;
return 0;
}
return 1;
}
/**
* \brief GetResource: return resource pointer by name.
*
* Sample exception:
* std::string msg("Getting resource : '" + name + "' has failed because it does not exist in the responsible resource manager.");
* throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
* \author <NAME>
* \date 10/13/2019
* \return nullptr on faliure.
* \exception Should throw by the client on faliure.
* @param name Name of the resource.
*/
T* GetResourceByName(std::string name)
{
if (m_resourceMap.find(name) != m_resourceMap.end())
{
return m_resourceMap[name];
}
return nullptr;
}
std::map<std::string, T*>& GetAllResources()
{
return m_resourceMap;
}
protected:
std::map<std::string, T*> m_resourceMap;
};
}<file_sep>/CS529_Game/src/Platform/Win32_SDL/WinSDLAudioManager.hpp
#pragma once
#include <map>
#include <SDL_mixer.h>
#include "Common/AudioManager.hpp"
namespace My
{
class WinSDLAudioManager : public AudioManager
{
public:
WinSDLAudioManager() noexcept;
WinSDLAudioManager(const WinSDLAudioManager&) = delete;
WinSDLAudioManager& operator=(const WinSDLAudioManager&) = delete;
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
void StopMusic();
void PlayMusic(std::string name, int loops = -1);
void ToggleMusic();
void PlayChunck(std::string name, int channel = -1, int loops = 0);
void Clear();
int AddMusic(std::string name, Mix_Music* mus);
int FreeMusicByName(std::string name);
Mix_Music* GetMusicByName(std::string name);
int AddChunck(std::string name, Mix_Chunk* mus);
int FreeChunckByName(std::string name);
Mix_Chunk* GetChunckByName(std::string name);
public:
std::string m_queueMusicPath;
std::string m_queuechunckPath;
std::string m_currentMusicPath;
std::string m_currentchunckPath;
private:
std::map<std::string, Mix_Music*> g_musicMap;
std::map<std::string, Mix_Chunk*> g_chunckMap;
};
extern std::shared_ptr<WinSDLAudioManager> g_pAudioManager;
}<file_sep>/CS529_Game/src/Entity/Gameplay/Weapon/KineticGunExplosion.cpp
#include "KineticGunExplosion.hpp"
#include "Common/Component/Physics/Body.hpp"
int My::Entity::KineticGunExplosion::Tick(double deltaTime)
{
if (deltaTime != 0.0)
{
if ((life_time_timer += deltaTime) >= WEAPON_KINETICGUN_EXPLOSION_LIFETIME)
{
SetGCToTrue();
}
}
IWeapon::Tick(deltaTime);
return 0;
}
<file_sep>/CS529_Game/src/SceneManager.hpp
#pragma once
#include "src/SerializedLoader.hpp"
namespace My
{
class Scene
{
public:
void Load(const char* level_file_path);
void Unload();
void LoadWave(const char* level_file_path);
public:
GfxConfiguration m_config;
};
extern std::shared_ptr<Scene> g_pScene;
class SceneManager : public IRunTimeModule
{
public:
SceneManager() noexcept;
SceneManager(const SceneManager&) = delete;
SceneManager& operator=(const SceneManager&) = delete;
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
public:
std::string m_currentLevelConfigPath;
std::string m_queueLevelConfigPath;
std::string m_currentWaveConfigPath;
std::string m_queueWaveConfigPath;
};
extern std::shared_ptr<SceneManager> g_pSceneManager;
}<file_sep>/CS529_Game/src/Entity/Gameplay/Objects/Background.hpp
#pragma once
#include "src/Entity/Gameplay/Interface/IMyGameObject.hpp"
namespace My
{
namespace Entity
{
class Background : public IMyGameObject
{
public:
Background() = delete;
explicit Background(void* owner, std::string name) noexcept
:IMyGameObject(MYGAMEOBJECT_TYPE::BACKGROUND, owner, name)
{
}
virtual int Draw() override;
};
}
class BackgroundObjectCreator : public IMyGameObjectCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IMyGameObject* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "Background0") override
{
if (pool)
{
return pool->New<Entity::Background>(owner, name);
}
else
{
return new Entity::Background(owner, name);
}
}
};
}<file_sep>/CS529_Game/src/Platform/Win32_SDL/WinSDLAudioManager.cpp
#include "WinSDLAudioManager.hpp"
#include "src/SerializedLoader.hpp"
My::WinSDLAudioManager::WinSDLAudioManager() noexcept
:
m_queueMusicPath(""),
m_queuechunckPath(""),
m_currentMusicPath(""),
m_currentchunckPath("")
{
}
int My::WinSDLAudioManager::Initialize()
{
if (g_gameObjectConfigurationIfstreamMap.find("AudioList") != g_gameObjectConfigurationIfstreamMap.end())
{
std::ifstream& input(g_gameObjectConfigurationIfstreamMap["AudioList"]);
if (!input.is_open())
{
std::string msg("Can't open object file: AudioList");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
else
{
for (std::string line; getline(input, line);)
{
char audioType[256] = { 0 };
char audioName[256] = { 0 };
char audioPath[256] = { 0 };
if (3 == sscanf_s(line.c_str(), "%s %s %s", audioType, 256, audioName, 256, audioPath, 256))
{
if (std::string(audioType).compare("Music") == 0)
{
auto mus = Mix_LoadMUS(audioPath);
if (mus)
{
AddMusic(audioName, mus);
}
else
{
printf("Failed to load beat music! SDL_mixer Error: %s\n", Mix_GetError());
print_fstream(input);
std::string msg(Str(audioPath) + " fails to load : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
else if (std::string(audioType).compare("Chunck") == 0)
{
auto wav = Mix_LoadWAV(audioPath);
if (wav)
{
AddChunck(audioName, wav);
}
else
{
printf("Failed to load beat music! SDL_mixer Error: %s\n", Mix_GetError());
print_fstream(input);
std::string msg(Str(audioPath) + " fails to load : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
else
{
print_fstream(input);
std::string msg("AudioList does not contain a valid music type : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
else
{
print_fstream(input);
std::string msg("AudioList does not contain a valid music in the form ~ ~ ~ : " + line);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
}
else
{
std::string msg("Please register 'AudioList' into g_gameObjectConfigurationIfstreamMap.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
return 0;
}
int My::WinSDLAudioManager::Tick(double deltaTime)
{
if (m_queueMusicPath != "")
{
PlayMusic(m_queueMusicPath);
m_currentMusicPath = m_queueMusicPath;
m_queueMusicPath = "";
}
if (m_queuechunckPath != "")
{
PlayChunck(m_queuechunckPath);
m_currentchunckPath = m_queuechunckPath;
m_queuechunckPath = "";
}
return 0;
}
int My::WinSDLAudioManager::Finalize()
{
StopMusic();
Clear();
return 0;
}
void My::WinSDLAudioManager::StopMusic()
{
//Stop the music
Mix_HaltMusic();
}
void My::WinSDLAudioManager::PlayMusic(std::string name, int loops)
{
//Stop the music
Mix_HaltMusic();
//If there is no music playing
if (Mix_PlayingMusic() == 0)
{
//Play the music
if (g_musicMap.find(name) != g_musicMap.end())
{
if (Mix_PlayMusic(g_musicMap[name], loops) == -1) {
printf("Mix_PlayMusic: %s\n", Mix_GetError());
// well, there's no music, but most games don't break without music...
}
}
else
{
std::string msg("Audio manager does not contain music with name: " + name);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
void My::WinSDLAudioManager::ToggleMusic()
{
//If music is being played
if (Mix_PlayingMusic() != 0)
{
//If the music is paused
if (Mix_PausedMusic() == 1)
{
//Resume the music
Mix_ResumeMusic();
}
//If the music is playing
else
{
//Pause the music
Mix_PauseMusic();
}
}
}
void My::WinSDLAudioManager::PlayChunck(std::string name, int channel, int loops)
{
//Play the music
if (g_chunckMap.find(name) != g_chunckMap.end())
{
if (Mix_PlayChannel(channel, g_chunckMap[name], loops) == -1) {
printf("Mix_PlayChannel: %s\n", Mix_GetError());
// well, there's no music, but most games don't break without music...
}
}
else
{
std::string msg("Audio manager does not contain music with name: " + name);
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
void My::WinSDLAudioManager::Clear()
{
for (auto it = g_chunckMap.begin(); it != g_chunckMap.end(); ++it)
{
Mix_FreeChunk(it->second);
}
for (auto it = g_musicMap.begin(); it != g_musicMap.end(); ++it)
{
Mix_FreeMusic(it->second);
}
g_chunckMap.clear();
g_musicMap.clear();
}
int My::WinSDLAudioManager::AddMusic(std::string name, Mix_Music* mus)
{
if (g_musicMap[name])
{
Mix_FreeMusic(g_musicMap[name]);
}
else
{
g_musicMap[name] = mus;
}
return 0;
}
int My::WinSDLAudioManager::FreeMusicByName(std::string name)
{
if (g_musicMap.find(name) != g_musicMap.end())
{
Mix_FreeMusic(g_musicMap[name]);
g_musicMap.erase(name);
return 0;
}
else
{
return 1;
}
}
Mix_Music* My::WinSDLAudioManager::GetMusicByName(std::string name)
{
if (g_musicMap.find(name) != g_musicMap.end())
{
return g_musicMap[name];
}
else
{
return nullptr;
}
}
int My::WinSDLAudioManager::AddChunck(std::string name, Mix_Chunk* mus)
{
if (g_chunckMap[name])
{
Mix_FreeChunk(g_chunckMap[name]);
}
else
{
g_chunckMap[name] = mus;
}
return 0;
}
int My::WinSDLAudioManager::FreeChunckByName(std::string name)
{
if (g_chunckMap.find(name) != g_chunckMap.end())
{
Mix_FreeChunk(g_chunckMap[name]);
g_chunckMap.erase(name);
return 0;
}
else
{
return 1;
}
}
Mix_Chunk* My::WinSDLAudioManager::GetChunckByName(std::string name)
{
if (g_chunckMap.find(name) != g_chunckMap.end())
{
return g_chunckMap[name];
}
else
{
return nullptr;
}
}
<file_sep>/CS529_Game/Main.cpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: Main
Purpose: implementation of Main
Language: c++ 11
Platform: win32 x86
Project: CS529_project_final
Author: <NAME> hang.yu 60001119
Creation date: 10/17/2019
- End Header ----------------------------*/
#include "Main.hpp"
using namespace My;
int main(int argc, char* args[])
{
// This api call make the process be aware of dpi
// i.e. managing dpi by ourself instead of Desktop Window Manager(DWM)
// i.e. ignoring user dpi scales which are common to be 125%, 150%, etc
// Not making this api call would result in the window we created to be scaled with
// user dpi setting (e.g. "Change Display Setting" in Win10).
//https://docs.microsoft.com/en-us/windows/win32/api/windef/ne-windef-dpi_awareness
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
// Initialization
{
Initialize();
}
// Game Loop
{
GameLoop();
}
// Finalize()
{
Finalize();
}
return 0;
}<file_sep>/CS529_Game/src/Platform/Win32_SDL/WinSDLOpenGLApplication.hpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: WinSDLOpenGLApplication.hpp
Purpose: header file of WinSDLOpenGLApplication
Language: c++ 11
Platform: win32 x86
Project: CS529_final_project
Author: <NAME> hang.yu 60001119
Creation date: 10/13/2019
- End Header ----------------------------*/
#pragma once
#include "Common/BaseApplication.hpp"
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_mixer.h>
#include <SDL_opengl.h>
#include <SDL_opengl_glext.h>
#include <windows.h>
extern PFNGLCREATESHADERPROC glCreateShader;
extern PFNGLSHADERSOURCEPROC glShaderSource;
extern PFNGLCOMPILESHADERPROC glCompileShader;
extern PFNGLGETSHADERIVPROC glGetShaderiv;
extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;
extern PFNGLDELETESHADERPROC glDeleteShader;
extern PFNGLATTACHSHADERPROC glAttachShader;
extern PFNGLCREATEPROGRAMPROC glCreateProgram;
extern PFNGLLINKPROGRAMPROC glLinkProgram;
extern PFNGLVALIDATEPROGRAMPROC glValidateProgram;
extern PFNGLGETPROGRAMIVPROC glGetProgramiv;
extern PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog;
extern PFNGLUSEPROGRAMPROC glUseProgram;
extern PFNGLGENVERTEXARRAYSPROC glGenVertexArrays;
extern PFNGLGENBUFFERSPROC glGenBuffers;
extern PFNGLBINDVERTEXARRAYPROC glBindVertexArray;
extern PFNGLBINDBUFFERPROC glBindBuffer;
extern PFNGLBUFFERDATAPROC glBufferData;
extern PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer;
extern PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray;
extern PFNGLGENERATEMIPMAPPROC glGenerateMipmap;
extern PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;
extern PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv;
extern PFNGLUNIFORM1IPROC glUniform1i;
bool initGLExtensions();
namespace My
{
class WinSDLOpenGLApplication : public BaseApplication
{
public:
WinSDLOpenGLApplication() = delete;
WinSDLOpenGLApplication(const WinSDLOpenGLApplication&) = delete;
WinSDLOpenGLApplication& operator=(const WinSDLOpenGLApplication&) = delete;
explicit WinSDLOpenGLApplication(const GfxConfiguration& config)
:
BaseApplication(config),
m_gContext(nullptr),
m_pWindow(nullptr),
m_renderer(nullptr),
m_texTarget(nullptr),
m_programId(0)
{}
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
virtual int BeginDraw() override;
virtual int OnDraw() override;
virtual int EndDraw() override;
virtual void ShowMessage(const std::wstring& title, const std::wstring& message) override;
SDL_Window* GetWindow() noexcept;
SDL_Renderer* GetRenderer() noexcept;
virtual void SetConfig(const GfxConfiguration& config) noexcept override;
void AddCallBackToOnDraw(void(*func)()) { m_OnDrawCallbacks.push_back(func); };
void ClearCallBackOnDraw() { m_OnDrawCallbacks.clear(); };
private:
GLuint m_programId;
SDL_Window* m_pWindow;
SDL_GLContext m_gContext;
SDL_Renderer* m_renderer;
SDL_Texture* m_texTarget;
std::vector<std::function<void()>> m_OnDrawCallbacks;
};
}<file_sep>/GameEngine/Common/Utility/EngineException.hpp
#pragma once
#include <string>
namespace My
{
class EngineException
{
public:
EngineException() = delete;
explicit EngineException( const wchar_t* file,unsigned int line,const std::wstring& note = L"" )
:
file( file ), //_CRT_WIDE(__FILE__)
line( line ), //__LINE__,
note( note ) //L"Error!"
{}
const std::wstring& GetNote() const;
const std::wstring& GetFile() const;
unsigned int GetLine() const;
std::wstring GetLocation() const;
virtual std::wstring GetFullMessage() const;
virtual std::wstring GetExceptionType() const;
private:
std::wstring note;
std::wstring file;
unsigned int line;
};
std::wstring str2wstr(const std::string& str);
std::string wstr2str(const std::wstring& wstr);
}
<file_sep>/GameEngine/Common/BaseApplication.cpp
#include "BaseApplication.hpp"
bool My::BaseApplication::m_bQuit = false;
double My::BaseApplication::frametime = 0.0;
double My::BaseApplication::time_modifier = 1.0;
double My::BaseApplication::static_frametime = 0.0;
bool My::BaseApplication::m_bPaused = false;
My::BaseApplication::BaseApplication(const GfxConfiguration& config)
:
m_config(config)
{}
int My::BaseApplication::Initialize()
{
return 0;
}
int My::BaseApplication::Tick(double deltaTime)
{
return 0;
}
int My::BaseApplication::Finalize()
{
return 0;
}
int My::BaseApplication::BeginDraw()
{
return 0;
}
int My::BaseApplication::OnDraw()
{
return 0;
}
int My::BaseApplication::EndDraw()
{
return 0;
}
void My::BaseApplication::ShowMessage(const std::wstring& title, const std::wstring& message)
{
std::wcerr << title << std::endl;
std::wcerr << message << std::endl;
}
const My::GfxConfiguration& My::BaseApplication::GetConfig() const noexcept { return m_config; }
void My::BaseApplication::SetConfig(const GfxConfiguration& config) noexcept { m_config = config; }
void My::BaseApplication::UpdateFrameTime(double deltaTime)
{
BaseApplication::frametime = deltaTime;
BaseApplication::static_frametime = deltaTime;
(m_bPaused) ? frametime = 0.0 : frametime = time_modifier * static_frametime;
}
bool My::BaseApplication::IsQuit()
{
return m_bQuit;
}
bool My::BaseApplication::IsPuased()
{
return m_bPaused;
}
void My::BaseApplication::SetQuit(bool q)
{
m_bQuit = q;
}
void My::BaseApplication::TogglePause()
{
m_bPaused = !m_bPaused;
}
<file_sep>/CS529_Game/src/Component/Graphics/SceneComponent.hpp
#pragma once
#include <SDL.h>
#include "Common/Component/Graphics/SceneComponent.hpp"
namespace My
{
namespace Component
{
class SceneComponent : public IComponent
{
public:
SceneComponent() = delete;
explicit SceneComponent(void* owner, std::string name);
virtual ~SceneComponent();
virtual void Update(double deltaTime) override;
virtual void Serialize(std::wostream& wostream) override;
virtual void Draw();
void DrawBackground();
void DrawPauseMenu();
void DrawObject();
};
}
class SceneComponentCreator : public IComponentCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IComponent* Create(void* owner = nullptr, MemoryPool* pool = nullptr, std::string name = "SceneComponent0") override
{
if (pool)
{
return pool->New<Component::SceneComponent>(owner, name);
}
else
{
return new Component::SceneComponent(owner, name);
}
}
};
}
<file_sep>/GameEngine/Common/Geommath/Shape/ShapeType.h
#pragma once
#include <string>
#include <map>
#include <memory>
namespace My
{
enum class SHAPE_TYPE
{
CIRCLE = 0,
RECTANGLE,
NUM
};
}<file_sep>/GameEngine/Common/Utility/Timer.cpp
#include "Timer.hpp"
My::Timer::Timer()
{
if (std::chrono::steady_clock::is_steady == false)
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, L"C++11 std::chrono::steady_clock::is_steady() returns FALSE.");
last = steady_clock::now();
}
void My::Timer::Reset() noexcept
{
last = steady_clock::now();
}
double My::Timer::Mark() noexcept
{
const duration<double> Time = steady_clock::now() - last;
return Time.count();
}
<file_sep>/GameEngine/Common/Component/Physics/Body.cpp
#include "Body.hpp"
#include "Common/Utility/Utility.hpp"
namespace My
{
/* (Optional) Using a custom memory pool to create a allocated space */
IComponent* BodyCreator::Create(void* owner, MemoryPool* pool, std::string name)
{
if (pool)
{
return pool->New<Component::Body>(owner, name);
}
else
{
return new Component::Body(owner, name);
}
}
}
My::Component::Body::Body(void* owner, std::string name)
:
IComponent(COMPONENT_TYPE::BODY, owner, name),
b_simulated(false),
m_Mass(0.0f),
m_InvMass(0.0f),
m_shape(nullptr),
m_angle(0.0f)
{
Vector2DZero(&m_position);
Vector2DZero(&m_prev_position);
Vector2DZero(&m_velocity);
Vector2DZero(&m_acceleration);
Vector2DZero(&m_force);
}
My::Component::Body::~Body()
{
if (m_shape) g_pMemoryManager->Delete(m_shape);
}
void My::Component::Body::Update(double deltaTime)
{
}
void My::Component::Body::PhysicsUpdate(double deltaTime)
{
std::lock_guard<std::mutex>lock(m_mutex);
float t = static_cast<float>(deltaTime);
if (m_Mass != 0.0f && b_simulated)
{
Vector2DScale(&m_acceleration, &m_force, m_Mass); // Update acceleration
}
Vector2DScaleAdd(&m_velocity, &m_acceleration, &m_velocity, t); // Update velocity
Vector2DSet(&m_prev_position, &m_position); // Update prev position
Vector2DScaleAdd(&m_position, &m_velocity, &m_position, t); // Update postion
Vector2DZero(&m_force); // Reset force to zero at the end of each update.
// The force on body should be modified by other body component && various logical event such as collision.
}
void My::Component::Body::Serialize(std::ifstream& fstream)
{
for (std::string line; getline(fstream, line);)
{
if (line[0] == ']')
{
return;
}
if (6 == sscanf_s(line.c_str(), "p (%f,%f) v (%f,%f) a (%f,%f)", &m_position.x, &m_position.y, &m_velocity.x, &m_velocity.y, &m_acceleration.x, &m_acceleration.y))
{
continue;
}
if (1 == sscanf_s(line.c_str(), "m %f", &m_Mass))
{
if (m_Mass > 0.0f) m_InvMass = 1.0f / m_Mass;
continue;
}
char shapeType[256] = { 0 };
if (1 == sscanf_s(line.c_str(), "!%s", &shapeType, 256))
{
// Serialize the game object component
if (g_shapeSerializationMap.find(shapeType) != g_shapeSerializationMap.end())
{
if (m_shape) g_pMemoryManager->Delete(m_shape);
m_shape = g_shapeCreatorMap[g_shapeSerializationMap[shapeType]]->Create(this, g_pMemoryManager.get());
m_shape->Serialize(fstream);
}
else
{
print_fstream(fstream);
std::string msg("Body component does not provide a valid shape type: " + std::string(shapeType) + ".");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
}
void My::Component::Body::Serialize(std::wostream& wostream)
{
wostream << "[Component: Body, ";
wostream << "Mass:" << m_Mass << "]";
}
void My::Component::Body::Copy(const Body* body)
{
Vector2DSet(&m_position, &body->m_position);
Vector2DSet(&m_prev_position, &body->m_prev_position);
Vector2DSet(&m_velocity, &body->m_velocity);
Vector2DSet(&m_acceleration, &body->m_acceleration);
Vector2DSet(&m_force, &body->m_force);
m_angle = body->m_angle;
}
<file_sep>/GameEngine/Common/Component/Graphics/SceneComponent.hpp
#pragma once
#include "Common/Component/Interface/IComponent.hpp"
namespace My
{
namespace Component
{
class SceneComponent;
}
class SceneIComponentCreator;
}
<file_sep>/GameEngine/Common/Event/EventDispatcher.hpp
#pragma once
#include <vector>
#include "Common/Event/EventManager.hpp"
#include "Common/Entity/GameObjectResourceManager.hpp"
namespace My
{
class EventDispatcher : public IRunTimeModule
{
public:
EventDispatcher() noexcept;
EventDispatcher(const EventDispatcher&) = delete;
EventDispatcher& operator=(const EventDispatcher&) = delete;
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
virtual void Serialize(std::wostream& wostream) override;
void Clear();
void BroadcastToAll(double wait_time, std::weak_ptr<Event> e);
void DispatchToGameObject(double wait_time, std::weak_ptr<Event> e, IGameObject* object);
void DispatchToSubscribers(double wait_time, std::weak_ptr<Event> e);
public:
typedef std::pair<double, std::pair<std::shared_ptr<Event>, IGameObject*>> event_object_type;
/* Support delayed events */
std::vector<event_object_type> m_disptachList;
};
// TODO : Initialize in your application
extern std::shared_ptr<EventDispatcher> g_pEventDispatcher;
}<file_sep>/CS529_Game/src/Entity/Gameplay/Pack/Pack_Shield.hpp
#pragma once
#include "src/Entity/Gameplay/Interface/IMyGameObject.hpp"
#include "src/Event/MyEvent.hpp"
namespace My
{
namespace Entity
{
class Pack_Shield : public IMyGameObject
{
public:
Pack_Shield() = delete;
explicit Pack_Shield(void* owner, std::string name) noexcept
:
IMyGameObject(MYGAMEOBJECT_TYPE::Item_SHIELD, owner, name),
life_time(PACK_LIFETIME)
{
m_eventManager.AddEventRegistry(EventType::ON_COMPONENTHIT);
}
virtual int Tick(double deltaTime) override;
virtual int Draw() override;
virtual void HandleEvent(std::weak_ptr<Event> e)
{
if (IsActive())
{
std::shared_ptr<Event> _e = e.lock();
switch (_e->GetType())
{
case EventType::ON_COMPONENTHIT:
OnComponentHit(_e);
break;
default:
break;
}
}
}
void OnComponentHit(std::weak_ptr<Event> e);
private:
double life_time;
};
}
class Pack_ShieldObjectCreator : public IMyGameObjectCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IMyGameObject* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "Pack_Shield0") override
{
if (pool)
{
return pool->New<Entity::Pack_Shield>(owner, name);
}
else
{
return new Entity::Pack_Shield(owner, name);
}
}
};
}<file_sep>/GameEngine/Common/Event/Event.cpp
#include "Event.hpp"
My::Event::Event(EventType type) : m_type(type) {}
My::Event::~Event() {}
void My::Event::Serialize(std::wostream& wostream) {}
My::EventType My::Event::GetType() { return m_type; }
void My::Event::AddSubscriber(void* sub)
{
subs.push_back(sub);
}
std::vector<void*>& My::Event::GetSubscriber()
{
return subs;
}
<file_sep>/CS529_Game/src/Component/Graphics/Sprite.hpp
#pragma once
#include <SDL.h>
#include <SDL_opengl.h>
#include <SDL_opengl_glext.h>
#include "Common/Component/Graphics/Sprite.hpp"
namespace My
{
namespace Component
{
class Sprite : public IComponent
{
public:
Sprite() = delete;
explicit Sprite(void* owner, std::string name);
virtual ~Sprite();
virtual void Update(double deltaTime) override;
virtual void Serialize(std::ifstream& fstream) override;
virtual void Serialize(std::wostream& wostream) override;
/* Flash between default and hit sprite */
void StartHitFlash();
void SetCurrentSpriteByName(std::string name);
public:
SDL_Texture* m_sprite;
SDL_Rect m_rcSprite;
/* degree is in degree */
float m_degree;
private:
std::string m_currentSpriteName;
double flash_period;
double flash_period_timer;
// Sprites managed by this component under different names.
std::map<std::string, std::pair<SDL_Texture*, SDL_Rect>> m_spriteMap;
};
}
class SpriteCreator : public IComponentCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IComponent* Create(void* owner = nullptr, MemoryPool* pool = nullptr, std::string name = "Sprite0") override
{
if (pool)
{
return pool->New<Component::Sprite>(owner, name);
}
else
{
return new Component::Sprite(owner, name);
}
}
};
}
<file_sep>/CS529_Game/src/Entity/Gameplay/Weapon/MissileBullet.cpp
#include "MissileBullet.hpp"
#include "Common/Utility/Utility.hpp"
#include "Common/Component/ComponentManager.hpp"
#include "Common/Component/Physics/Body.hpp"
#include "Common/Entity/GameObjectResourceManager.hpp"
#include "src/Component/Gameplay/HealthPoint.hpp"
#include "src/Component/Graphics/SceneComponent.hpp"
#include "src/Platform/Win32_SDL/WinSDLOpenGLApplication.hpp"
int My::Entity::MissleBullet::Tick(double deltaTime)
{
if (deltaTime != 0.0)
{
auto p_transformCom = static_cast<Component::Body*>(GetComponent(COMPONENT_TYPE::BODY));
auto p_App = static_cast<WinSDLOpenGLApplication*>(g_pBaseApplication.get());
int SCREEN_WIDTH, SCREEN_HEIGHT;
SDL_GetWindowSize(p_App->GetWindow(), &SCREEN_WIDTH, &SCREEN_HEIGHT);
{
std::lock_guard<std::mutex> lock(p_transformCom->m_mutex);
/* collide with edges of screen */
if (p_transformCom->m_position.x < 0 || p_transformCom->m_position.x > SCREEN_WIDTH || p_transformCom->m_position.y < 0 || p_transformCom->m_position.y > SCREEN_HEIGHT) {
SetGCToTrue();
}
}
}
IWeapon::Tick(deltaTime);
return 0;
}
int My::Entity::MissleBullet::Draw()
{
if (auto sceneCom = GetComponent(COMPONENT_TYPE::SCENECOMPONENT))
{
static_cast<Component::SceneComponent*>(sceneCom)->Draw();
}
return 0;
}
void My::Entity::MissleBullet::OnComponentHit(std::weak_ptr<Event> e)
{
static int count = 0;
std::shared_ptr<Event> _e = e.lock();
auto event = static_cast<Events::DeathEvent*>(_e.get());
auto other = reinterpret_cast<IMyGameObject*>(event->other);
if (other->GetType() == MYGAMEOBJECT_TYPE::UFO)
{
DEBUG_wPRINT(str2wstr(m_name + " collides with "));
DEBUG_wPRINT(str2wstr(other->GetName()) << "\n");
{
auto hp_com = static_cast<Component::HealthPoint*>(other->GetComponent(COMPONENT_TYPE::HEALTHPOINT));
std::lock_guard<std::mutex> lock1(hp_com->m_mutex);
hp_com->Reduce(WEAPON_MISSILE_DAM_BASE);
}
char weaponType[256] = "MissileExplosion";
std::string weaponName(m_name + "_explosion" + Str(++count));
// Serialize the game object and set its owner to be the root object.
if (g_weaponSerializationMap.find(weaponType) != g_weaponSerializationMap.end())
{
auto pNewObject = LoadIWeaponFromFile(this, weaponType, weaponName);
// Add game object under the resource manager.
if (1 == g_pGameObjectResourceManager->AddResource(pNewObject, weaponName))
{
std::string msg("Adding resource : '" + std::string(weaponName) + "' has failed.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
auto p_other_sprite = static_cast<Component::Sprite*>(pNewObject->GetComponent(COMPONENT_TYPE::SPRITE));
auto p_ohter_transformCom = static_cast<Component::Body*>(pNewObject->GetComponent(COMPONENT_TYPE::BODY));
auto p_transformCom = static_cast<Component::Body*>(GetComponent(COMPONENT_TYPE::BODY));
{
std::lock_guard<std::mutex> lock1(p_ohter_transformCom->m_mutex);
std::lock_guard<std::mutex> lock2(p_transformCom->m_mutex);
Vector2DSet(&p_ohter_transformCom->m_position, &p_transformCom->m_position);
p_ohter_transformCom->m_position.y -= static_cast<float>(p_other_sprite->m_rcSprite.h / 2);
}
}
else
{
std::string msg("File does not provide a valid game object of type: " + std::string(weaponName));
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
SetGCToTrue();
}
}
<file_sep>/GameEngine/Common/Geommath/2D/Math.hpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: Math
Purpose: header file of Math
Language: c++ 11
Platform: win32 x86
Project: CS529_project_2
Author: <NAME> hang.yu 60001119
Creation date: 10/03/2019
- End Header ----------------------------*/
#pragma once
#include <math.h>
#ifndef EPSILON
#define EPSILON 0.0001f
#endif
#ifndef F_UNDEFINE
#define F_UNDEFINE 19951215.0f // Weird number, hum?
#endif
#ifndef PI
#define PI 3.14159265358979323846f
#endif
#ifndef TWO_PI
#define TWO_PI 3.14159265358979323846f * 2.0f
#endif
#ifndef RAD
#define RAD 0.0174532925f
#endif
#define RAND_I(LO, HI) LO + static_cast <int> (rand()) / (static_cast <int> (RAND_MAX / (HI - LO)))
#define RAND_F(LO, HI) LO + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI - LO)))
#define IN_RANGE(a, x, y) (a >= x && a <= y)
#define MAX(x, y) (x>y)?x:y
#define MIN(x, y) (x<y)?x:y<file_sep>/GameEngine/Common/GfxConfiguration.hpp
#pragma once
#include <stdint.h>
#include <iostream>
#include <string>
#include <fstream>
#include <map>
namespace My {
struct GfxConfiguration {
/// all-elements constructor.
/// \param[in] r the red color depth in bits
/// \param[in] g the green color depth in bits
/// \param[in] b the blue color depth in bits
/// \param[in] a the alpha color depth in bits
/// \param[in] d the depth buffer depth in bits
/// \param[in] s the stencil buffer depth in bits
/// \param[in] msaa the msaa sample count
/// \param[in] width the screen width in pixel
/// \param[in] height the screen height in pixel
GfxConfiguration(const char* file_path = nullptr ,uint32_t r = 8, uint32_t g = 8,
uint32_t b = 8, uint32_t a = 8,
uint32_t d = 32, uint32_t s = 0, uint32_t msaa = 0, uint32_t maxFPS = 60,
uint32_t width = 600, uint32_t height = 800, const wchar_t* app_name=L"Final Project") :
redBits(r), greenBits(g), blueBits(b), alphaBits(a),
depthBits(d), stencilBits(s), msaaSamples(msaa), maxfps(maxFPS),
screenWidth(width), screenHeight(height), appName(app_name)
{
if (file_path)
{
std::map<std::string, int> config_dict;
std::ifstream input(file_path);
if (!input.is_open())
{
exit(1);
}
else
{
for (std::string line; getline(input, line);)
{
char key[256] = { 0 };
int value = 0;
if (2 == sscanf_s(line.c_str(), "[%s %d", key, 256, &value))
{
config_dict[key] = value;
}
}
if (config_dict.find("Screen_width") != config_dict.end())
{
screenWidth = config_dict["Screen_width"];
}
if (config_dict.find("Screen_height") != config_dict.end())
{
screenHeight = config_dict["Screen_height"];
}
if (config_dict.find("MAX_FPS") != config_dict.end())
{
maxfps = config_dict["MAX_FPS"];
}
input.close();
}
}
}
uint32_t redBits; ///< red color channel depth in bits
uint32_t greenBits; ///< green color channel depth in bits
uint32_t blueBits; ///< blue color channel depth in bits
uint32_t alphaBits; ///< alpha color channel depth in bits
uint32_t depthBits; ///< depth buffer depth in bits
uint32_t stencilBits; ///< stencil buffer depth in bits
uint32_t msaaSamples; ///< MSAA samples
uint32_t maxfps; ///< maximum fps
uint32_t screenWidth;
uint32_t screenHeight;
const wchar_t* appName;
friend std::wostream& operator<<(std::wostream& out, const GfxConfiguration& conf)
{
out << "App Name:" << conf.appName << std::endl;
out << "GfxConfiguration:" <<
" R:" << conf.redBits <<
" G:" << conf.greenBits <<
" B:" << conf.blueBits <<
" A:" << conf.alphaBits <<
" D:" << conf.depthBits <<
" S:" << conf.stencilBits <<
" M:" << conf.msaaSamples <<
" FPS: " << conf.maxfps <<
" W:" << conf.screenWidth <<
" H:" << conf.screenHeight <<
std::endl;
return out;
}
};
}
<file_sep>/GameEngine/Common/Component/Physics/BodyResourceManager.hpp
#pragma once
#include "Body.hpp"
namespace My {
class BodyResourceManager : public ResourceManager<Component::Body>
{
public:
virtual int Initialize() override;
virtual int PhysicsUpdate(double deltaTime);
virtual int CollisionUpdate(double deltaTime);
private:
bool (*Shape2DCollisionFunction[static_cast<size_t>(SHAPE_TYPE::NUM)][static_cast<size_t>(SHAPE_TYPE::NUM)])(Component::Body* body1, Component::Body* body2);
};
// TODO : Initialize in your application
extern std::shared_ptr<BodyResourceManager> g_pBodyResourceManager;
namespace Collision
{
bool Circle2Circle(Component::Body* body1, Component::Body* body2);
bool Circle2Rectangle(Component::Body* body1, Component::Body* body2);
bool Rectangle2Circle(Component::Body* body1, Component::Body* body2);
bool Rectangle2Rectangle(Component::Body* body1, Component::Body* body2);
}
}<file_sep>/CS529_Game/src/Component/Graphics/Sprite.cpp
#include "Sprite.hpp"
#include "Common/Component/ComponentManager.hpp"
#include "Common/Component/Physics/Body.hpp"
#include "src/Platform/Win32_SDL/WinSDLOpenGLApplication.hpp"
#include "Common/Utility/Utility.hpp"
My::Component::Sprite::Sprite(void* owner, std::string name)
:
IComponent(COMPONENT_TYPE::SPRITE, owner, name),
m_sprite(nullptr),
m_degree(0.0f),
flash_period(0.0),
flash_period_timer(0.0),
m_currentSpriteName("")
{
m_rcSprite.x = 0;
m_rcSprite.y = 0;
m_rcSprite.w = 0;
m_rcSprite.h = 0;
m_spriteMap["nullptr"] = std::make_pair(nullptr, m_rcSprite);
}
My::Component::Sprite::~Sprite()
{
for (auto it = m_spriteMap.begin(); it != m_spriteMap.end(); ++it)
{
SDL_DestroyTexture(it->second.first);
}
}
void My::Component::Sprite::Update(double deltaTime)
{
// Flash to default sprite
if (flash_period != 0.0 && (flash_period_timer+=deltaTime) >= flash_period * 0.5)
{
if (m_currentSpriteName.compare("Hit") == 0)
{
SetCurrentSpriteByName("Default");
}
}
auto owner = static_cast<ComponentManager*>(GetOwner());
auto temp = owner->GetComponent(COMPONENT_TYPE::BODY);
auto p_App = static_cast<WinSDLOpenGLApplication*>(g_pBaseApplication.get());
if (temp && p_App)
{
int SCREEN_WIDTH, SCREEN_HEIGHT, SPRITE_W, SPRITE_H;
SDL_GetWindowSize(p_App->GetWindow(), &SCREEN_WIDTH, &SCREEN_HEIGHT);
m_rcSprite.w = m_spriteMap[m_currentSpriteName].second.w;
m_rcSprite.h = m_spriteMap[m_currentSpriteName].second.h;
if (m_rcSprite.w == 0 && m_rcSprite.h == 0)
{
SDL_QueryTexture(m_sprite, nullptr, nullptr, &SPRITE_W, &SPRITE_H);
m_rcSprite.w = SPRITE_W;
m_rcSprite.h = SPRITE_H;
}
else
{
SPRITE_W = m_rcSprite.w;
SPRITE_H = m_rcSprite.h;
}
auto p_transformCom = static_cast<Component::Body*>(temp);
{
std::lock_guard<std::mutex> lock(p_transformCom->m_mutex);
m_rcSprite.x = static_cast<int>(p_transformCom->m_position.x) - SPRITE_W / 2;
m_rcSprite.y = static_cast<int>(p_transformCom->m_position.y) - SPRITE_H / 2;
m_degree = p_transformCom->m_angle / RAD;
}
}
}
void My::Component::Sprite::Serialize(std::ifstream& fstream)
{
for (std::string line; getline(fstream, line);)
{
char spritePath[256] = { 0 };
char spriteName[256] = { 0 };
SDL_Rect rc;
rc.x = 0;
rc.y = 0;
rc.w = 0;
rc.h = 0;
if (1 == sscanf_s(line.c_str(), "flash_period %lf", &flash_period))
{
}
else if (2 <= sscanf_s(line.c_str(), "~%s %s %d %d", spritePath, 256, spriteName, 256, &rc.w, &rc.h))
{
std::string path(spritePath);
if (m_spriteMap.find(spriteName) != m_spriteMap.end())
{
// If m_sprite exists, free it for updating.
SDL_DestroyTexture(m_spriteMap[spriteName].first);
}
auto p_App = static_cast<WinSDLOpenGLApplication*>(g_pBaseApplication.get());
auto* bmpTex = IMG_LoadTexture(p_App->GetRenderer(), spritePath);
if (!bmpTex)
{
print_fstream(fstream);
std::string msg("Sprite path " + path + " can not be loaded. \nIMG error : " + IMG_GetError());
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
m_currentSpriteName = spriteName;
m_rcSprite = rc;
m_spriteMap[spriteName] = std::make_pair(bmpTex, rc);
m_sprite = bmpTex;
}
else if (line[0] == ']')
{
return;
}
else
{
print_fstream(fstream);
std::string msg("Sprite serialization has failed at line " + line + ".");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
void My::Component::Sprite::Serialize(std::wostream& wostream)
{
wostream << "[Component : Sprite ";
for (auto it = m_spriteMap.begin(); it != m_spriteMap.end(); ++it)
{
wostream << str2wstr("sprite : " + it->first + " ");
}
wostream << "] ";
}
void My::Component::Sprite::StartHitFlash()
{
// Flash to hit sprite
if (flash_period_timer >= flash_period)
{
flash_period_timer = 0.0;
SetCurrentSpriteByName("Hit");
}
}
void My::Component::Sprite::SetCurrentSpriteByName(std::string name)
{
if (m_currentSpriteName.compare(name) != 0)
{
if (m_spriteMap.find(name) != m_spriteMap.end())
{
m_sprite = m_spriteMap[name].first;
m_currentSpriteName = name;
}
else
{
std::string msg("This sprite component does not contain " + name + ".");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
<file_sep>/CS529_Game/src/Entity/Gameplay/Weapon/KineticGun.hpp
#pragma once
#include "Common/Event/Event.hpp"
#include "src/Entity/Gameplay/Interface/IWeapon.hpp"
#include "src/Event/MyEvent.hpp"
namespace My
{
namespace Entity
{
class KineticGun : public IWeapon
{
public:
KineticGun() = delete;
explicit KineticGun(void* owner, std::string name) noexcept
:
IWeapon(WEAPON_TYPE::WEAPON_KINETICGUN, owner, name),
bullet_id(0),
fire_period(WEAPON_KINETICGUN_FIRE_PERIOD),
fire_period_timer(WEAPON_KINETICGUN_FIRE_PERIOD)
{
}
virtual int Tick(double deltaTime) override;
virtual int Draw() override;
IWeapon* SpawnBullet();
void SpawnBullet1();
void SpawnBullet2();
void SpawnBullet3();
private:
uint64_t bullet_id;
double fire_period;
double fire_period_timer;
};
}
class KineticGunObjectCreator : public IWeaponCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IWeapon* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "KineticGun0") override
{
if (pool)
{
return pool->New<Entity::KineticGun>(owner, name);
}
else
{
return new Entity::KineticGun(owner, name);
}
}
};
}<file_sep>/CS529_Game/src/Component/Logic/PackController.cpp
#include <SDL.h>
#include "PackController.hpp"
#include "Common/Geommath/2D/Vector2D.hpp"
#include "Common/Component/ComponentManager.hpp"
#include "Common/Component/Physics/Body.hpp"
#include "src/Platform/Win32_SDL/WinSDLOpenGLApplication.hpp"
#include "src/Component/Graphics/Sprite.hpp"
My::Component::PackController::PackController(void* owner, std::string name)
:
IComponent((COMPONENT_TYPE::PACKCONTROLLER), owner, name)
{
Vector2DSet(&m_velocity, ((RAND_I(0,1)==0)?-1.0f:1.0f) * RAND_F(PACK_SPEED_LOW, PACK_SPEED_HIGH), ((RAND_I(0, 1) == 0) ? -1.0f : 1.0f) * RAND_F(PACK_SPEED_LOW, PACK_SPEED_HIGH));
}
void My::Component::PackController::Update(double deltaTime)
{
// Transformation
{
auto temp = static_cast<ComponentManager*>(GetOwner())->GetComponent(COMPONENT_TYPE::BODY);
auto p_App = static_cast<WinSDLOpenGLApplication*>(g_pBaseApplication.get());
if (temp && p_App)
{
int SCREEN_WIDTH, SCREEN_HEIGHT, SPRITE_W, SPRITE_H;
SDL_GetWindowSize(p_App->GetWindow(), &SCREEN_WIDTH, &SCREEN_HEIGHT);
auto p_transformCom = static_cast<Component::Body*>(temp);
std::lock_guard<std::mutex> lock(p_transformCom->m_mutex);
// Reset rotation
p_transformCom->m_angle = 0.0f;
// Windows Limit
auto p_App = static_cast<WinSDLOpenGLApplication*>(g_pBaseApplication.get());
auto temp_sprite = static_cast<ComponentManager*>(GetOwner())->GetComponent(COMPONENT_TYPE::SPRITE);
if (temp_sprite && p_App)
{
auto sprite_com = static_cast<Component::Sprite*>(temp_sprite);
int SCREEN_WIDTH, SCREEN_HEIGHT, SPRITE_W, SPRITE_H;
SDL_GetWindowSize(p_App->GetWindow(), &SCREEN_WIDTH, &SCREEN_HEIGHT);
SPRITE_W = sprite_com->m_rcSprite.w;
SPRITE_H = sprite_com->m_rcSprite.h;
/* collide with edges of screen */
if (sprite_com->m_rcSprite.x < 0) {
sprite_com->m_rcSprite.x = 0;
p_transformCom->m_position.x = static_cast<float>(sprite_com->m_rcSprite.x + SPRITE_W / 2);
if (m_velocity.x < 0.0)
{
m_velocity.x = -m_velocity.x;
}
}
else if (sprite_com->m_rcSprite.x > SCREEN_WIDTH - SPRITE_W) {
sprite_com->m_rcSprite.x = SCREEN_WIDTH - SPRITE_W;
p_transformCom->m_position.x = static_cast<float>(sprite_com->m_rcSprite.x + SPRITE_W / 2);
if (m_velocity.x > 0.0)
{
m_velocity.x = -m_velocity.x;
}
}
if (sprite_com->m_rcSprite.y < 0) {
sprite_com->m_rcSprite.y = 0;
p_transformCom->m_position.y = static_cast<float>(sprite_com->m_rcSprite.y + SPRITE_H / 2);
if (m_velocity.y < 0.0)
{
m_velocity.y = -m_velocity.y;
}
}
else if (sprite_com->m_rcSprite.y > SCREEN_HEIGHT - SPRITE_H) {
sprite_com->m_rcSprite.y = SCREEN_HEIGHT - SPRITE_H;
p_transformCom->m_position.y = static_cast<float>(sprite_com->m_rcSprite.y + SPRITE_H / 2);
if (m_velocity.y > 0.0)
{
m_velocity.y = -m_velocity.y;
}
}
// Reset velocity
Vector2DSet(&p_transformCom->m_velocity, &m_velocity);
}
}
}
}
void My::Component::PackController::Serialize(std::wostream& wostream)
{
wostream << "[Component : PackController] ";
}
<file_sep>/GameEngine/Common/Component/Physics/Body.hpp
#pragma once
#include <mutex>
#include "Common/Geommath/2D/Math2D.hpp"
#include "Common/Component/Interface/IComponent.hpp"
#include "Common/Geommath/Shape/Shape.hpp"
#include "Common/ResourceManager.hpp"
namespace My
{
namespace Component
{
class Body : public IComponent
{
public:
Body() = delete;
explicit Body(void* owner, std::string name);
virtual ~Body();
virtual void Update(double deltaTime) override; // Trivial
virtual void PhysicsUpdate(double deltaTime);
virtual void Serialize(std::ifstream& fstream) override;
virtual void Serialize(std::wostream& wostream) override;
void Copy(const Body* body);
public:
std::mutex m_mutex;
Vector2D m_position;
Vector2D m_prev_position;
Vector2D m_velocity;
Vector2D m_acceleration;
Vector2D m_force;
/* angle in rad */
float m_angle;
/* Response to physical effect (gravity, reflection) or not */
bool b_simulated;
float m_Mass;
float m_InvMass;
Collision::Shape* m_shape;
};
}
class BodyCreator : public IComponentCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IComponent* Create(void* owner = nullptr, MemoryPool* pool = nullptr, std::string name = "Body0") override;
};
}<file_sep>/CS529_Game/src/Event/MyEvent.hpp
#pragma once
#include <vector>
#include "Common/Event/Event.hpp"
namespace My
{
namespace Events
{
class DeathEvent : public Event
{
public:
DeathEvent() = delete;
explicit DeathEvent(void* _self) : Event(EventType::ON_DEATH), other(_self) {};
public:
void* other;
};
class LockHPEvent : public Event
{
public:
LockHPEvent() : Event(EventType::ON_LOCKHP) {};
};
class UnLockHPEvent : public Event
{
public:
UnLockHPEvent() : Event(EventType::ON_UNLOCKHP) {};
};
class MouseClickEvent : public Event
{
public:
MouseClickEvent() = delete;
explicit MouseClickEvent(int _x, int _y) : Event(EventType::ON_MOUSECLICK), x(_x), y(_y) {};
public:
int x, y;
};
class MouseMotionEvent : public Event
{
public:
MouseMotionEvent() = delete;
explicit MouseMotionEvent(int _x, int _y) : Event(EventType::ON_MOUSEMOTION), x(_x), y(_y) {};
public:
int x, y;
};
class AISwitchFireModeEvent : public Event
{
public:
AISwitchFireModeEvent() = delete;
explicit AISwitchFireModeEvent(int _mode) : Event(EventType::ON_TELEPORT), mode(_mode) {};
public:
int mode;
};
}
}<file_sep>/CS529_Game/src/Entity/Gameplay/Pack/Pack_HP.hpp
#pragma once
#include "src/Entity/Gameplay/Interface/IMyGameObject.hpp"
#include "src/Event/MyEvent.hpp"
namespace My
{
namespace Entity
{
class Pack_HP : public IMyGameObject
{
public:
Pack_HP() = delete;
explicit Pack_HP(void* owner, std::string name) noexcept
:
IMyGameObject(MYGAMEOBJECT_TYPE::Item_HP, owner, name),
life_time(PACK_LIFETIME)
{
m_eventManager.AddEventRegistry(EventType::ON_COMPONENTHIT);
}
virtual int Tick(double deltaTime) override;
virtual int Draw() override;
virtual void HandleEvent(std::weak_ptr<Event> e)
{
if (IsActive())
{
std::shared_ptr<Event> _e = e.lock();
switch (_e->GetType())
{
case EventType::ON_COMPONENTHIT:
OnComponentHit(_e);
break;
default:
break;
}
}
}
void OnComponentHit(std::weak_ptr<Event> e);
private:
double life_time;
};
}
class Pack_HPObjectCreator : public IMyGameObjectCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IMyGameObject* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "Pack_HP0") override
{
if (pool)
{
return pool->New<Entity::Pack_HP>(owner, name);
}
else
{
return new Entity::Pack_HP(owner, name);
}
}
};
}<file_sep>/CS529_Game/Main.hpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: Main
Purpose: header file of Main
Language: c++ 11
Platform: win32 x86
Project: CS529_project_final
Author: <NAME> hang.yu 60001119
Creation date: 10/17/2019
- End Header ----------------------------*/
#pragma once
#include "stdio.h"
FILE _iob[] = { *stdin, *stdout, *stderr };
extern "C" FILE* __cdecl __iob_func(void)
{
return _iob;
}
#pragma comment(lib, "legacy_stdio_definitions.lib")
#include "src/GameApplication.hpp"
namespace My
{
extern MY_CALL_BACK Initialize();
extern MY_CALL_BACK GameLoop();
extern MY_CALL_BACK Finalize();
}<file_sep>/GameEngine/Common/Interface/IRunTimeModule.hpp
#pragma once
#include <functional>
#include <vector>
#include <memory>
#include "Common/Utility/EngineException.hpp"
namespace My
{
class IRunTimeModule
{
public:
virtual int Initialize() = 0;
virtual int Tick(double deltaTime) { for (auto& func : m_callbacks) { func(deltaTime); }; return 0; };
virtual int Finalize() = 0;
virtual void Serialize(std::wostream& wostream) {};
void AddCallBackToTick(std::function<void(double)> func) { m_callbacks.push_back(func); };
void ClearCallBackToTick() { m_callbacks.clear(); };
private:
std::vector<std::function<void(double)>> m_callbacks;
};
}<file_sep>/GameEngine/Common/Event/Event.hpp
#pragma once
#include <vector>
#include <memory>
#include "EventType.h"
namespace My {
class Event
{
public:
Event() = delete;
explicit Event(EventType type);
virtual ~Event();
virtual void Serialize(std::wostream& wostream);
EventType GetType();
void AddSubscriber(void* sub);
std::vector<void*>& GetSubscriber();
private:
EventType m_type;
std::vector<void*> subs;
};
namespace Events
{
class ComponentHitEvent : public Event
{
public:
ComponentHitEvent() = delete;
explicit ComponentHitEvent(void* _other) : Event(EventType::ON_COMPONENTHIT), other(_other) {};
public:
void* other;
};
class TeleportEvent : public Event
{
public:
TeleportEvent() : Event(EventType::ON_TELEPORT) {};
};
class SetVelocityEvent : public Event
{
public:
SetVelocityEvent() = delete;
explicit SetVelocityEvent(float vx, float vy) : Event(EventType::ON_SET_VELOCITY),vx(vx),vy(vy) {};
public:
float vx;
float vy;
};
}
}<file_sep>/CS529_Game/src/SerializedLoader.hpp
#pragma once
#include "Common/GfxConfiguration.hpp"
#include "Common/ResourceManager.hpp"
#include "Common/Entity/GameObjectResourceManager.hpp"
#include "Common/Component/Physics/BodyResourceManager.hpp"
#include "Common/Event/EventDispatcher.hpp"
#include "Common/BaseApplication.hpp"
#include "Common/Utility/Utility.hpp"
#include "src/Entity/Gameplay/Interface/IMyGameObject.hpp"
namespace My
{
// TODO : Initialize in your application
/* This map is used to assign game object with a call back function (e.g. execute callback on a button's OnClick event)*/
extern std::map<std::string, std::map<std::string, std::function<void(void)>>> g_globalCallBackSerializationMap;
extern std::map<std::string, std::ifstream> g_gameObjectConfigurationIfstreamMap;
/**
Comment :
Serialization of level config.
Sample game object configuration file level1.txt:
[Screen_width 800 ]
[Screen_height 600 ]
[MAX_FPS 60 ]
*/
IMyGameObject* LoadIGameObjectFromFile(const char* file_path, std::string name);
/**
Comment :
Serialization of game object.
Sample game object configuration file Player.txt:
#Player // Object type -> initiate object creator
[Transform // Component Transform
p (0,0) v (0,0) a (0,0) // initiate component creator
]
[Sprite // Component Sprite
~Player.bmp // initiate component creator
]
[PlayerController // Component PlayerController
]
[SceneComponet // Component scene (This makes the object visible in the scene)
]
*/
int LoadLevelConfigFromFile(const char* file_path, GfxConfiguration& config);
/**
Comment :
Sample game object configuration file level1.txt:
#./Resource/Configuration/Background.txt Back
[Transform
p(0, 0) v(-200, 0) a(0, 0) // One more comment
]
// This is a comment : Create a player object with name "Player"
#./Resource/Configuration/Player.txt Player // This is a comment, too
[Transform
p(100, 100) v(0, 0) a(0,0)
]
// This is the third comment : Create a UFO object with name "Enemy1"
#./Resource/Configuration/UFO.txt Enemy1
[Transform
p(300, 100) v(0, 0) a(0, 0) // One more comment
]
#./Resource/Configuration/UFO.txt Enemy2
[Transform
p(400, 500) v(0, 0) a(0, 0) // One more comment
]
#./Resource/Configuration/UFO.txt Enemy3
[Transform
p(100, 400) v(0, 0) a(0, 0) // One more comment
]
*/
int LoadLevelObjectFromFile(const char* file_path);
}<file_sep>/CS529_Game/src/Entity/Gameplay/UI/Button.cpp
#include <SDL_mixer.h>
#include "Button.hpp"
#include "src/Event/MyEvent.hpp"
#include "src/Component/Graphics/Sprite.hpp"
#include "Common/Utility/Utility.hpp"
int My::Entity::UI_Button::Draw()
{
if (auto sceneCom = m_componentManager.GetComponent(COMPONENT_TYPE::SCENECOMPONENT))
{
static_cast<Component::SceneComponent*>(sceneCom)->Draw();
}
return 0;
}
void My::Entity::UI_Button::OnClick(std::weak_ptr<Event> e)
{
auto temp_sprite = m_componentManager.GetComponent(COMPONENT_TYPE::SPRITE);
std::shared_ptr<Event> _e = e.lock();
auto event = static_cast<Events::MouseClickEvent*>(_e.get());
if (temp_sprite && event)
{
auto p_spriteCom = static_cast<Component::Sprite*>(temp_sprite);
if (IN_RANGE(event->x, p_spriteCom->m_rcSprite.x, p_spriteCom->m_rcSprite.x + p_spriteCom->m_rcSprite.w) &&
IN_RANGE(event->y, p_spriteCom->m_rcSprite.y, p_spriteCom->m_rcSprite.y + p_spriteCom->m_rcSprite.h))
{
DEBUG_PRINT(Str(event->x) + ", " + Str(event->y) + " " + m_name + " button is clicked... ");
if (m_callBacks["OnClick"])
{
m_callBacks["OnClick"]();
DEBUG_PRINT("And a callback is executed.\n");
}
else
{
DEBUG_PRINT("But there is no callback to execute.\n");
}
}
}
}
void My::Entity::UI_Button::OnHover(std::weak_ptr<Event> e)
{
auto temp_sprite = m_componentManager.GetComponent(COMPONENT_TYPE::SPRITE);
std::shared_ptr<Event> _e = e.lock();
auto event = static_cast<Events::MouseMotionEvent*>(_e.get());
if (temp_sprite && event)
{
auto p_spriteCom = static_cast<Component::Sprite*>(temp_sprite);
if (IN_RANGE(event->x, p_spriteCom->m_rcSprite.x, p_spriteCom->m_rcSprite.x + p_spriteCom->m_rcSprite.w) &&
IN_RANGE(event->y, p_spriteCom->m_rcSprite.y, p_spriteCom->m_rcSprite.y + p_spriteCom->m_rcSprite.h))
{
p_spriteCom->SetCurrentSpriteByName("Hover");
}
else
{
p_spriteCom->SetCurrentSpriteByName("Default");
}
}
}
void My::Entity::UI_Button::SetIsShown(bool v)
{
b_isShown = v;
}
bool My::Entity::UI_Button::GetIsShown()
{
return b_isShown;
}
int My::Entity::UI_Volume_Button::mode = 0;
int My::Entity::UI_Volume_Button::Tick(double deltaTime)
{
auto temp_sprite = m_componentManager.GetComponent(COMPONENT_TYPE::SPRITE);
auto p_spriteCom = static_cast<Component::Sprite*>(temp_sprite);
switch (mode)
{
case 0:
p_spriteCom->SetCurrentSpriteByName("On");
break;
case 1:
p_spriteCom->SetCurrentSpriteByName("Reduce");
break;
case 2:
p_spriteCom->SetCurrentSpriteByName("Off");
break;
default:
break;
}
IMyGameObject::Tick(deltaTime);
return 0;
}
int My::Entity::UI_Volume_Button::Draw()
{
if (auto sceneCom = m_componentManager.GetComponent(COMPONENT_TYPE::SCENECOMPONENT))
{
static_cast<Component::SceneComponent*>(sceneCom)->Draw();
}
return 0;
}
void My::Entity::UI_Volume_Button::OnClick(std::weak_ptr<Event> e)
{
auto temp_sprite = m_componentManager.GetComponent(COMPONENT_TYPE::SPRITE);
std::shared_ptr<Event> _e = e.lock();
auto event = static_cast<Events::MouseClickEvent*>(_e.get());
if (temp_sprite && event)
{
auto p_spriteCom = static_cast<Component::Sprite*>(temp_sprite);
if (IN_RANGE(event->x, p_spriteCom->m_rcSprite.x, p_spriteCom->m_rcSprite.x + p_spriteCom->m_rcSprite.w) &&
IN_RANGE(event->y, p_spriteCom->m_rcSprite.y, p_spriteCom->m_rcSprite.y + p_spriteCom->m_rcSprite.h))
{
DEBUG_PRINT(Str(event->x) + ", " + Str(event->y) + " " + m_name + " button is clicked... ");
if (++mode > 2)
{
mode = 0;
}
switch (mode)
{
case 0:
p_spriteCom->SetCurrentSpriteByName("On");
Mix_VolumeMusic(MIX_MAX_VOLUME);
Mix_Volume(-1, MIX_MAX_VOLUME);
break;
case 1:
p_spriteCom->SetCurrentSpriteByName("Reduce");
Mix_VolumeMusic(MIX_MAX_VOLUME / 4);
Mix_Volume(-1, MIX_MAX_VOLUME / 4);
break;
case 2:
p_spriteCom->SetCurrentSpriteByName("Off");
Mix_VolumeMusic(0);
Mix_Volume(-1, 0);
break;
default:
break;
}
}
}
}
<file_sep>/CS529_Game/src/GameApplication.cpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: GameApplication.cpp
Purpose: implementation file of GameApplication
Language: c++ 11
Platform: win32 x86
Project: CS529_final_project
Author: <NAME> hang.yu 60001119
Creation date: 10/13/2019
- End Header ----------------------------*/
#include "GameApplication.hpp"
#include "src/Platform/Win32_SDL/WinSDLInputManager.hpp"
#include "src/Platform/Win32_SDL/WinSDLAudioManager.hpp"
#include "src/SerializedLoader.hpp"
#include "src/SceneManager.hpp"
#include "src/Event/MyEvent.hpp"
#include "src/Component/Graphics/Sprite.hpp"
#include "src/Component/Graphics/SceneComponent.hpp"
#include "src/Component/Logic/PlayerController.hpp"
#include "src/Component/Logic/AIController.hpp"
#include "src/Component/Logic/PackController.hpp"
#include "src/Component/Gameplay/HealthPoint.hpp"
#include "src/Component/Gameplay/WeaponarySystem.hpp"
#include "src/Entity/GamePlay/Interface/IMyGameObject.hpp"
#include "src/Entity/Gameplay/UI/Button.hpp"
#include "src/Entity/GamePlay/Objects/Player.hpp"
#include "src/Entity/GamePlay/Objects/UFO.hpp"
#include "src/Entity/GamePlay/Objects/Background.hpp"
#include "src/Entity/GamePlay/Pack/Pack_HP.hpp"
#include "src/Entity/GamePlay/Pack/Pack_Shield.hpp"
#include "src/Entity/GamePlay/Pack/Pack_Upgrade.hpp"
#include "src/Entity/Gameplay/Weapon/Lazer.hpp"
#include "src/Entity/Gameplay/Weapon/LazerBeam.hpp"
#include "src/Entity/Gameplay/Weapon/KineticGun.hpp"
#include "src/Entity/Gameplay/Weapon/KineticGunBullet.hpp"
#include "src/Entity/Gameplay/Weapon/KineticGunExplosion.hpp"
#include "src/Entity/Gameplay/Weapon/Missile.hpp"
#include "src/Entity/Gameplay/Weapon/MissileBullet.hpp"
#include "src/Entity/Gameplay/Weapon/MissileExplosion.hpp"
#include "src/Entity/Gameplay/Weapon/UFOBullet.hpp"
#define RegisterSerialization(map, key, value) map[key] = value
#define RegisterCreator(map, key, value) map[key] = std::make_shared<value>()
using namespace My;
/*
Variable Initializer.
*/
namespace My
{
// Initialize Maps
// Game object serialization
std::map<std::string, GAMEOBJECT_TYPE> g_gameObjectSerializationMap;
std::map<GAMEOBJECT_TYPE, std::shared_ptr<IGameObjectCreator>> g_gameObjectCreatorMap;
// My Game Object
std::map<std::string, MYGAMEOBJECT_TYPE> g_myGameObjectSerializationMap;
std::map<MYGAMEOBJECT_TYPE, std::shared_ptr<IMyGameObjectCreator>> g_myGameObjectCreatorMap;
// Shape(collision) object serialization
std::map<std::string, SHAPE_TYPE> g_shapeSerializationMap;
std::map<SHAPE_TYPE, std::shared_ptr<ShapeCreator>> g_shapeCreatorMap;
// Event object serialization
std::map<std::string, std::map<std::string, std::function<void(void)>>> g_globalCallBackSerializationMap;
std::map<std::string, std::ifstream> g_gameObjectConfigurationIfstreamMap;
// Component object serialization
std::map<std::string, COMPONENT_TYPE> g_componentSerializationMap;
std::map<COMPONENT_TYPE, std::shared_ptr<IComponentCreator>> g_componentCreatorMap;
// Weapon object serialization
std::map<std::string, WEAPON_TYPE> g_weaponSerializationMap;
std::map<WEAPON_TYPE, std::shared_ptr<IWeaponCreator>> g_weaponCreatorMap;
// Initialize scene configuration
std::shared_ptr<RootObject> g_pRootObject = std::make_shared<RootObject>();
std::shared_ptr<Scene> g_pScene = std::make_shared<Scene>();
std::shared_ptr<SceneManager> g_pSceneManager = std::make_shared<SceneManager>();
// Contains all Game object
std::shared_ptr<IGameObjectResourceManager> g_pGameObjectResourceManager = std::make_shared<IGameObjectResourceManager>();
// Manage all physics components
std::shared_ptr<BodyResourceManager> g_pBodyResourceManager = std::make_shared<BodyResourceManager>();
// Initialize global pointers
std::shared_ptr<InputManager> g_pInputManager = std::make_shared<WinSDLInputManager>();
std::shared_ptr<MemoryManager> g_pMemoryManager = std::make_shared<MemoryManager>();
std::shared_ptr<EventDispatcher> g_pEventDispatcher = std::make_shared<EventDispatcher>();
std::shared_ptr<WinSDLAudioManager> g_pAudioManager = std::make_shared<WinSDLAudioManager>();
// Initialize application
std::shared_ptr<BaseApplication> g_pBaseApplication = std::make_shared<GameApplication>(g_pScene->m_config);
std::shared_ptr<GameApplication> g_pApp = std::static_pointer_cast<GameApplication>(g_pBaseApplication);
}
MY_CALL_BACK LoadVictory0()
{
// Loading game object by serialization
g_pSceneManager->m_queueLevelConfigPath = "Victory0";
g_pAudioManager->m_queuechunckPath = "Victory0";
g_pAudioManager->StopMusic();
}
MY_CALL_BACK LoadDefeat0()
{
// Loading game object by serialization
g_pSceneManager->m_queueLevelConfigPath = "Defeat0";
g_pAudioManager->m_queuechunckPath = "Defeat0";
g_pAudioManager->StopMusic();
}
MY_CALL_BACK LoadLevel1()
{
// Loading game object by serialization
g_pSceneManager->m_queueLevelConfigPath = "Level1";
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave1";
g_pAudioManager->m_queueMusicPath = "Level1";
}
MY_CALL_BACK LoadMenu0()
{
g_pSceneManager->m_queueLevelConfigPath = "Menu0";
g_pAudioManager->m_queueMusicPath = "Menu0";
}
MY_CALL_BACK QuitApplication()
{
BaseApplication::SetQuit(true);
}
MY_CALL_BACK LoadMenuGuide0()
{
g_pSceneManager->m_queueLevelConfigPath = "MenuGuide0";
}
MY_CALL_BACK ReturnToMenu0_1()
{
g_pSceneManager->m_queueLevelConfigPath = "Menu0";
}
MY_CALL_BACK Resume()
{
BaseApplication::TogglePause();
}
MY_CALL_BACK RestartFromPause()
{
LoadLevel1();
BaseApplication::TogglePause();
}
MY_CALL_BACK RestartLevel1()
{
LoadLevel1();
}
MY_CALL_BACK ReturnToMenu0FromPause()
{
LoadMenu0();
BaseApplication::TogglePause();
}
MY_CALL_BACK ReturnToMenu0()
{
LoadMenu0();
}
/*
Callback Initializer
*/
namespace My
{
MY_CALL_BACK CreatorInitialization()
{
{
// Level
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1", std::ifstream("./Resource/Level/Level1.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Menu0", std::ifstream("./Resource/Level/Menu0.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "MenuGuide0", std::ifstream("./Resource/Level/MenuGuide0.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Victory0", std::ifstream("./Resource/Level/Victory0.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Defeat0", std::ifstream("./Resource/Level/Defeat0.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave1", std::ifstream("./Resource/Level/Level1_Wave1.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave2", std::ifstream("./Resource/Level/Level1_Wave2.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave3", std::ifstream("./Resource/Level/Level1_Wave3.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave4", std::ifstream("./Resource/Level/Level1_Wave4.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave5", std::ifstream("./Resource/Level/Level1_Wave5.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave6", std::ifstream("./Resource/Level/Level1_Wave6.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave7", std::ifstream("./Resource/Level/Level1_Wave7.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave8", std::ifstream("./Resource/Level/Level1_Wave8.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave9", std::ifstream("./Resource/Level/Level1_Wave9.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave10", std::ifstream("./Resource/Level/Level1_Wave10.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Level1_Wave11", std::ifstream("./Resource/Level/Level1_Wave11.txt"));
// Audio
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "AudioList", std::ifstream("./Resource/Configuration/Audio/AudioList.txt"));
// Game objects
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Background", std::ifstream("./Resource/Configuration/Object/Background.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Player", std::ifstream("./Resource/Configuration/Object/Player.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "UFO", std::ifstream("./Resource/Configuration/Object/UFO.txt"));
// UI
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "UI_Button", std::ifstream("./Resource/Configuration/UI/UI_Button.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "UI_Volume_Button", std::ifstream("./Resource/Configuration/UI/UI_Volume_Button.txt"));
// Pack
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Pack_HP", std::ifstream("./Resource/Configuration/Pack/Pack_HP.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Pack_Shield", std::ifstream("./Resource/Configuration/Pack/Pack_Shield.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Pack_Upgrade", std::ifstream("./Resource/Configuration/Pack/Pack_Upgrade.txt"));
// Weapons
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Lazer", std::ifstream("./Resource/Configuration/Weapon/Lazer.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "LazerBeam", std::ifstream("./Resource/Configuration/Weapon/LazerBeam.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "KineticGun", std::ifstream("./Resource/Configuration/Weapon/KineticGun.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "KineticGunBullet", std::ifstream("./Resource/Configuration/Weapon/KineticGunBullet.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "KineticGunExplosion", std::ifstream("./Resource/Configuration/Weapon/KineticGunExplosion.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "Missile", std::ifstream("./Resource/Configuration/Weapon/Missile.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "MissileBullet", std::ifstream("./Resource/Configuration/Weapon/MissileBullet.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "MissileExplosion", std::ifstream("./Resource/Configuration/Weapon/MissileExplosion.txt"));
RegisterSerialization(g_gameObjectConfigurationIfstreamMap, "UFOBullet", std::ifstream("./Resource/Configuration/Weapon/UFOBullet.txt"));
}
{
std::map<std::string, std::function<void(void)>> Player;
Player["Defeat"] = &LoadDefeat0;
Player["Victory"] = &LoadVictory0;
RegisterSerialization(g_globalCallBackSerializationMap, "002_Player", Player);
// Main Menu
std::map<std::string, std::function<void(void)>> UI_Start_Button;
UI_Start_Button["OnClick"] = &LoadLevel1;
RegisterSerialization(g_globalCallBackSerializationMap, "UI_Start_Button", UI_Start_Button);
std::map<std::string, std::function<void(void)>> UI_Quit_Button;
UI_Quit_Button["OnClick"] = &QuitApplication;
RegisterSerialization(g_globalCallBackSerializationMap, "UI_Quit_Button", UI_Quit_Button);
std::map<std::string, std::function<void(void)>> UI_GameGuide_Button;
UI_GameGuide_Button["OnClick"] = &LoadMenuGuide0;
RegisterSerialization(g_globalCallBackSerializationMap, "UI_GameGuide_Button", UI_GameGuide_Button);
// Game Guide Menu
std::map<std::string, std::function<void(void)>> UI_Guide_MainMenu_Button;
UI_Guide_MainMenu_Button["OnClick"] = &ReturnToMenu0_1;
RegisterSerialization(g_globalCallBackSerializationMap, "UI_Guide_MainMenu_Button", UI_Guide_MainMenu_Button);
// Victory/Defeat Menu
std::map<std::string, std::function<void(void)>> UI_MainMenu_Button;
UI_MainMenu_Button["OnClick"] = &ReturnToMenu0;
RegisterSerialization(g_globalCallBackSerializationMap, "UI_MainMenu_Button", UI_MainMenu_Button);
std::map<std::string, std::function<void(void)>> UI_Restart_Button;
UI_Restart_Button["OnClick"] = &RestartLevel1;
RegisterSerialization(g_globalCallBackSerializationMap, "UI_Restart_Button", UI_Restart_Button);
// In Game Pause Menu
std::map<std::string, std::function<void(void)>> UI_PauseMenu_MainMenu_Button;
UI_PauseMenu_MainMenu_Button["OnClick"] = &ReturnToMenu0FromPause;
RegisterSerialization(g_globalCallBackSerializationMap, "UI_PauseMenu_MainMenu_Button", UI_PauseMenu_MainMenu_Button);
std::map<std::string, std::function<void(void)>> UI_PauseMenu_Resume_Button;
UI_PauseMenu_Resume_Button["OnClick"] = &Resume;
RegisterSerialization(g_globalCallBackSerializationMap, "UI_PauseMenu_Resume_Button", UI_PauseMenu_Resume_Button);
std::map<std::string, std::function<void(void)>> UI_PauseMenu_Restart_Button;
UI_PauseMenu_Restart_Button["OnClick"] = &RestartFromPause;
RegisterSerialization(g_globalCallBackSerializationMap, "UI_PauseMenu_Restart_Button", UI_PauseMenu_Restart_Button);
}
{
// Game Objects
RegisterSerialization(g_myGameObjectSerializationMap, "UI_Button", MYGAMEOBJECT_TYPE::UI_Button);
RegisterSerialization(g_myGameObjectSerializationMap, "UI_Volume_Button", MYGAMEOBJECT_TYPE::UI_Volume_Button);
RegisterSerialization(g_myGameObjectSerializationMap, "Player", MYGAMEOBJECT_TYPE::PLAYER);
RegisterSerialization(g_myGameObjectSerializationMap, "UFO", MYGAMEOBJECT_TYPE::UFO);
RegisterSerialization(g_myGameObjectSerializationMap, "Background", MYGAMEOBJECT_TYPE::BACKGROUND);
RegisterSerialization(g_myGameObjectSerializationMap, "Pack_HP", MYGAMEOBJECT_TYPE::Item_HP);
RegisterSerialization(g_myGameObjectSerializationMap, "Pack_Shield", MYGAMEOBJECT_TYPE::Item_SHIELD);
RegisterSerialization(g_myGameObjectSerializationMap, "Pack_Upgrade", MYGAMEOBJECT_TYPE::Item_UPGRADE);
RegisterCreator(g_myGameObjectCreatorMap, MYGAMEOBJECT_TYPE::UI_Button, UI_ButtonObjectCreator);
RegisterCreator(g_myGameObjectCreatorMap, MYGAMEOBJECT_TYPE::UI_Volume_Button, UI_Volume_ButtonObjectCreator);
RegisterCreator(g_myGameObjectCreatorMap, MYGAMEOBJECT_TYPE::PLAYER, PlayerObjectCreator);
RegisterCreator(g_myGameObjectCreatorMap, MYGAMEOBJECT_TYPE::UFO, UFOObjectCreator);
RegisterCreator(g_myGameObjectCreatorMap, MYGAMEOBJECT_TYPE::BACKGROUND, BackgroundObjectCreator);
RegisterCreator(g_myGameObjectCreatorMap, MYGAMEOBJECT_TYPE::Item_HP, Pack_HPObjectCreator);
RegisterCreator(g_myGameObjectCreatorMap, MYGAMEOBJECT_TYPE::Item_SHIELD, Pack_ShieldObjectCreator);
RegisterCreator(g_myGameObjectCreatorMap, MYGAMEOBJECT_TYPE::Item_UPGRADE, Pack_UpgradeObjectCreator);
// Weapons
RegisterSerialization(g_weaponSerializationMap, "Lazer", WEAPON_TYPE::WEAPON_LAZER);
RegisterSerialization(g_weaponSerializationMap, "LazerBeam", WEAPON_TYPE::WEAPON_LAZER_BEAM);
RegisterSerialization(g_weaponSerializationMap, "Missile", WEAPON_TYPE::WEAPON_MISSILE);
RegisterSerialization(g_weaponSerializationMap, "MissileBullet", WEAPON_TYPE::WEAPON_MISSILE_BULLET);
RegisterSerialization(g_weaponSerializationMap, "MissileExplosion", WEAPON_TYPE::WEAPON_MISSILE_EXPLOSION);
RegisterSerialization(g_weaponSerializationMap, "KineticGun", WEAPON_TYPE::WEAPON_KINETICGUN);
RegisterSerialization(g_weaponSerializationMap, "KineticGunBullet", WEAPON_TYPE::WEAPON_KINETICGUN_BULLET);
RegisterSerialization(g_weaponSerializationMap, "KineticGunExplosion", WEAPON_TYPE::WEAPON_KINETICGUN_EXPLOSION);
RegisterSerialization(g_weaponSerializationMap, "UFOBullet", WEAPON_TYPE::UFO_BULLET);
RegisterCreator(g_weaponCreatorMap, WEAPON_TYPE::WEAPON_LAZER, LazerObjectCreator);
RegisterCreator(g_weaponCreatorMap, WEAPON_TYPE::WEAPON_LAZER_BEAM, LazerBeamObjectCreator);
RegisterCreator(g_weaponCreatorMap, WEAPON_TYPE::WEAPON_MISSILE, MissleObjectCreator);
RegisterCreator(g_weaponCreatorMap, WEAPON_TYPE::WEAPON_MISSILE_BULLET, MissleBulletObjectCreator);
RegisterCreator(g_weaponCreatorMap, WEAPON_TYPE::WEAPON_MISSILE_EXPLOSION, MissileExplosionObjectCreator);
RegisterCreator(g_weaponCreatorMap, WEAPON_TYPE::WEAPON_KINETICGUN, KineticGunObjectCreator);
RegisterCreator(g_weaponCreatorMap, WEAPON_TYPE::WEAPON_KINETICGUN_BULLET, KineticGunBulletObjectCreator);
RegisterCreator(g_weaponCreatorMap, WEAPON_TYPE::WEAPON_KINETICGUN_EXPLOSION, KineticGunExplosionObjectCreator);
RegisterCreator(g_weaponCreatorMap, WEAPON_TYPE::UFO_BULLET, UFOBulletObjectCreator);
}
{
// Shape
RegisterSerialization(g_shapeSerializationMap, "Circle", SHAPE_TYPE::CIRCLE);
RegisterSerialization(g_shapeSerializationMap, "Rectangle", SHAPE_TYPE::RECTANGLE);
RegisterCreator(g_shapeCreatorMap, SHAPE_TYPE::CIRCLE, CircleCreator);
RegisterCreator(g_shapeCreatorMap, SHAPE_TYPE::RECTANGLE, RectangleCreator);
}
{
// Component
RegisterSerialization(g_componentSerializationMap, "Sprite", COMPONENT_TYPE::SPRITE);
RegisterSerialization(g_componentSerializationMap, "SceneComponent", COMPONENT_TYPE::SCENECOMPONENT);
RegisterSerialization(g_componentSerializationMap, "Transform", COMPONENT_TYPE::TRANSFORM);
RegisterSerialization(g_componentSerializationMap, "Body", COMPONENT_TYPE::BODY);
RegisterSerialization(g_componentSerializationMap, "PlayerController", COMPONENT_TYPE::PLAYERCONTROLLER);
RegisterSerialization(g_componentSerializationMap, "AIController", COMPONENT_TYPE::AICONTROLLER);
RegisterSerialization(g_componentSerializationMap, "PackController", COMPONENT_TYPE::PACKCONTROLLER);
RegisterSerialization(g_componentSerializationMap, "HealthPoint", COMPONENT_TYPE::HEALTHPOINT);
RegisterSerialization(g_componentSerializationMap, "WeaponarySystem", COMPONENT_TYPE::WEAPONARYSYSTEM);
RegisterCreator(g_componentCreatorMap, COMPONENT_TYPE::SPRITE, SpriteCreator);
RegisterCreator(g_componentCreatorMap, COMPONENT_TYPE::SCENECOMPONENT, SceneComponentCreator);
RegisterCreator(g_componentCreatorMap, COMPONENT_TYPE::BODY, BodyCreator);
RegisterCreator(g_componentCreatorMap, COMPONENT_TYPE::PLAYERCONTROLLER, PlayerControllerCreator);
RegisterCreator(g_componentCreatorMap, COMPONENT_TYPE::AICONTROLLER, AIControllerCreator);
RegisterCreator(g_componentCreatorMap, COMPONENT_TYPE::PACKCONTROLLER, PackControllerCreator);
RegisterCreator(g_componentCreatorMap, COMPONENT_TYPE::HEALTHPOINT, HealthPointCreator);
RegisterCreator(g_componentCreatorMap, COMPONENT_TYPE::WEAPONARYSYSTEM, WeaponarySystemCreator);
}
}
MY_CALL_BACK PrintPerSecond()
{
static Timer printTimer;
static int m_nbFrames = 0;
m_nbFrames++;
if (printTimer.Mark() >= 1.0)
{
// Print all objects
// g_pRootObject->Serialize(std::wcout);
PRINT(Str(1000.0 / m_nbFrames) + " ms/frame\n");
m_nbFrames = 0;
printTimer.Reset();
}
}
}
/*
Implementing
extern MY_CALL_BACK Initialize();
extern MY_CALL_BACK GameLoop();
extern MY_CALL_BACK Finalize();
*/
MY_CALL_BACK My::Initialize()
{
Run(
[] {
srand(time(0));
// Register all creators/factories
CreatorInitialization();
g_pSceneManager->Initialize();
g_pEventDispatcher->Initialize();
g_pBaseApplication->Initialize(); /* equivalient to g_pApp->Initialize() as they are base-derived classes */
g_pInputManager->Initialize();
g_pBodyResourceManager->Initialize();
g_pGameObjectResourceManager->Initialize();
g_pMemoryManager->Initialize();
// Must init after g_pBaseApplication init
g_pAudioManager->Initialize();
LoadMenu0();
}
);
}
MY_CALL_BACK My::GameLoop()
{
Run(
[] {
Timer drawTimer;
while (!BaseApplication::IsQuit())
{
// Reset timer
drawTimer.Reset();
{
// Must call first
BaseApplication::UpdateFrameTime(1.0 / g_pScene->m_config.maxfps);
}
// Managers update
{
// All Objects GC
g_pGameObjectResourceManager->GC();
// Process scene loading/unloading
g_pSceneManager->Tick(BaseApplication::frametime);
// Process audio loading/unloading
g_pAudioManager->Tick(BaseApplication::frametime);
// Process logical event in the game application tick
g_pBaseApplication->Tick(BaseApplication::frametime);
// Process input event
g_pInputManager->Tick(BaseApplication::frametime);
// Process physics (could run parallelly)
g_pBodyResourceManager->PhysicsUpdate(BaseApplication::frametime);
// Process collision (could run parallelly with physics)
g_pBodyResourceManager->CollisionUpdate(BaseApplication::frametime);
// Dispatch events
g_pEventDispatcher->Tick(BaseApplication::frametime);
// All Objects (events and components) update
g_pGameObjectResourceManager->Tick(BaseApplication::frametime);
}
// Graphics update
{
// Prepare drawing
g_pBaseApplication->BeginDraw();
// Application drawing
g_pBaseApplication->OnDraw();
// Draw all objects
g_pGameObjectResourceManager->DrawAll();
// End draw call
g_pBaseApplication->EndDraw();
}
// Print game loop debug
PrintPerSecond();
// Busy waiting
while (drawTimer.Mark() < BaseApplication::static_frametime)
{
};
}
PRINT("Exit!\n");
}
);
}
MY_CALL_BACK My::Finalize()
{
Run(
[] {
g_pAudioManager->Finalize();
g_pSceneManager->Finalize();
g_pEventDispatcher->Finalize();
g_pBodyResourceManager->Finalize();
g_pGameObjectResourceManager->Finalize();
g_pMemoryManager->Finalize();
g_pInputManager->Finalize();
g_pBaseApplication->Finalize();
}
);
}
<file_sep>/GameEngine/Common/MemoryPool.hpp
#pragma once
#include <new>
#include <vector>
#include "Common/Utility/EngineException.hpp"
namespace My
{
class MemoryPool
{
public:
// Replacement for new
template<class T, typename... Arguments>
T* New(Arguments... parameters)
{
return new (Allocate(sizeof(T))) T(parameters...);
}
public:
MemoryPool();
virtual ~MemoryPool();
void* Allocate(size_t size);
void Reset();
const std::vector<void*>& GetBookKeeper();
private:
void ResizePool(size_t scalar);
private:
uint8_t* m_pPoolHead;
uint8_t* m_pPoolTail;
size_t m_PoolSize;
size_t m_PoolMaxSize;
static const size_t kPageSize;
/* BookKeeps all the pointer to objects in the memory pool */
std::vector<void*> m_bookkeeper;
};
}<file_sep>/README.txt
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited.
File Name: README.txt
Purpose: Project Description
Language: C++ 11
Platform: Visual Studio 2017 Win32 x86/x64
Project: CS529 2019 Fall
Author: <NAME>, hang.yu, 60001119
Creation date: Dec.10.2019
- End Header --------------------------------------------------------*/
├───CS529_Game
│ ├───Resource
│ │ ├───Audio
│ │ ├───Configuration
│ │ │ ├───Audio
│ │ │ ├───Object
│ │ │ ├───Pack
│ │ │ ├───UI
│ │ │ └───Weapon
│ │ ├───Level
│ │ ├───Shader
│ │ └───Sprite
│ │ ├───Source
│ │ └───UI
│ ├───src
│ │ ├───Component
│ │ │ ├───Gameplay
│ │ │ ├───Graphics
│ │ │ └───Logic
│ │ ├───Entity
│ │ │ └───Gameplay
│ │ │ ├───Interface
│ │ │ ├───Objects
│ │ │ ├───Pack
│ │ │ ├───UI
│ │ │ └───Weapon
│ │ ├───Event
│ │ └───Platform
│ │ └───Win32_SDL
├───GameEngine
│ ├───Common
│ │ ├───Component
│ │ │ ├───Graphics
│ │ │ ├───Interface
│ │ │ ├───Logic
│ │ │ └───Physics
│ │ ├───Entity
│ │ ├───Event
│ │ ├───Geommath
│ │ │ ├───2D
│ │ │ └───Shape
│ │ ├───Interface
│ │ └───Utility
├───SDL2.0 Image
│ ├───include
│ └───lib
│ ├───x64
│ │ └───dll
│ └───x86
│ └───dll
├───SDL2.0 Lib
│ ├───include
│ └───lib
│ ├───x64
│ │ └───dll
│ └───x86
│ └───dll
├───SDL2.0 Mixer
│ ├───include
│ └───lib
│ ├───x64
│ │ └───dll
│ └───x86
│ └───dll
└───Test_GameEngine
1. In this project, I have made a game of 2D Vertical Scroll Shooter.
You play as a Space Ranger to defeat waves of enemy forces including one BOSS fight which has multiple attack mode.
You are equiped with our best gears, totaling one lazer gun, one kinetic coil gun and automatic missiles.
Executables are avaiable in "./CS529_Game/Win32" and "./CS529_Game/x64".
Arrow keys to maneuver.
"A" "D" to switch weapon.
"Z" "X" to switch weapon.
"Shift" to slow down your ship.
Pilot guide is avaiable in the "How To Play" menu in the game.
"./Resouce" under "./CS529_Game" contains all the serialization files for game objects and levels.
├───CS529_Game
│ ├───Resource
│ │ ├───Audio
│ │ ├───Configuration
│ │ │ ├───Audio
│ │ │ ├───Object
│ │ │ ├───Pack
│ │ │ ├───UI
│ │ │ └───Weapon
│ │ ├───Level
│ │ ├───Shader
│ │ └───Sprite
│ │ ├───Source
│ │ └───UI
The BOSS setting is avaiable in "./CS529_Game/Resource/Level/Level1_Wave7.txt". You can modify its healthpoint component change the total HP of the BOSS.
2. User interface
(1)
The main menu contains:
"New Game"
"How To Play"
"Quit"
and a music volume icon on the top right corner.
(2)
In game menu:
Press "ESC" to toggle pause in the game.
3. Known Bugs:
(1) Switching weapons rapidly (pressing "A","S" repeatedly) may cause crash.
(2) I wrote test for my custom memory allocator in the "Test_GameEngine" project. But tests were not discovered by VS when I finished the project. (Does not affect gameplay)
4. Credit:
(1)
Sound:
Blast.wav http://soundbible.com/538-Blast.html
Komiku_-_64_-_First_Dance https://files.freemusicarchive.org/storage-freemusicarchive-org/music/Music_for_Video/Komiku/Poupis_incredible_adventures_/Komiku_-_64_-_First_Dance.mp3
Komiku_-_58_-_Universe_big_takedown https://files.freemusicarchive.org/storage-freemusicarchive-org/music/Music_for_Video/Komiku/Poupis_incredible_adventures_/Komiku_-_58_-_Universe_big_takedown.mp3
Komiku_-_07_-_Battle_of_Pogs https://files.freemusicarchive.org/storage-freemusicarchive-org/music/Music_for_Video/Komiku/Poupis_incredible_adventures_/Komiku_-_07_-_Battle_of_Pogs.mp3
Monplaisir_-_05_-_Level_2 https://files.freemusicarchive.org/storage-freemusicarchive-org/music/WFMU/Monplaisir/Turbo_Rallye_Clicker_4000_Soundtrack/Monplaisir_-_05_-_Level_2.mp3
Defeat https://files.freemusicarchive.org/storage-freemusicarchive-org/music/WFMU/Monplaisir/Turbo_Rallye_Clicker_4000_Soundtrack/Monplaisir_-_09_-_Defeat.mp3
Victory https://files.freemusicarchive.org/storage-freemusicarchive-org/music/WFMU/Monplaisir/Turbo_Rallye_Clicker_4000_Soundtrack/Monplaisir_-_08_-_Victory.mp3
雷霆战机BGM http://sc.chinaz.com/tag_yinxiao/LeiZuoZhanJi.html
(2) Sprite:
https://fontmeme.com/pixel-fonts/
https://onlinepngtools.com/create-transparent-png
<file_sep>/GameEngine/Common/Event/EventManager.cpp
#include "EventManager.hpp"
#include "Common/Entity/IGameObject.hpp"
My::EventManager::EventManager() noexcept
:
m_owner(nullptr)
{
}
int My::EventManager::Initialize()
{
return 0;
}
int My::EventManager::Tick(double deltaTime)
{
while (!m_eventsQueue.empty())
{
auto e = m_eventsQueue.front();
// Event type is registered
#if USE_EventRegistry
if (m_eventsRegistry.find(e->GetType()) != m_eventsRegistry.end() && m_eventsRegistry[e->GetType()])
{
reinterpret_cast<IGameObject*>(m_owner)->HandleEvent(e);
}
#else
reinterpret_cast<IGameObject*>(m_owner)->HandleEvent(e);
#endif
m_eventsQueue.pop();
}
return 0;
}
int My::EventManager::Finalize()
{
return 0;
}
void My::EventManager::Serialize(std::wostream& wostream)
{
auto tmp_q(m_eventsQueue); //copy the original queue to the temporary queue
while (!tmp_q.empty())
{
auto q_element = tmp_q.front();
q_element->Serialize(wostream);
tmp_q.pop();
}
}
void My::EventManager::AddEventRegistry(EventType type)
{
m_eventsRegistry[type] = true;
}
void My::EventManager::AddEvent(std::weak_ptr<Event> e)
{
std::shared_ptr<Event> _e = e.lock();
m_eventsQueue.push(_e);
}
void* My::EventManager::GetOwner() noexcept
{
return m_owner;
}
void My::EventManager::SetOwner(void* owner) noexcept
{
m_owner = owner;
}
<file_sep>/CS529_Game/src/Entity/Gameplay/Interface/IMyGameObject.hpp
#pragma once
#include "MyObjectType.hpp"
#include "Common/Entity/IGameObject.hpp"
#include "Common/Component/ComponentManager.hpp"
#include "Common/MemoryManager.hpp"
#include "Common/Event/EventManager.hpp"
#include "src/Component/Graphics/Sprite.hpp"
#include "src/Component/Graphics/SceneComponent.hpp"
namespace My
{
/**
Comment :
To create a custom weapon
1. Add a new element to the enum type in the weapon type header
2. Create a derived class which inherits from IMyGameObject
3. Create a derived class which inherits from IMyGameObjectCreator
4. RegisterSerialization (g_weaponSerializationMap) in your initializer
5. RegisterCreator (g_weaponCreatorMap) in your initializer
*/
class IMyGameObject : public IGameObject
{
public:
IMyGameObject(const IMyGameObject&) = delete;
IMyGameObject& operator=(const IMyGameObject&) = delete;
explicit IMyGameObject(MYGAMEOBJECT_TYPE type, void* owner, std::string name) noexcept;
MYGAMEOBJECT_TYPE GetType() const noexcept;
protected:
MYGAMEOBJECT_TYPE m_type;
};
class IMyGameObjectCreator
{
public:
/* owner = g_pRootObject.get(), pool = g_pMemoryManager.get() */
virtual IMyGameObject* Create(void* owner, MemoryManager* pool, std::string name) = 0;
};
// TODO : Initialize in your application
extern std::map<std::string, MYGAMEOBJECT_TYPE> g_myGameObjectSerializationMap;
extern std::map<MYGAMEOBJECT_TYPE, std::shared_ptr<IMyGameObjectCreator>> g_myGameObjectCreatorMap;
}<file_sep>/CS529_Game/src/SceneManager.cpp
#include "SceneManager.hpp"
#include "Common/Event/EventDispatcher.hpp"
void My::Scene::Load(const char* level_file_path)
{
if (g_pRootObject) g_pRootObject.reset();
g_pRootObject = std::make_shared<RootObject>();
LoadLevelConfigFromFile(level_file_path, m_config);
LoadLevelObjectFromFile(level_file_path);
}
void My::Scene::Unload()
{
if (g_pRootObject) g_pRootObject.reset();
g_pGameObjectResourceManager->Clear();
g_pBodyResourceManager->Clear();
g_pEventDispatcher->Clear();
}
void My::Scene::LoadWave(const char* level_file_path)
{
LoadLevelObjectFromFile(level_file_path);
}
My::SceneManager::SceneManager() noexcept
:
m_queueLevelConfigPath(""),
m_currentLevelConfigPath(""),
m_currentWaveConfigPath(""),
m_queueWaveConfigPath("")
{
}
int My::SceneManager::Initialize()
{
return 0;
}
int My::SceneManager::Tick(double deltaTime)
{
if (m_queueLevelConfigPath != "")
{
g_pScene->Unload();
g_pScene->Load(m_queueLevelConfigPath.c_str());
m_currentLevelConfigPath = m_queueLevelConfigPath;
m_queueLevelConfigPath = "";
}
if (m_queueWaveConfigPath != "")
{
g_pScene->LoadWave(m_queueWaveConfigPath.c_str());
m_currentWaveConfigPath = m_queueWaveConfigPath;
m_queueWaveConfigPath = "";
}
return 0;
}
int My::SceneManager::Finalize()
{
g_pScene->Unload();
return 0;
}
<file_sep>/GameEngine/Common/Event/EventDispatcher.cpp
#include "EventDispatcher.hpp"
#include "Common/Entity/IGameObject.hpp"
#include "Common/Utility/Utility.hpp"
#include <stack>
My::EventDispatcher::EventDispatcher() noexcept
{
}
int My::EventDispatcher::Initialize()
{
return 0;
}
int My::EventDispatcher::Tick(double deltaTime)
{
static std::stack<decltype(m_disptachList.begin())> rm_index;
for (auto it = m_disptachList.begin(); it != m_disptachList.end(); ++it)
{
auto& event_object = (*it);
if ((event_object.first -= deltaTime) <= 0.0)
{
rm_index.push(it);
auto event = event_object.second.first;
auto object = event_object.second.second;
object->AddEvent(event);
}
}
// Erase dispatched events
while (!rm_index.empty())
{
m_disptachList.erase(rm_index.top());
rm_index.pop();
}
return 0;
}
int My::EventDispatcher::Finalize()
{
return 0;
}
void My::EventDispatcher::Serialize(std::wostream& wostream)
{
for (size_t i = 0; i < m_disptachList.size(); ++i)
{
wostream << m_disptachList[i].first ;
auto event = m_disptachList[i].second.first;
auto object = m_disptachList[i].second.second;
event->Serialize(wostream);
object->Serialize(wostream);
}
}
void My::EventDispatcher::Clear()
{
m_disptachList.clear();
}
void My::EventDispatcher::BroadcastToAll(double wait_time, std::weak_ptr<Event> e)
{
auto _e = e.lock();
auto gameObjects = g_pGameObjectResourceManager->GetAllResources();
for (auto it = gameObjects.begin(); it != gameObjects.end(); ++it)
{
std::pair<std::shared_ptr<Event>, IGameObject*> event_pair(_e, it->second);
std::pair<double, std::pair<std::shared_ptr<Event>, IGameObject*>> timed_event_pair(wait_time, event_pair);
m_disptachList.push_back(timed_event_pair);
}
}
void My::EventDispatcher::DispatchToGameObject(double wait_time, std::weak_ptr<Event> e, IGameObject* object)
{
auto _e = e.lock();
std::pair<std::shared_ptr<Event>, IGameObject*> event_pair(_e, object);
std::pair<double, std::pair<std::shared_ptr<Event>, IGameObject*>> timed_event_pair(wait_time, event_pair);
m_disptachList.push_back(timed_event_pair);
}
void My::EventDispatcher::DispatchToSubscribers(double wait_time, std::weak_ptr<Event> e)
{
auto _e = e.lock();
for (auto& object : _e->GetSubscriber())
{
std::pair<std::shared_ptr<Event>, IGameObject*> event_pair(_e, reinterpret_cast<IGameObject*>(object));
std::pair<double, std::pair<std::shared_ptr<Event>, IGameObject*>> timed_event_pair(wait_time, event_pair);
m_disptachList.push_back(timed_event_pair);
}
}
<file_sep>/CS529_Game/src/Component/Logic/PlayerController.hpp
#pragma once
#include "Common/InputManager.hpp"
#include "Common/Component/Logic/Controller.hpp"
#define PLAYER_SPEED 600.0f
namespace My
{
namespace Component
{
class PlayerController : public IComponent
{
public:
PlayerController() = delete;
explicit PlayerController(void* owner, std::string name);
virtual void Update(double deltaTime) override;
virtual void Serialize(std::wostream& wostream) override;
};
}
class PlayerControllerCreator : public IComponentCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IComponent* Create(void* owner = nullptr, MemoryPool* pool = nullptr, std::string name = "PlayerController0") override
{
if (pool)
{
return pool->New<Component::PlayerController>(owner, name);
}
else
{
return new Component::PlayerController(owner, name);
}
}
};
}<file_sep>/CS529_Game/src/Entity/Gameplay/Weapon/Lazer.cpp
#include "Lazer.hpp"
#include "Common/Entity/IGameObject.hpp"
#include "Common/Utility/Utility.hpp"
#include "Common/Component/Physics/Body.hpp"
#include "Common/Component/ComponentManager.hpp"
#include "Common/BaseApplication.hpp"
#include "Common/Entity/GameObjectResourceManager.hpp"
#include "src/Component/Graphics/Sprite.hpp"
#include "src/Component/Graphics/SceneComponent.hpp"
#include "src/Component/Gameplay/HealthPoint.hpp"
int My::Entity::Lazer::Tick(double deltaTime)
{
if (deltaTime != 0.0 && IsActive())
{
ResetSize();
if ((fire_period_timer += deltaTime) >= fire_period)
{
fire_period_timer = 0.0;
switch (m_level)
{
case 1:
SpawnBullet1();
break;
case 2:
SpawnBullet2();
break;
case 3:
SpawnBullet3();
break;
default:
break;
}
}
}
IWeapon::Tick(deltaTime);
return 0;
}
void My::Entity::Lazer::OnComponentHit(std::weak_ptr<Event> e)
{
std::shared_ptr<Event> _e = e.lock();
auto event = static_cast<Events::DeathEvent*>(_e.get());
auto other = reinterpret_cast<IMyGameObject*>(event->other);
if (other->GetType() == MYGAMEOBJECT_TYPE::UFO)
{
DEBUG_wPRINT(str2wstr(m_name + " collides with "));
DEBUG_wPRINT(str2wstr(other->GetName()) << "\n");
{
auto hp_com = static_cast<Component::HealthPoint*>(other->GetComponent(COMPONENT_TYPE::HEALTHPOINT));
std::lock_guard<std::mutex> lock3(hp_com->m_mutex);
float damage = 0.0f;
switch (m_level)
{
case 1:
damage = WEAPON_LAZER_DAM_BASE;
break;
case 2:
damage = WEAPON_LAZER_DAM_BASE + 1.0f;
break;
case 3:
damage = WEAPON_LAZER_DAM_BASE + 2.0f;
break;
default:
break;
}
hp_com->Reduce(ADJUST_fVALUE_60HZ(damage, BaseApplication::frametime));
}
}
}
void My::Entity::Lazer::ResetSize()
{
if (!BaseApplication::IsPuased() && IsActive())
{
auto owner = static_cast<ComponentManager*>(static_cast<IComponent*>(GetOwner())->GetOwner());
auto p_owner_transformCom = static_cast<Component::Body*>(owner->GetComponent(COMPONENT_TYPE::BODY));
auto p_owner_spriteCom = static_cast<Component::Sprite*>(owner->GetComponent(COMPONENT_TYPE::SPRITE));
auto p_transformCom = static_cast<Component::Body*>(GetComponent(COMPONENT_TYPE::BODY));
auto p_spriteCom = static_cast<Component::Sprite*>(GetComponent(COMPONENT_TYPE::SPRITE));
{
std::lock_guard<std::mutex> lock1(p_owner_transformCom->m_mutex);
std::lock_guard<std::mutex> lock2(p_transformCom->m_mutex);
Vector2DSet(&p_transformCom->m_position, &p_owner_transformCom->m_position);
p_spriteCom->m_rcSprite.h = WEAPON_LAZER_ORIGIN_HIEGHT;
p_transformCom->m_position.y -= (p_spriteCom->m_rcSprite.h / 2 + p_owner_spriteCom->m_rcSprite.h / 2);
static_cast<Collision::Rectangle*>(p_transformCom->m_shape)->m_height = static_cast<float>(p_spriteCom->m_rcSprite.h);
}
}
}
IWeapon* My::Entity::Lazer::SpawnBullet()
{
char weaponType[256] = "LazerBeam";
std::string weaponName("003_LB_" + Str(bullet_id++));
// Serialize the game object and set its owner to be the root object.
if (g_weaponSerializationMap.find(weaponType) != g_weaponSerializationMap.end())
{
auto pNewObject = LoadIWeaponFromFile(this, weaponType, weaponName);
// Add game object under the resource manager.
if (1 == g_pGameObjectResourceManager->AddResource(pNewObject, weaponName))
{
std::string msg("Adding resource : '" + std::string(weaponName) + "' has failed.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
// Set bullet to the current weapon level
pNewObject->SetUpgradeLevel(m_level);
return pNewObject;
}
else
{
std::string msg("File does not provide a valid game object of type: " + std::string(weaponName));
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
void My::Entity::Lazer::SpawnBullet1()
{
Vector2D p;
auto owner = static_cast<ComponentManager*>(static_cast<IComponent*>(GetOwner())->GetOwner());
auto p_owner_transformCom = static_cast<Component::Body*>(owner->GetComponent(COMPONENT_TYPE::BODY));
auto p_owner_spriteCom = static_cast<Component::Sprite*>(owner->GetComponent(COMPONENT_TYPE::SPRITE));
{
std::lock_guard<std::mutex> lock1(p_owner_transformCom->m_mutex);
Vector2DSet(&p, &p_owner_transformCom->m_position);
}
Vector2D v(0.0f, -WEAPON_LAZER_BULLET_SPEED);
for (int i = -1; i <= 1; i+=2)
{
auto pNewObject = SpawnBullet();
// Set bullet position and velocity
auto p_transformCom = static_cast<Component::Body*>(pNewObject->GetComponent(COMPONENT_TYPE::BODY));
auto p_spriteCom = static_cast<Component::Sprite*>(pNewObject->GetComponent(COMPONENT_TYPE::SPRITE));
{
std::lock_guard<std::mutex> lock2(p_transformCom->m_mutex);
Vector2DSet(&p_transformCom->m_position, &p);
p_transformCom->m_position.y += (p_owner_spriteCom->m_rcSprite.h / 2);
p_transformCom->m_position.x += i*(p_owner_spriteCom->m_rcSprite.w *2 / 3);
Vector2DSet(&p_transformCom->m_velocity, &v);
}
}
}
void My::Entity::Lazer::SpawnBullet2()
{
SpawnBullet1();
}
void My::Entity::Lazer::SpawnBullet3()
{
SpawnBullet1();
}
<file_sep>/CS529_Game/src/Platform/Win32_SDL/WinSDLInputManager.hpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: InputManager.hpp
Purpose: header file of InputManager
Language: c++ 11
Platform: win32 x86
Project: CS529_final_project
Author: <NAME> hang.yu 60001119
Creation date: 10/13/2019
- End Header ----------------------------*/
#pragma once
#include <SDL.h>
#include "Common/InputManager.hpp"
namespace My
{
class WinSDLInputManager : public InputManager
{
public:
WinSDLInputManager() noexcept;
WinSDLInputManager(const WinSDLInputManager&) = delete;
WinSDLInputManager& operator=(const WinSDLInputManager&) = delete;
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
virtual int KeyIsPressed(int KeyScanCode) noexcept override;
virtual int KeyIsReleased(int KeyScanCode) noexcept override;
virtual int KeyIsDown(int KeyScanCode) noexcept override;
private:
Uint8* m_previous_keyboard_state;
Uint8* m_current_keyboard_state;
const Uint8* keyboard_state;
};
}<file_sep>/GameEngine/Common/BaseApplication.hpp
#pragma once
#include <sstream>
#include "Common/Interface/IRunTimeModule.hpp"
#include "Common/GfxConfiguration.hpp"
#include "Common/MemoryManager.hpp"
namespace My
{
class BaseApplication : public IRunTimeModule
{
public:
BaseApplication() = delete;
BaseApplication(const BaseApplication&) = delete;
BaseApplication& operator=(const BaseApplication&) = delete;
explicit BaseApplication(const GfxConfiguration& config);
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
virtual int BeginDraw();
virtual int OnDraw();
virtual int EndDraw();
virtual void ShowMessage(const std::wstring& title, const std::wstring& message);
const GfxConfiguration& GetConfig() const noexcept;
virtual void SetConfig(const GfxConfiguration& config) noexcept;
static void UpdateFrameTime(double deltaTime);
static bool IsQuit();
static bool IsPuased();
static void SetQuit(bool q);
static void TogglePause();
public:
static double frametime;
static double time_modifier;
static double static_frametime;
protected:
GfxConfiguration m_config;
private:
static bool m_bQuit;
static bool m_bPaused;
};
extern std::shared_ptr<BaseApplication> g_pBaseApplication;
}
#include "Common/Utility/Scheduler.hpp"<file_sep>/CS529_Game/src/Component/Gameplay/HealthPoint.hpp
#pragma once
#include <mutex>
#include "Common/Component/Interface/IComponent.hpp"
namespace My
{
namespace Component
{
class HealthPoint : public IComponent
{
public:
HealthPoint() = delete;
explicit HealthPoint(void* owner, std::string name);;
virtual void Update(double deltaTime) override;
virtual void Serialize(std::ifstream& fstream) override;
virtual void Serialize(std::wostream& wostream) override;
/* Lock HP for deltaTime seconds */
void LockHP();
void UnLockHP();
void Restore(float value);
void Reduce(float value);
bool IsDeplited();
bool IsLockHP();
public:
std::mutex m_mutex;
private:
float m_value;
float m_maxValue;
bool b_lockHP;
};
}
class HealthPointCreator : public IComponentCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IComponent* Create(void* owner = nullptr, MemoryPool* pool = nullptr, std::string name = "HealthPoint0") override
{
if (pool)
{
return pool->New<Component::HealthPoint>(owner, name);
}
else
{
return new Component::HealthPoint(owner, name);
}
}
};
}<file_sep>/GameEngine/Common/Utility/Utility.hpp
#pragma once
#include <fstream>
#include <sstream>
#include <iostream>
#include "Common/Geommath/2D/Math.hpp"
#define PRINT(str) std::cout << str
#define wPRINT(str) std::wcout << str
#define ADJUST_fVALUE_60HZ(value, frameTime) value * static_cast<float>(frameTime) * 60.0f
#define ADJUST_dVALUE_60HZ(value, frameTime) value * frameTime * 60.0
#ifdef _DEBUG
#define DEBUG_PRINT(str) std::cout << str
#define DEBUG_wPRINT(str) std::wcout << str
#else
#define DEBUG_PRINT(str)
#define DEBUG_wPRINT(str)
#endif // DEBUG
namespace My
{
template <typename T>
std::string Str(const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
template <typename T>
std::wstring wStr(const T& t)
{
std::wstringstream ss;
ss << t;
return ss.str();
}
template<class T>
void SafeRelease(T **ppInterfaceToRelease)
{
if (*ppInterfaceToRelease != nullptr)
{
(*ppInterfaceToRelease)->Release();
(*ppInterfaceToRelease) = nullptr;
}
}
void print_fstream(std::ifstream& fstream);
void rewind_fstream(std::ifstream& fstream);
}
<file_sep>/GameEngine/Common/Entity/GameObjectType.h
#pragma once
#include <string>
#include <map>
#include <memory>
namespace My
{
enum class GAMEOBJECT_TYPE
{
CUSTOM_GAME = 0,
NUM
};
}<file_sep>/CS529_Game/Resource/TODO.txt
Game objects:
Dec5,6
0, weapon component (x)
1, Weapon class lazer - collectable, mutal exclusive (x)
2, Weapon class kinetic weapon - collectable, mutal exclusive (x)
3, Weapon class homing missile - collectable, mutal exclusive (x)
4, Universal weaponary upgrades that upgr ades lazer, kinetice weapon, and homing missle
- Memorized by the weapon component, upgrades are incremental only (x)
Make damage frame time indifferent (x)
Dec6,
4.5 Priority rendering (x, using the fact that std::map is ordered by its key)
4.5, Sound system (x)
5, Pause menu (Resume, Restart, Main menu, Game Guide) (x)
6, Beat the game menu (You won!, Main menu) (x)
7, Failure menu (You die!, Restart, Main menu) (x)
9, BGM Volume button (x)
Dec7,
Mechanics:
1, HP pack - restore the real hp (x)
2, Upgrade pack (x)
3, Invincible pack - consumable activative skill (4s depletion) (x)
4, Score ui, hp ui, (Maybe not?)
Reference
https://www.bilibili.com/video/av1066398?from=search&seid=11013035783363053575
(AI: 1, transformation mode 2, firing mode)
9, small ufo ai (moving from left to right, right to left and launches bullets)
10, mid ufo ai (holding a position and shoot clusterd bomb)
12, Boss ufo ai (moving : shooting a waterfall of bullets, holding : shooting clustered bomb)
8, Game Guide menu (On going)
<file_sep>/GameEngine/Common/InputManager.cpp
#include "InputManager.hpp"
My::InputManager::InputManager() noexcept
{
}
int My::InputManager::Initialize()
{
return 0;
}
int My::InputManager::Tick(double deltaTime)
{
return 0;
}
int My::InputManager::Finalize()
{
return 0;
}
int My::InputManager::KeyIsPressed(int KeyScanCode) noexcept
{
return 0;
}
int My::InputManager::KeyIsReleased(int KeyScanCode) noexcept
{
return 0;
}
int My::InputManager::KeyIsDown(int KeyScanCode) noexcept
{
return 0;
}<file_sep>/CS529_Game/src/Component/Logic/AIController.hpp
#pragma once
#include "Common/InputManager.hpp"
#include "Common/Component/Logic/Controller.hpp"
#include "Common/Geommath/2D/Vector2D.hpp"
#include "src/Entity/Gameplay/Interface/IWeapon.hpp"
namespace My
{
namespace Component
{
class AIController : public IComponent
{
public:
AIController() = delete;
explicit AIController(void* owner, std::string name);
virtual void Update(double deltaTime) override;
virtual void Serialize(std::wostream& wostream) override;
virtual void Serialize(std::ifstream& fstream) override;
void UpdateMotion(double deltaTime);
void UpdateFire(double deltaTime);
void SetFireMode(int mode);
IWeapon* SpawnBullet(std::string weaponType, int lvl);
public:
bool switched_event_sent;
private:
int motion_mode;
int motion_mode2;
int motion_mode3;
int fire_mode;
int fire_mode2;
int fire_mode3;
uint64_t bullet_id;
Vector2D m_destination;
double fire_period;
double fire_period_timer;
float m_phase;
float m_amplitude;
float m_right;
};
}
class AIControllerCreator : public IComponentCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IComponent* Create(void* owner = nullptr, MemoryPool* pool = nullptr, std::string name = "AIController0") override
{
if (pool)
{
return pool->New<Component::AIController>(owner, name);
}
else
{
return new Component::AIController(owner, name);
}
}
};
}<file_sep>/CS529_Game/src/Entity/Gameplay/Weapon/MissileExplosion.hpp
#pragma once
#include "Common/Event/Event.hpp"
#include "src/Entity/Gameplay/Interface/IWeapon.hpp"
#include "src/Event/MyEvent.hpp"
namespace My
{
namespace Entity
{
class MissileExplosion : public IWeapon
{
public:
MissileExplosion() = delete;
explicit MissileExplosion(void* owner, std::string name) noexcept
:
IWeapon(WEAPON_TYPE::WEAPON_MISSILE_EXPLOSION, owner, name),
life_time_timer(0.0)
{
}
virtual int Tick(double deltaTime) override;
private:
double life_time_timer;
};
}
class MissileExplosionObjectCreator : public IWeaponCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IWeapon* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "MissileExplosion0") override
{
if (pool)
{
return pool->New<Entity::MissileExplosion>(owner, name);
}
else
{
return new Entity::MissileExplosion(owner, name);
}
}
};
}<file_sep>/GameEngine/Common/Entity/GameObjectResourceManager.hpp
#pragma once
#include "IGameObject.hpp"
namespace My
{
class IGameObjectResourceManager : public ResourceManager<IGameObject>
{
public:
/* Update all game objects, and erase inactive game objects afterwards */
virtual int Tick(double deltaTime) override;
int DrawAll();
void GC();
/* Use Memory Manager's Delete function to free all pointers managed by this resource manager.- */
virtual int Clear() override
{
for (auto it = m_resourceMap.begin(); it != m_resourceMap.end(); ++it)
{
g_pMemoryManager->Delete(it->second);
}
m_resourceMap.clear();
return 0;
}
/* Find all resources that contains name */
std::vector<IGameObject*> FindAllResourcesByName(std::string sub_name)
{
std::vector<IGameObject*> result;
for (auto it = m_resourceMap.begin(); it != m_resourceMap.end(); ++it)
{
if (it->first.find(sub_name) != std::string::npos)
{
result.push_back(it->second);
}
}
return result;
}
private:
std::vector<std::string> gc_list;
};
// TODO : Initialize in your application
extern std::shared_ptr<IGameObjectResourceManager> g_pGameObjectResourceManager;
// TODO : Initialize in your application
extern std::map<std::string, GAMEOBJECT_TYPE> g_gameObjectSerializationMap;
extern std::map<GAMEOBJECT_TYPE, std::shared_ptr<IGameObjectCreator>> g_gameObjectCreatorMap;
}<file_sep>/CS529_Game/src/Component/Logic/PackController.hpp
#pragma once
#include "Common/InputManager.hpp"
#include "Common/Component/Logic/Controller.hpp"
#include "Common/Geommath/2D/Vector2D.hpp"
#define PACK_SPEED_LOW 100.0f
#define PACK_SPEED_HIGH 200.0f
namespace My
{
namespace Component
{
class PackController : public IComponent
{
public:
PackController() = delete;
explicit PackController(void* owner, std::string name);
virtual void Update(double deltaTime) override;
virtual void Serialize(std::wostream& wostream) override;
private:
Vector2D m_velocity;
};
}
class PackControllerCreator : public IComponentCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IComponent* Create(void* owner = nullptr, MemoryPool* pool = nullptr, std::string name = "PackController0") override
{
if (pool)
{
return pool->New<Component::PackController>(owner, name);
}
else
{
return new Component::PackController(owner, name);
}
}
};
}<file_sep>/GameEngine/Common/InputManager.hpp
#pragma once
#include "Interface/IRunTimeModule.hpp"
namespace My
{
class InputManager : public IRunTimeModule
{
public:
InputManager() noexcept;
InputManager(const InputManager&) = delete;
InputManager& operator=(const InputManager&) = delete;
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
virtual int KeyIsPressed(int KeyScanCode) noexcept;
virtual int KeyIsReleased(int KeyScanCode) noexcept;
virtual int KeyIsDown(int KeyScanCode) noexcept;
};
extern std::shared_ptr<InputManager> g_pInputManager;
}<file_sep>/GameEngine/Common/Geommath/2D/LineSegment2D.h
#ifndef LINESEGMENT2D_H
#define LINESEGMENT2D_H
#include "Vector2D.hpp"
using namespace My;
typedef struct LineSegment2D
{
Vector2D mP0; // Point on the line
Vector2D mP1; // Point on the line
Vector2D mN; // Line's normal
float mNdotP0; // To avoid computing it every time it's needed
}LineSegment2D;
/*
This function builds a 2D line segment's data using 2 points
- Computes the normal (Unit Vector)
- Computes the dot product of the normal with one of the points
- Parameters
- LS: The to-be-built line segment
- Point0: One point on the line
- Point1: Another point on the line
- Returns 1 if the line equation was built successfully
*/
int BuildLineSegment2D(LineSegment2D *LS, Vector2D *Point0, Vector2D *Point1);
#endif<file_sep>/CS529_Game/src/Component/Gameplay/HealthPoint.cpp
#include "HealthPoint.hpp"
#include "Common/Utility/Utility.hpp"
My::Component::HealthPoint::HealthPoint(void* owner, std::string name)
:
IComponent((COMPONENT_TYPE::HEALTHPOINT), owner, name),
m_value(0.0f),
m_maxValue(0.0f),
b_lockHP(false)
{
}
void My::Component::HealthPoint::Update(double deltaTime)
{
}
void My::Component::HealthPoint::Serialize(std::ifstream& fstream)
{
for (std::string line; getline(fstream, line);)
{
if (2 == sscanf_s(line.c_str(), "%f %f", &m_value, &m_maxValue))
{
}
else if (line[0] == ']')
{
return;
}
else
{
print_fstream(fstream);
std::string msg("Sprite serialization has failed at line " + line + ".");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
void My::Component::HealthPoint::Serialize(std::wostream& wostream)
{
wostream << "[Component : HealthPoint] ";
}
void My::Component::HealthPoint::LockHP()
{
b_lockHP = true;
}
void My::Component::HealthPoint::UnLockHP()
{
b_lockHP = false;
}
void My::Component::HealthPoint::Restore(float value)
{
if (!b_lockHP)
{
if (m_value < m_maxValue)
{
m_value += value;
}
else
{
m_value = m_maxValue;
}
}
}
void My::Component::HealthPoint::Reduce(float value)
{
if (!b_lockHP)
{
if (m_value > 0.0f)
{
m_value -= value;
}
else
{
m_value = 0.0f;
}
}
}
bool My::Component::HealthPoint::IsDeplited()
{
return m_value <= 0.0f;
}
bool My::Component::HealthPoint::IsLockHP()
{
return b_lockHP;
}
<file_sep>/CS529_Game/src/Component/Gameplay/WeaponarySystem.hpp
#pragma once
#include "Common/Component/Interface/IComponent.hpp"
#include "src/Entity/Gameplay/Interface/IWeapon.hpp"
namespace My
{
namespace Component
{
class WeaponarySystem : public IComponent
{
public:
WeaponarySystem() = delete;
explicit WeaponarySystem(void* owner, std::string name);
virtual void Update(double deltaTime) override;
virtual ~WeaponarySystem();
virtual void Serialize(std::ifstream& fstream) override;
virtual void Serialize(std::wostream& wostream) override;
void UpgradeWeapons();
void DowngradeWeapons();
void ChangeWeapon(int id, std::string name);
private:
int m_maxWeapons;
std::vector<IWeapon*> m_currentWeapons;
std::vector<std::map<std::string, IWeapon*>> m_weaponMaps;
};
}
class WeaponarySystemCreator : public IComponentCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IComponent* Create(void* owner = nullptr, MemoryPool* pool = nullptr, std::string name = "WeaponarySystem0") override
{
if (pool)
{
return pool->New<Component::WeaponarySystem>(owner, name);
}
else
{
return new Component::WeaponarySystem(owner, name);
}
}
};
}<file_sep>/CS529_Game/src/Entity/Gameplay/Weapon/MissileExplosion.cpp
#include "MissileExplosion.hpp"
#include "Common/Component/Physics/Body.hpp"
int My::Entity::MissileExplosion::Tick(double deltaTime)
{
if (deltaTime != 0.0)
{
if ((life_time_timer += deltaTime) >= WEAPON_MISSILE_EXPLOSION_LIFETIME)
{
SetGCToTrue();
}
}
IWeapon::Tick(deltaTime);
return 0;
}
<file_sep>/GameEngine/Common/Component/Logic/Controller.hpp
#pragma once
#include "Common/InputManager.hpp"
#include "Common/Component/Interface/IComponent.hpp"
namespace My
{
namespace Component
{
class PlayerController;
class AIController;
}
class PlayerControllerCreator;
class AIControllerCreator;
}<file_sep>/CS529_Game/src/Component/Graphics/SceneComponent.cpp
#include "SceneComponent.hpp"
#include "Common/Component/ComponentManager.hpp"
#include "Common/Component/Physics/Body.hpp"
#include "Common/Entity/IGameObject.hpp"
#include "src/Component/Graphics/Sprite.hpp"
#include "src/Platform/Win32_SDL/WinSDLOpenGLApplication.hpp"
#include "src/Entity/Gameplay/UI/Button.hpp"
My::Component::SceneComponent::SceneComponent(void* owner, std::string name) : IComponent(COMPONENT_TYPE::SCENECOMPONENT, owner, name)
{
}
My::Component::SceneComponent::~SceneComponent()
{
}
void My::Component::SceneComponent::Update(double deltaTime)
{
}
void My::Component::SceneComponent::Serialize(std::wostream& wostream)
{
wostream << "[Component : SceneComponent] ";
}
void My::Component::SceneComponent::Draw()
{
auto name = static_cast<IMyGameObject*>(static_cast<ComponentManager*>(GetOwner())->GetOwner())->GetName();
if (name.find("Background") != std::string::npos)
{
DrawBackground();
}
else if (name.find("PauseMenu") != std::string::npos)
{
DrawPauseMenu();
}
else
{
DrawObject();
}
}
void My::Component::SceneComponent::DrawObject()
{
auto owner = static_cast<ComponentManager*>(GetOwner());
auto temp_sprite = owner->GetComponent(COMPONENT_TYPE::SPRITE);
auto p_spriteCom = static_cast<Component::Sprite*>(temp_sprite);
auto p_App = static_cast<WinSDLOpenGLApplication*>(g_pBaseApplication.get());
SDL_RenderCopyEx(p_App->GetRenderer(), p_spriteCom->m_sprite, nullptr, &p_spriteCom->m_rcSprite, p_spriteCom->m_degree, nullptr, SDL_FLIP_NONE);
}
void My::Component::SceneComponent::DrawPauseMenu()
{
auto owner = static_cast<ComponentManager*>(GetOwner());
auto button = static_cast<Entity::UI_Button*>(owner->GetOwner());
if (BaseApplication::IsPuased())
{
button->SetIsShown(true);
auto temp_sprite = owner->GetComponent(COMPONENT_TYPE::SPRITE);
auto p_spriteCom = static_cast<Component::Sprite*>(temp_sprite);
auto p_App = static_cast<WinSDLOpenGLApplication*>(g_pBaseApplication.get());
SDL_RenderCopyEx(p_App->GetRenderer(), p_spriteCom->m_sprite, nullptr, &p_spriteCom->m_rcSprite, p_spriteCom->m_degree, nullptr, SDL_FLIP_NONE);
}
else
{
button->SetIsShown(false);
}
}
void My::Component::SceneComponent::DrawBackground()
{
auto owner = reinterpret_cast<ComponentManager*>(GetOwner());
auto temp_sprite = owner->GetComponent(COMPONENT_TYPE::SPRITE);
auto temp_body = owner->GetComponent(COMPONENT_TYPE::BODY);
auto p_App = reinterpret_cast<WinSDLOpenGLApplication*>(g_pBaseApplication.get());
if (temp_sprite && temp_body && p_App)
{
auto p_spriteCom = reinterpret_cast<Component::Sprite*>(temp_sprite);
auto p_bodyCom = reinterpret_cast<Component::Body*>(temp_body);
int SCREEN_WIDTH, SCREEN_HEIGHT, SPRITE_WIDTH, SPRITE_HEIGHT;
SDL_GetWindowSize(p_App->GetWindow(), &SCREEN_WIDTH, &SCREEN_HEIGHT);
SPRITE_WIDTH = p_spriteCom->m_rcSprite.w;
SPRITE_HEIGHT = p_spriteCom->m_rcSprite.h;
// Repeater mechanism, reset backgroud sprite to the origin
{
std::lock_guard<std::mutex> lock(p_bodyCom->m_mutex);
p_bodyCom->m_position.x = fmodf(p_bodyCom->m_position.x, static_cast<float>(SPRITE_WIDTH));
p_bodyCom->m_position.y = fmodf(p_bodyCom->m_position.y, static_cast<float>(SPRITE_HEIGHT));
}
SDL_Rect rcSurface = p_spriteCom->m_rcSprite;
/* draw the background */
for (int x = -1; x < SCREEN_WIDTH / SPRITE_WIDTH + 2; x++)
{
for (int y = -1; y < SCREEN_HEIGHT / SPRITE_HEIGHT + 2; y++)
{
rcSurface.x = x * SPRITE_WIDTH + p_spriteCom->m_rcSprite.x;
rcSurface.y = y * SPRITE_HEIGHT + p_spriteCom->m_rcSprite.y;
SDL_RenderCopy(p_App->GetRenderer(), p_spriteCom->m_sprite, nullptr, &rcSurface);
}
}
}
}
<file_sep>/GameEngine/Common/Geommath/2D/Vector2D.cpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: Vector2D
Purpose: implementation of Vector2D
Language: c++ 11
Platform: win32 x86
Project: CS529_project_2
Author: <NAME> hang.yu 60001119
Creation date: 10/30/2019
- End Header ----------------------------*/
#include "Vector2D.hpp"
// ---------------------------------------------------------------------------
void My::Vector2DZero(Vector2D *pResult)
{
pResult->x = 0;
pResult->y = 0;
}
void My::Vector2DSet(Vector2D* pResult, Vector2D* pVec0)
{
pResult->x = pVec0->x;
pResult->y = pVec0->y;
}
void My::Vector2DSet(Vector2D* pResult, const Vector2D* pVec0)
{
pResult->x = pVec0->x;
pResult->y = pVec0->y;
}
// ---------------------------------------------------------------------------
void My::Vector2DSet(Vector2D *pResult, float x, float y)
{
pResult->x = x;
pResult->y = y;
}
// ---------------------------------------------------------------------------
void My::Vector2DNeg(Vector2D *pResult, Vector2D *pVec0)
{
pResult->x = -pVec0->x;
pResult->y = -pVec0->y;
}
// ---------------------------------------------------------------------------
void My::Vector2DAdd(Vector2D *pResult, Vector2D *pVec0, Vector2D *pVec1)
{
pResult->x = (pVec0->x + pVec1->x);
pResult->y = (pVec0->y + pVec1->y);
}
// ---------------------------------------------------------------------------
void My::Vector2DSub(Vector2D *pResult, Vector2D *pVec0, Vector2D *pVec1)
{
pResult->x = (pVec0->x - pVec1->x);
pResult->y = (pVec0->y - pVec1->y);
}
// ---------------------------------------------------------------------------
void My::Vector2DNormalize(Vector2D *pResult, Vector2D *pVec0)
{
float len_inverse = 1.0f / (Vector2DLength(pVec0) + EPSILON);
pResult->x = pVec0->x * len_inverse;
pResult->y = pVec0->y * len_inverse;
}
// ---------------------------------------------------------------------------
void My::Vector2DScale(Vector2D *pResult, Vector2D *pVec0, float c)
{
pResult->x = pVec0->x * c;
pResult->y = pVec0->y * c;
}
// ---------------------------------------------------------------------------
void My::Vector2DScaleAdd(Vector2D *pResult, Vector2D *pVec0, Vector2D *pVec1, float c)
{
pResult->x = (pVec0->x * c + pVec1->x);
pResult->y = (pVec0->y * c + pVec1->y);
}
// ---------------------------------------------------------------------------
void My::Vector2DScaleSub(Vector2D *pResult, Vector2D *pVec0, Vector2D *pVec1, float c)
{
pResult->x = (pVec0->x * c - pVec1->x);
pResult->y = (pVec0->y * c - pVec1->y);
}
// ---------------------------------------------------------------------------
float My::Vector2DLength(Vector2D *pVec0)
{
return (pVec0) ? sqrtf(powf(pVec0->x,2) + powf(pVec0->y,2)) : F_UNDEFINE;
}
// ---------------------------------------------------------------------------
float My::Vector2DSquareLength(Vector2D *pVec0)
{
return (pVec0) ? (powf(pVec0->x, 2) + powf(pVec0->y, 2)) : F_UNDEFINE;
}
// ---------------------------------------------------------------------------
float My::Vector2DDistance(Vector2D *pVec0, Vector2D *pVec1)
{
return (pVec0 && pVec1) ? sqrtf(powf(pVec0->x - pVec1->x, 2) + powf(pVec0->y - pVec1->y, 2)) : F_UNDEFINE;
}
// ---------------------------------------------------------------------------
float My::Vector2DSquareDistance(Vector2D *pVec0, Vector2D *pVec1)
{
return (pVec0 && pVec1) ? (powf(pVec0->x - pVec1->x, 2) + powf(pVec0->y - pVec1->y, 2)) : F_UNDEFINE;
}
// ---------------------------------------------------------------------------
float My::Vector2DDotProduct(Vector2D *pVec0, Vector2D *pVec1)
{
return (pVec0 && pVec1) ? (pVec0->x * pVec1->x + pVec0->y * pVec1->y) : F_UNDEFINE;
}
// ---------------------------------------------------------------------------
void My::Vector2DFromAngleDeg(Vector2D *pResult, float angle)
{
Vector2DFromAngleRad(pResult, 0.01745329251f * angle);
}
// ---------------------------------------------------------------------------
void My::Vector2DFromAngleRad(Vector2D *pResult, float angle)
{
float c = cosf(angle);
float s = sinf(angle);
float x = pResult->x * c - pResult->y * s;
float y = pResult->x * s + pResult->y * c;
pResult->x = x;
pResult->y = y;
}
float My::Vector2DAngleFromVec2(Vector2D* pVec)
{
return (pVec) ? atanf(pVec->y / pVec->x) : F_UNDEFINE;
}
namespace My
{
Vector2D operator-(Vector2D& vec1, Vector2D& vec2)
{
Vector2D ret;
Vector2DSub(&ret, &vec1, &vec2);
return ret;
}
Vector2D operator+(Vector2D& vec1, Vector2D& vec2)
{
Vector2D ret;
Vector2DAdd(&ret, &vec1, &vec2);
return ret;
}
}
// ---------------------------------------------------------------------------
<file_sep>/GameEngine/Common/Entity/GameObjectResourceManager.cpp
#include "GameObjectResourceManager.hpp"
#include "Common/MemoryManager.hpp"
#include "Common/Component/Physics/BodyResourceManager.hpp"
#include "Common/Utility/Utility.hpp"
int My::IGameObjectResourceManager::Tick(double deltaTime)
{
for (auto it = m_resourceMap.begin(); it != m_resourceMap.end(); ++it)
{
if (it->second->IsActive())
{
it->second->Tick(deltaTime);
}
else if (it->second->IsGC())
{
gc_list.push_back(it->first);
}
}
return 0;
}
int My::IGameObjectResourceManager::DrawAll()
{
for (auto it = m_resourceMap.begin(); it != m_resourceMap.end(); ++it)
{
if (it->second->IsActive())
{
it->second->Draw();
}
}
return 0;
}
void My::IGameObjectResourceManager::GC()
{
// GC
for (auto& name : gc_list)
{
g_pBodyResourceManager->FreeByNameWithDefault(name);
FreeByNameWithMemoryManager(name);
DEBUG_PRINT("Object GC " + name + "\n");
}
gc_list.clear();
}
<file_sep>/GameEngine/Common/Geommath/2D/Matrix2D.cpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: Matrix2D
Purpose: implementation of Matrix2D
Language: c++ 11
Platform: win32 x86
Project: CS529_project_2
Author: <NAME> hang.yu 60001119
Creation date: 10/03/2019
- End Header ----------------------------*/
#include "Matrix2D.hpp"
/*
This function sets the matrix Result to the identity matrix
*/
void My::Matrix2DIdentity(Matrix2D* pResult)
{
if (pResult)
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
pResult->m[i][j] = (i == j) ? 1.0f : 0.0f;
}
}
}
}
// ---------------------------------------------------------------------------
/*
This functions calculated the transpose matrix of Mtx and saves it in Result
*/
void My::Matrix2DTranspose(Matrix2D *pResult, Matrix2D *pMtx)
{
if (pResult && pMtx)
{
// Not the same pointer, just swap
if (pResult != pMtx)
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
pResult->m[i][j] = pMtx->m[j][i];
}
}
}
// The same pointer, needs a temporal matrix to store values
else
{
Matrix2D mat;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
mat.m[i][j] = pMtx->m[j][i];
}
}
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
pResult->m[i][j] = mat.m[i][j];
}
}
}
}
}
// ---------------------------------------------------------------------------
/*
This function multiplies Mtx0 with Mtx1 and saves the result in Result
Result = Mtx0*Mtx1
*/
void My::Matrix2DConcat(Matrix2D* pResult, const Matrix2D* pMtx0, const Matrix2D* pMtx1)
{
if (pResult && pMtx0 && pMtx1)
{
Matrix2D mat;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
mat.m[i][j] = pMtx0->m[i][0] * pMtx1->m[0][j] \
+ pMtx0->m[i][1] * pMtx1->m[1][j] \
+ pMtx0->m[i][2] * pMtx1->m[2][j];
}
}
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
pResult->m[i][j] = mat.m[i][j];
}
}
}
}
void My::Matrix2DConcat(Matrix2D* pResult, Matrix2D* pMtx0, Matrix2D* pMtx1)
{
if (pResult && pMtx0 && pMtx1)
{
Matrix2D mat;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
mat.m[i][j] = pMtx0->m[i][0] * pMtx1->m[0][j] \
+ pMtx0->m[i][1] * pMtx1->m[1][j] \
+ pMtx0->m[i][2] * pMtx1->m[2][j];
}
}
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
pResult->m[i][j] = mat.m[i][j];
}
}
}
}
// ---------------------------------------------------------------------------
/*
This function creates a translation matrix from x & y and saves it in Result
*/
void My::Matrix2DTranslate(Matrix2D *pResult, float x, float y)
{
if (pResult)
{
Matrix2DIdentity(pResult);
pResult->m[0][2] = x;
pResult->m[1][2] = y;
}
}
// ---------------------------------------------------------------------------
/*
This function creates a scaling matrix from x & y and saves it in Result
*/
void My::Matrix2DScale(Matrix2D *pResult, float x, float y)
{
if (pResult)
{
Matrix2DIdentity(pResult);
pResult->m[0][0] = x;
pResult->m[1][1] = y;
}
}
// ---------------------------------------------------------------------------
/*
This matrix creates a rotation matrix from "Angle" whose value is in degree.
Save the resultant matrix in Result
*/
void My::Matrix2DRotDeg(Matrix2D *pResult, float Angle)
{
if (pResult)
{
Angle *= ((float)PI / 180.0f);
float c = cosf(Angle);
float s = sinf(Angle);
Matrix2DIdentity(pResult);
pResult->m[0][0] = c;
pResult->m[0][1] = -s;
pResult->m[1][0] = s;
pResult->m[1][1] = c;
}
}
// ---------------------------------------------------------------------------
/*
This matrix creates a rotation matrix from "Angle" whose value is in radian.
Save the resultant matrix in Result
*/
void My::Matrix2DRotRad(Matrix2D *pResult, float Angle)
{
if (pResult)
{
float c = cosf(Angle);
float s = sinf(Angle);
Matrix2DIdentity(pResult);
pResult->m[0][0] = c;
pResult->m[0][1] = -s;
pResult->m[1][0] = s;
pResult->m[1][1] = c;
}
}
// ---------------------------------------------------------------------------
/*
This function multiplies the matrix Mtx with the vector Vec and saves the result in Result
Result = Mtx * Vec
*/
void My::Matrix2DMultVec(Vector2D *pResult, Matrix2D *pMtx, Vector2D *pVec)
{
if (pResult && pMtx && pVec)
{
// pVec has w coord as 1.0f, which can be ignored as a translation multiplier.
float x = pMtx->m[0][0] * pVec->x + pMtx->m[0][1] * pVec->y + pMtx->m[0][2];
float y = pMtx->m[1][0] * pVec->x + pMtx->m[1][1] * pVec->y + pMtx->m[1][2];
Vector2DSet(pResult, x, y);
}
}
void My::Matrix2DMultVec(Vector2D* pResult, const Matrix2D* pMtx, const Vector2D* pVec)
{
if (pResult && pMtx && pVec)
{
// pVec has w coord as 1.0f, which can be ignored as a translation multiplier.
float x = pMtx->m[0][0] * pVec->x + pMtx->m[0][1] * pVec->y + pMtx->m[0][2];
float y = pMtx->m[1][0] * pVec->x + pMtx->m[1][1] * pVec->y + pMtx->m[1][2];
Vector2DSet(pResult, x, y);
}
}
My::Matrix2D operator*(const My::Matrix2D& mat1, const My::Matrix2D& mat2)
{
My::Matrix2D ret;
Matrix2DConcat(&ret, &mat1, &mat2);
return ret;
}
My::Vector2D operator*(const My::Matrix2D& mat1, const My::Vector2D& mat2)
{
My::Vector2D ret;
Matrix2DMultVec(&ret, &mat1, &mat2);
return ret;
}
// ---------------------------------------------------------------------------
<file_sep>/GameEngine/Common/Component/ComponentManager.hpp
#pragma once
#include "Common/Interface/IRunTimeModule.hpp"
#include "Common/Component/Interface/IComponent.hpp"
#include "Common/MemoryPool.hpp"
#define MEMORY_POOL_OPT 1
namespace My
{
class ComponentManager : public IRunTimeModule
{
public:
ComponentManager() noexcept;
ComponentManager(const ComponentManager&) = delete;
ComponentManager& operator=(const ComponentManager&) = delete;
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
virtual void Serialize(std::wostream& wostream) override;
/**
* \brief AddComponent: add newly allocated component to the component manager of such type.
*
* If the component of such type already exists, simply return the existed component.
* Set the ownership of that component to this component manager.
* \author <NAME>
* \date 10/21/2019
* \return pointer to component.
* \exception None.
* @param com IComponent pointer.
*/
IComponent* AddComponent(COMPONENT_TYPE type);
/**
* \brief GetComponent: return component with such type
* \author <NAME>
* \date 10/21/2019
* \return pointer to component pointer, nullptr if such component type does not exist.
* \exception None.
* @param type COMPONENT_TYPE enumerator.
*/
IComponent* GetComponent(COMPONENT_TYPE type);
void* GetOwner() noexcept;
void SetOwner(void* owner) noexcept;
private:
// Owner is an entity (e.g. IGameObject)
void* m_owner;
#if MEMORY_POOL_OPT
MemoryPool m_pool;
#else
std::vector<std::shared_ptr<IComponent>> m_components;
#endif // MEMORY_POOL_OPT
};
}<file_sep>/CS529_Game/src/Entity/Gameplay/Weapon/UFOBullet.hpp
#pragma once
#include "Common/Event/Event.hpp"
#include "src/Entity/Gameplay/Interface/IWeapon.hpp"
#include "src/Event/MyEvent.hpp"
namespace My
{
namespace Entity
{
class UFOBullet : public IWeapon
{
public:
UFOBullet() = delete;
explicit UFOBullet(void* owner, std::string name) noexcept : IWeapon(WEAPON_TYPE::UFO_BULLET, owner, name)
{
m_eventManager.AddEventRegistry(EventType::ON_COMPONENTHIT);
}
virtual int Tick(double deltaTime) override;
virtual void HandleEvent(std::weak_ptr<Event> e) override
{
std::shared_ptr<Event> _e = e.lock();
switch (_e->GetType())
{
case EventType::ON_COMPONENTHIT:
OnComponentHit(_e);
break;
default:
break;
}
}
/*
Hitting UFO:
Shrink the UFOBullet to the colliding object
*/
void OnComponentHit(std::weak_ptr<Event> e);
};
}
class UFOBulletObjectCreator : public IWeaponCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IWeapon* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "UFOBullet0") override
{
if (pool)
{
return pool->New<Entity::UFOBullet>(owner, name);
}
else
{
return new Entity::UFOBullet(owner, name);
}
}
};
}<file_sep>/GameEngine/Common/Geommath/2D/LineSegment2D.c
#include "LineSegment2D.h"
using namespace My;
int BuildLineSegment2D(LineSegment2D *LS, Vector2D *Point0, Vector2D *Point1)
{
if (LS && Point0 && Point1)
{
Vector2DSet(&(LS->mP0), Point0->x, Point0->y);
Vector2DSet(&(LS->mP1), Point1->x, Point1->y);
Vector2DSub(&(LS->mN), Point1, Point0);
Vector2DSet(&(LS->mN), LS->mN.y, -LS->mN.x);
Vector2DNormalize(&(LS->mN), &(LS->mN));
LS->mNdotP0 = Vector2DDotProduct(&(LS->mN), Point0);
return 1;
}
else
{
return 0;
}
}<file_sep>/CS529_Game/src/Component/Logic/PlayerController.cpp
#include <SDL.h>
#include "PlayerController.hpp"
#include "Common/Geommath/2D/Vector2D.hpp"
#include "Common/Component/ComponentManager.hpp"
#include "Common/Component/Physics/Body.hpp"
#include "Common/Event/EventDispatcher.hpp"
#include "Common/Entity/GameObjectResourceManager.hpp"
#include "Common/BaseApplication.hpp"
#include "Common/Utility/Utility.hpp"
#include "src/Component/Gameplay/WeaponarySystem.hpp"
#include "src/Platform/Win32_SDL/WinSDLOpenGLApplication.hpp"
#include "src/Component/Graphics/Sprite.hpp"
My::Component::PlayerController::PlayerController(void* owner, std::string name)
:
IComponent((COMPONENT_TYPE::PLAYERCONTROLLER), owner, name)
{
}
void My::Component::PlayerController::Update(double deltaTime)
{
// Puase by clicking "Esc"
if (g_pInputManager->KeyIsPressed(SDL_SCANCODE_ESCAPE))
{
BaseApplication::TogglePause();
}
// Controller logic proceeds iff the game is not paused
if (!BaseApplication::IsPuased())
{
float player_speed = PLAYER_SPEED;
// Slow time
if (g_pInputManager->KeyIsDown(SDL_SCANCODE_LSHIFT))
{
player_speed *= 0.5f;
}
// Slow time
if (g_pInputManager->KeyIsPressed(SDL_SCANCODE_Z))
{
BaseApplication::time_modifier -= 0.5;
}
// Fast time
if (g_pInputManager->KeyIsPressed(SDL_SCANCODE_X))
{
BaseApplication::time_modifier += 0.5;
}
// Restrict the time slowing effect
BaseApplication::time_modifier = MAX(BaseApplication::time_modifier, 0.5);
BaseApplication::time_modifier = MIN(BaseApplication::time_modifier, 1.0);
// Switch to Lazer
if (g_pInputManager->KeyIsPressed(SDL_SCANCODE_A))
{
auto temp = static_cast<ComponentManager*>(GetOwner())->GetComponent(COMPONENT_TYPE::WEAPONARYSYSTEM);
if (temp)
{
DEBUG_PRINT("Switch to Player_Lazer\n");
auto p_weapon_com = static_cast<WeaponarySystem*>(temp);
p_weapon_com->ChangeWeapon(1, "Lazer");
}
}
// Switch to Kinetic Gun
if (g_pInputManager->KeyIsPressed(SDL_SCANCODE_D))
{
auto temp = static_cast<ComponentManager*>(GetOwner())->GetComponent(COMPONENT_TYPE::WEAPONARYSYSTEM);
if (temp)
{
DEBUG_PRINT("Switch to Player_KineticGun\n");
auto p_weapon_com = static_cast<WeaponarySystem*>(temp);
p_weapon_com->ChangeWeapon(1, "KineticGun");
}
}
// Transformation
{
auto temp = static_cast<ComponentManager*>(GetOwner())->GetComponent(COMPONENT_TYPE::BODY);
auto p_transformCom = static_cast<Component::Body*>(temp);
std::lock_guard<std::mutex> lock(p_transformCom->m_mutex);
// Reset rotation
p_transformCom->m_angle = 0.0f;
// Reset velocity
Vector2DZero(&p_transformCom->m_velocity);
// Modify velocity by player nput
if (g_pInputManager->KeyIsDown(SDL_SCANCODE_UP))
{
Vector2DAdd(&p_transformCom->m_velocity, &p_transformCom->m_velocity, &Vector2D(0.0, -player_speed));
}
if (g_pInputManager->KeyIsDown(SDL_SCANCODE_DOWN))
{
Vector2DAdd(&p_transformCom->m_velocity, &p_transformCom->m_velocity, &Vector2D(0.0, player_speed));
}
if (g_pInputManager->KeyIsDown(SDL_SCANCODE_LEFT))
{
Vector2DAdd(&p_transformCom->m_velocity, &p_transformCom->m_velocity, &Vector2D(-player_speed, 0));
}
if (g_pInputManager->KeyIsDown(SDL_SCANCODE_RIGHT))
{
Vector2DAdd(&p_transformCom->m_velocity, &p_transformCom->m_velocity, &Vector2D(player_speed, 0));
}
// Speed Limit
if (Vector2DSquareLength(&p_transformCom->m_velocity) > player_speed * player_speed)
{
Vector2DNormalize(&p_transformCom->m_velocity, &p_transformCom->m_velocity);
Vector2DScale(&p_transformCom->m_velocity, &p_transformCom->m_velocity, player_speed);
}
// Windows Limit
auto p_App = static_cast<WinSDLOpenGLApplication*>(g_pBaseApplication.get());
auto temp_sprite = static_cast<ComponentManager*>(GetOwner())->GetComponent(COMPONENT_TYPE::SPRITE);
if (temp_sprite && p_App)
{
auto sprite_com = static_cast<Component::Sprite*>(temp_sprite);
int SCREEN_WIDTH, SCREEN_HEIGHT, SPRITE_W, SPRITE_H;
SDL_GetWindowSize(p_App->GetWindow(), &SCREEN_WIDTH, &SCREEN_HEIGHT);
SPRITE_W = sprite_com->m_rcSprite.w;
SPRITE_H = sprite_com->m_rcSprite.h;
/* collide with edges of screen */
if (sprite_com->m_rcSprite.x < 0) {
sprite_com->m_rcSprite.x = 0;
p_transformCom->m_position.x = static_cast<float>(sprite_com->m_rcSprite.x + SPRITE_W / 2);
}
else if (sprite_com->m_rcSprite.x > SCREEN_WIDTH - SPRITE_W) {
sprite_com->m_rcSprite.x = SCREEN_WIDTH - SPRITE_W;
p_transformCom->m_position.x = static_cast<float>(sprite_com->m_rcSprite.x + SPRITE_W / 2);
}
if (sprite_com->m_rcSprite.y < 0) {
sprite_com->m_rcSprite.y = 0;
p_transformCom->m_position.y = static_cast<float>(sprite_com->m_rcSprite.y + SPRITE_H / 2);
}
else if (sprite_com->m_rcSprite.y > SCREEN_HEIGHT - SPRITE_H) {
sprite_com->m_rcSprite.y = SCREEN_HEIGHT - SPRITE_H;
p_transformCom->m_position.y = static_cast<float>(sprite_com->m_rcSprite.y + SPRITE_H / 2);
}
}
}
}
}
void My::Component::PlayerController::Serialize(std::wostream& wostream)
{
wostream << "[Component : PlayerController] ";
}
<file_sep>/GameEngine/Common/Component/Interface/IComponent.hpp
#pragma once
#include <string>
#include <fstream>
#include "ComponentType.h"
#include "Common/MemoryPool.hpp"
/**
Comment :
To create a custom component
1. Add a new element to the enum type in the component type header
2. Create a derived class which inherits from IComponent
3. Create a derived class which inherits from IIComponentCreator
4. RegisterSerialization in your initializer
5. RegisterCreator in your initializer
*/
namespace My
{
class ComponentManager;
class IComponent
{
public:
explicit IComponent(COMPONENT_TYPE type, void* owner, std::string name) noexcept;;
virtual ~IComponent();
virtual void Update(double deltaTime) = 0;
virtual void Serialize(std::ifstream& fstream);
virtual void Serialize(std::wostream& wostream) = 0;
COMPONENT_TYPE GetType() noexcept;;
void SetName(std::string name) noexcept;
const std::string& GetName() const noexcept;
void* GetOwner() const noexcept;;
bool IsActive() noexcept;
void SetActive(bool v) noexcept;
friend ComponentManager;
private:
void SetOwner(void* owner) noexcept;;
private:
COMPONENT_TYPE m_type;
std::string m_name;
void* m_owner;
bool m_active;
};
class IComponentCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IComponent* Create(void* owner, MemoryPool* pool, std::string name = "_com") = 0;
};
// TODO : Initialize in your application
extern std::map<std::string, COMPONENT_TYPE> g_componentSerializationMap;
extern std::map<COMPONENT_TYPE, std::shared_ptr<IComponentCreator>> g_componentCreatorMap;
}<file_sep>/GameEngine/Common/Geommath/Shape/Shape.cpp
#include "Shape.hpp"
#include "Common/Utility/Utility.hpp"
My::Collision::Shape::Shape(SHAPE_TYPE type, void* owner)
:
m_type(type), m_owner(owner), m_active(true)
{
}
My::Collision::Shape::~Shape() {}
My::SHAPE_TYPE My::Collision::Shape::GetType() const noexcept
{
return m_type;
}
void My::Collision::Shape::SetOwner(void* owner) noexcept
{
m_owner = owner;
}
void* My::Collision::Shape::GetOwner() const noexcept
{
return m_owner;
}
bool My::Collision::Shape::IsActive() const noexcept
{
return m_active;
}
void My::Collision::Shape::SetActive(bool v) noexcept
{
m_active = v;
}
My::Collision::Circle::Circle(void* owner)
:
Shape(SHAPE_TYPE::CIRCLE, owner), m_radius(0.0f)
{
}
void My::Collision::Circle::Serialize(std::ifstream& fstream)
{
std::string line; getline(fstream, line);
{
if (1 == sscanf_s(line.c_str(), "r %f", &m_radius))
{
return;
}
else
{
print_fstream(fstream);
std::string msg("Shape serialization has failed without providing a valid form for radius: r ~.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
My::Collision::Rectangle::Rectangle(void* owner)
:
Shape(SHAPE_TYPE::RECTANGLE, owner), m_width(0.0f), m_height(0.0f)
{
}
void My::Collision::Rectangle::Serialize(std::ifstream& fstream)
{
std::string line; getline(fstream, line);
{
if (2 == sscanf_s(line.c_str(), "w %f h %f", &m_width, &m_height))
{
return;
}
else
{
print_fstream(fstream);
std::string msg("Shape serialization has failed without providing a valid form for radius: w ~ h ~.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
<file_sep>/CS529_Game/src/Entity/Gameplay/Weapon/MissileBullet.hpp
#pragma once
#include "Common/Event/Event.hpp"
#include "src/Entity/Gameplay/Interface/IWeapon.hpp"
#include "src/Event/MyEvent.hpp"
namespace My
{
namespace Entity
{
class MissleBullet : public IWeapon
{
public:
MissleBullet() = delete;
explicit MissleBullet(void* owner, std::string name) noexcept : IWeapon(WEAPON_TYPE::WEAPON_MISSILE_BULLET, owner, name)
{
m_eventManager.AddEventRegistry(EventType::ON_COMPONENTHIT);
}
virtual int Tick(double deltaTime) override;
virtual int Draw() override;
virtual void HandleEvent(std::weak_ptr<Event> e) override
{
std::shared_ptr<Event> _e = e.lock();
switch (_e->GetType())
{
case EventType::ON_COMPONENTHIT:
OnComponentHit(_e);
break;
default:
break;
}
}
/*
Hitting UFO:
Shrink the MissleBullet to the colliding object
*/
void OnComponentHit(std::weak_ptr<Event> e);
};
}
class MissleBulletObjectCreator : public IWeaponCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IWeapon* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "MissleBullet0") override
{
if (pool)
{
return pool->New<Entity::MissleBullet>(owner, name);
}
else
{
return new Entity::MissleBullet(owner, name);
}
}
};
}<file_sep>/GameEngine/Common/AudioManager.cpp
#include "AudioManager.hpp"
My::AudioManager::AudioManager() noexcept
{
}
int My::AudioManager::Initialize()
{
return 0;
}
int My::AudioManager::Tick(double deltaTime)
{
return 0;
}
int My::AudioManager::Finalize()
{
return 0;
}
<file_sep>/CS529_Game/src/Entity/Gameplay/Pack/Pack_Upgrade.hpp
#pragma once
#include "src/Entity/Gameplay/Interface/IMyGameObject.hpp"
#include "src/Event/MyEvent.hpp"
namespace My
{
namespace Entity
{
class Pack_Upgrade : public IMyGameObject
{
public:
Pack_Upgrade() = delete;
explicit Pack_Upgrade(void* owner, std::string name) noexcept
:
IMyGameObject(MYGAMEOBJECT_TYPE::Item_UPGRADE, owner, name),
life_time(PACK_LIFETIME)
{
m_eventManager.AddEventRegistry(EventType::ON_COMPONENTHIT);
}
virtual int Tick(double deltaTime) override;
virtual int Draw() override;
virtual void HandleEvent(std::weak_ptr<Event> e)
{
if (IsActive())
{
std::shared_ptr<Event> _e = e.lock();
switch (_e->GetType())
{
case EventType::ON_COMPONENTHIT:
OnComponentHit(_e);
break;
default:
break;
}
}
}
void OnComponentHit(std::weak_ptr<Event> e);
private:
double life_time;
};
}
class Pack_UpgradeObjectCreator : public IMyGameObjectCreator
{
public:
/* (Optional) Using a custom memory pool to create a allocated space */
virtual IMyGameObject* Create(void* owner = nullptr, MemoryManager* pool = nullptr, std::string name = "Pack_Upgrade0") override
{
if (pool)
{
return pool->New<Entity::Pack_Upgrade>(owner, name);
}
else
{
return new Entity::Pack_Upgrade(owner, name);
}
}
};
}<file_sep>/GameEngine/Common/Component/ComponentManager.cpp
#include "ComponentManager.hpp"
My::ComponentManager::ComponentManager() noexcept
:
m_owner(nullptr)
{
}
int My::ComponentManager::Initialize()
{
return 0;
}
int My::ComponentManager::Tick(double deltaTime)
{
#if MEMORY_POOL_OPT
for (auto& com : m_pool.GetBookKeeper())
{
reinterpret_cast<IComponent*>(com)->Update(deltaTime);
}
#else
for (auto& com : m_components)
{
com->Update(deltaTime);
}
#endif
return 0;
}
int My::ComponentManager::Finalize()
{
return 0;
}
void My::ComponentManager::Serialize(std::wostream& wostream)
{
#if MEMORY_POOL_OPT
for (auto& com : m_pool.GetBookKeeper())
{
reinterpret_cast<IComponent*>(com)->Serialize(wostream);
}
#else
for (auto& com : m_components)
{
com->->Serialize(wostream);
}
#endif
}
/**
* \brief AddComponent: add newly allocated component to the component manager.
*
* Set the ownership of that component to this component manager.
* \author <NAME>
* \date 10/21/2019
* \return void.
* \exception None.
* @param com IComponent pointer.
*/
My::IComponent* My::ComponentManager::AddComponent(COMPONENT_TYPE type)
{
IComponent* com;
if (com = GetComponent(type))
{
return com;
}
#if MEMORY_POOL_OPT
com = g_componentCreatorMap[type]->Create(this,&m_pool);
#else
com = g_componentCreatorMap[type]->Create(this);
m_components.push_back(std::shared_ptr<IComponent>(com));
#endif
return com;
}
/**
* \brief GetComponent: return component with a specified type
* \author <NAME>
* \date 10/21/2019
* \return nullptr if such type does not exist.
* \exception None.
* @param type COMPONENT_TYPE enumerator.
*/
My::IComponent* My::ComponentManager::GetComponent(COMPONENT_TYPE type)
{
#if MEMORY_POOL_OPT
for (auto com : m_pool.GetBookKeeper())
{
if (com == nullptr)
{
return nullptr;
}
else if (reinterpret_cast<IComponent*>(com)->GetType() == type)
{
return reinterpret_cast<IComponent*>(com);
}
}
#else
for (auto com : m_components)
{
if (com == nullptr)
{
return nullptr;
}
else if (com->GetType() == type)
{
return com.get();
}
}
#endif
return nullptr;
}
void* My::ComponentManager::GetOwner() noexcept
{
return m_owner;
}
void My::ComponentManager::SetOwner(void* owner) noexcept
{
m_owner = owner;
}<file_sep>/CS529_Game/src/Entity/Gameplay/Interface/MyObjectType.hpp
#pragma once
#include <string>
#include <map>
#include <memory>
#include "Common/Geommath/2D/Math.hpp"
// Player
#define COLLISION_HP_REDUCE 2.0f
#define PLAYER_HP_RESTORE 100.0f
#define PLAYER_LOCKHP_PERIOD 4.0
#define MAX_WEAPON_LVL 3
#define WINNING_HEAD_COUNT 3+3+3+5+6+6+1+6+6+3+3
// Pack life time
#define PACK_LIFETIME 6.0
// Pack drop index
#define PACK_HP_INDEX 1
#define PACK_UPGRADE_INDEX 2
#define PACK_SHIELD_INDEX 3
// Pack drop threshold
#define PACK_HP_THRESHOLD .1
#define PACK_UPGRADE_THRESHOLD .2
#define PACK_SHIELD_THRESHOLD .3
namespace My
{
enum class MYGAMEOBJECT_TYPE
{
BACKGROUND = 0,
PLAYER,
UFO,
MINIBOSS,
BOSS,
Item_HP,
Item_SHIELD,
Item_UPGRADE,
WEAPON,
UI_Button,
UI_Volume_Button,
NUM
};
}
<file_sep>/GameEngine/Common/AudioManager.hpp
#pragma once
#include "Interface/IRunTimeModule.hpp"
namespace My
{
class AudioManager : public IRunTimeModule
{
public:
AudioManager() noexcept;
AudioManager(const AudioManager&) = delete;
AudioManager& operator=(const AudioManager&) = delete;
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
};
}<file_sep>/CS529_Game/src/Platform/Win32_SDL/WinSDLInputManager.cpp
#include "WinSDLInputManager.hpp"
My::WinSDLInputManager::WinSDLInputManager() noexcept
:
m_current_keyboard_state(nullptr),
m_previous_keyboard_state(nullptr),
keyboard_state(nullptr)
{
}
int My::WinSDLInputManager::Initialize()
{
int size = 1024;
m_previous_keyboard_state = new Uint8[size];
m_current_keyboard_state = new Uint8[size];
return 0;
}
int My::WinSDLInputManager::Tick(double deltaTime)
{
int size = 1024;
keyboard_state = SDL_GetKeyboardState(&size);
memcpy(m_previous_keyboard_state, m_current_keyboard_state, size);
memcpy(m_current_keyboard_state, keyboard_state, size);
IRunTimeModule::Tick(deltaTime); // Execute additional callback functions added to the input manager.
return 0;
}
int My::WinSDLInputManager::Finalize()
{
delete[] m_previous_keyboard_state;
delete[] m_current_keyboard_state;
return 0;
}
int My::WinSDLInputManager::KeyIsPressed(int KeyScanCode) noexcept
{
return (m_previous_keyboard_state[KeyScanCode] != 1 && m_current_keyboard_state[KeyScanCode] == 1) ? 1 : 0;
}
int My::WinSDLInputManager::KeyIsReleased(int KeyScanCode) noexcept
{
return (m_previous_keyboard_state[KeyScanCode] == 1 && m_current_keyboard_state[KeyScanCode] != 1) ? 1 : 0;
}
int My::WinSDLInputManager::KeyIsDown(int KeyScanCode) noexcept
{
return (m_current_keyboard_state[KeyScanCode] == 1) ? 1 : 0;
}
<file_sep>/CS529_Game/src/Entity/Gameplay/Interface/IMyGameObject.cpp
#include "IMyGameObject.hpp"
My::IMyGameObject::IMyGameObject(MYGAMEOBJECT_TYPE type, void* owner, std::string name) noexcept
:
IGameObject(GAMEOBJECT_TYPE::CUSTOM_GAME, owner, name),
m_type(type)
{}
My::MYGAMEOBJECT_TYPE My::IMyGameObject::GetType() const noexcept
{
return m_type;
}
<file_sep>/GameEngine/Common/Geommath/2D/Matrix2D.hpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: Matrix2D
Purpose: header file of Matrix2D
Language: c++ 11
Platform: win32 x86
Project: CS529_project_2
Author: <NAME> hang.yu 60001119
Creation date: 10/03/2019
- End Header ----------------------------*/
#pragma once
#include "Math.hpp"
#include "Vector2D.hpp"
namespace My {
typedef struct Matrix2D
{
float m[3][3];
}Matrix2D;
/*
This function sets the matrix Result to the identity matrix
*/
void Matrix2DIdentity(Matrix2D* pResult);
/*
This functions calculated the transpose matrix of Mtx and saves it in Result
*/
void Matrix2DTranspose(Matrix2D* pResult, Matrix2D* pMtx);
/*
This function multiplies Mtx0 with Mtx1 and saves the result in Result
Result = Mtx0*Mtx1
*/
void Matrix2DConcat(Matrix2D* pResult, Matrix2D* pMtx0, Matrix2D* pMtx1);
void Matrix2DConcat(Matrix2D* pResult, const Matrix2D* pMtx0, const Matrix2D* pMtx1);
/*
This function creates a translation matrix from x & y and saves it in Result
*/
void Matrix2DTranslate(Matrix2D* pResult, float x, float y);
/*
This function creates a scaling matrix from x & y and saves it in Result
*/
void Matrix2DScale(Matrix2D* pResult, float x, float y);
/*
This matrix creates a rotation matrix from "Angle" whose value is in degree.
Save the resultant matrix in Result
*/
void Matrix2DRotDeg(Matrix2D* pResult, float Angle);
/*
This matrix creates a rotation matrix from "Angle" whose value is in radian.
Save the resultant matrix in Result
*/
void Matrix2DRotRad(Matrix2D* pResult, float Angle);
/*
This function multiplies the matrix Mtx with the vector Vec and saves the result in Result
Result = Mtx * Vec
*/
void Matrix2DMultVec(Vector2D* pResult, Matrix2D* pMtx, Vector2D* pVec);
void Matrix2DMultVec(Vector2D* pResult, const Matrix2D* pMtx, const Vector2D* pVec);
}
My::Matrix2D operator*(const My::Matrix2D& mat1, const My::Matrix2D& mat2);
My::Vector2D operator*(const My::Matrix2D& mat1, const My::Vector2D& mat2);<file_sep>/GameEngine/Common/GraphicsManager.hpp
#pragma once
#include "Interface/IRunTimeModule.hpp"
namespace My
{
class GraphicsManager : public IRunTimeModule
{
public:
GraphicsManager() noexcept;
GraphicsManager(const GraphicsManager&) = delete;
GraphicsManager& operator=(const GraphicsManager&) = delete;
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
};
}<file_sep>/GameEngine/Common/Component/Interface/ComponentType.h
#pragma once
#include <string>
#include <map>
#include <memory>
namespace My
{
enum class COMPONENT_TYPE
{
SPRITE=0,
SCENECOMPONENT,
TRANSFORM,
BODY = TRANSFORM,
PLAYERCONTROLLER,
AICONTROLLER,
PACKCONTROLLER,
HEALTHPOINT,
WEAPONARYSYSTEM,
NUM
};
}<file_sep>/GameEngine/Common/Geommath/2D/Math2D.cpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: Math2D
Purpose: implementation of Math2D
Language: c++ 11
Platform: win32 x86
Project: CS529_project_2
Author: <NAME> hang.yu 60001119
Creation date: 10/03/2019
- End Header ----------------------------*/
#include "Math2D.hpp"
/*
This function checks if the point P is colliding with the circle whose
center is "Center" and radius is "Radius"
*/
int My::StaticPointToStaticCircle(Vector2D *pP, Vector2D *pCenter, float Radius)
{
if (pP && pCenter && Radius > 0.0f)
{
return (Vector2DSquareDistance(pP, pCenter) <= powf(Radius, 2)) ? 1 : 0;
}
else
{
return 0;
}
}
/*
This function checks if the point Pos is colliding with the rectangle
whose center is Rect, width is "Width" and height is Height
*/
int My::StaticPointToStaticRect(Vector2D *pPos, Vector2D *pRect, float Width, float Height)
{
if (pPos && pRect && Width > 0.0f && Height > 0.0f)
{
Vector2D vec;
Vector2DSub(&vec, pPos, pRect);
return (fabs(vec.x) <= (Width / 2.0f) && fabs(vec.y) <= (Height / 2.0f)) ? 1 : 0;
}
else
{
return 0;
}
}
/*
This function checks for collision between 2 circles.
Circle0: Center is Center0, radius is "Radius0"
Circle1: Center is Center1, radius is "Radius1"
*/
int My::StaticCircleToStaticCircle(Vector2D *pCenter0, float Radius0, Vector2D *pCenter1, float Radius1)
{
if (pCenter0 && pCenter1 && Radius0 > 0.0f && Radius1 > 0.0f)
{
return (Vector2DSquareDistance(pCenter0, pCenter1) <= powf(Radius0 + Radius1, 2)) ? 1 : 0;
}
else
{
return 0;
}
}
/*
This functions checks if 2 rectangles are colliding
Rectangle0: Center is pRect0, width is "Width0" and height is "Height0"
Rectangle1: Center is pRect1, width is "Width1" and height is "Height1"
*/
int My::StaticRectToStaticRect(Vector2D *pRect0, float Width0, float Height0, Vector2D *pRect1, float Width1, float Height1)
{
if (pRect0 && pRect1 && Width0 > 0.0f && Height0 > 0.0f && Width1 > 0.0f && Height1 > 0.0f)
{
Vector2D vec;
Vector2DSub(&vec, pRect0, pRect1);
return (fabs(vec.x) <= ((Width0 + Width1) / 2.0f) && fabs(vec.y) <= ((Height0 + Height1) / 2.0f)) ? 1 : 0;
}
else
{
return 0;
}
}
//////////////////////
// New to project 2 //
//////////////////////
/*
This function determines the distance separating a point from a line
- Parameters
- P: The point whose location should be determined
- LS: The line segment
- Returned value: The distance. Note that the returned value should be:
- Negative if the point is in the line's inside half plane
- Positive if the point is in the line's outside half plane
- Zero if the point is on the line
*/
float My::StaticPointToStaticLineSegment(Vector2D* P, LineSegment2D* LS)
{
return (P && LS) ? Vector2DDotProduct(&(LS->mN), P) - LS->mNdotP0 : -F_UNDEFINE;
}
/*
This function checks whether an animated point is colliding with a line segment
- Parameters
- Ps: The point's starting location
- Pe: The point's ending location
- LS: The line segment
- Pi: This will be used to store the intersection point's coordinates (In case there's an intersection)
- Returned value: Intersection time t
- -1.0f: If there's no intersection
- Intersection time: If there's an intersection
*/
float My::AnimatedPointToStaticLineSegment(Vector2D* Ps, Vector2D* Pe, LineSegment2D* LS, Vector2D* Pi)
{
if (Ps && Pe && LS && Pi)
{
float t, dot;
Vector2D v;
Vector2DSub(&v, Pe, Ps);
dot = Vector2DDotProduct(&(LS->mN), &v);
if (dot != 0.0f) // Parallel line
{
t = (LS->mNdotP0 - Vector2DDotProduct(&(LS->mN), Ps)) / dot;
if (t >= 0.0f && t <= 1.0f) // Intersection is on the line segment of [Ps, Pe]
{
Vector2D Pi_P1;
Vector2D P0_P1;
Vector2D Pi_P0;
Vector2D P1_P0;
Vector2DScaleAdd(Pi, &v, Ps, t);
Vector2DSub(&Pi_P1, Pi, &(LS->mP1));
Vector2DSub(&P0_P1, &(LS->mP0), &(LS->mP1));
Vector2DSub(&Pi_P0, Pi, &(LS->mP0));
Vector2DSub(&P1_P0, &(LS->mP1), &(LS->mP0));
if (Vector2DDotProduct(&Pi_P1, &P0_P1) >= 0.0f && Vector2DDotProduct(&Pi_P0, &P1_P0) >= 0.0f) // Intersection is on the line segment of LS
{
return t;
}
else
{
return -1.0f;
}
}
else
{
return -1.0f;
}
}
else
{
return -1.0f;
}
}
else
{
return -F_UNDEFINE;
}
}
/*
This function checks whether an animated circle is colliding with a line segment
- Parameters
- Ps: The center's starting location
- Pe: The center's ending location
- Radius: The circle's radius
- LS: The line segment
- Pi: This will be used to store the intersection point's coordinates (In case there's an intersection)
- Returned value: Intersection time t
- -1.0f: If there's no intersection
- Intersection time: If there's an intersection
*/
float My::AnimatedCircleToStaticLineSegment(Vector2D* Ps, Vector2D* Pe, float Radius, LineSegment2D* LS, Vector2D* Pi)
{
if (Ps && Pe && LS && Pi && Radius > 0.0f)
{
float D = StaticPointToStaticLineSegment(Ps, LS);
if (D > 0) // Ps is outside
{
D = Radius;
}
else // Ps is inside
{
D = -Radius;
}
float t, dot;
Vector2D v;
Vector2DSub(&v, Pe, Ps);
dot = Vector2DDotProduct(&(LS->mN), &v);
if (dot != 0.0f) // Parallel line
{
t = (LS->mNdotP0 - Vector2DDotProduct(&(LS->mN), Ps) + D) / dot;
if (t >= 0.0f && t <= 1.0f) // Intersection is on the line segment of [Ps, Pe]
{
Vector2D Pi_P1;
Vector2D P0_P1;
Vector2D Pi_P0;
Vector2D P1_P0;
Vector2DScaleAdd(Pi, &v, Ps, t);
Vector2DSub(&Pi_P1, Pi, &(LS->mP1));
Vector2DSub(&P0_P1, &(LS->mP0), &(LS->mP1));
Vector2DSub(&Pi_P0, Pi, &(LS->mP0));
Vector2DSub(&P1_P0, &(LS->mP1), &(LS->mP0));
if (Vector2DDotProduct(&Pi_P1, &P0_P1) >= 0.0f && Vector2DDotProduct(&Pi_P0, &P1_P0) >= 0.0f) // Intersection is on the line segment of LS
{
return t;
}
else // TODO(Don't know how?): Need to handle the case where the circle hit the start or end point of the line segment.
{
return -1.0f;
}
}
else
{
return -1.0f;
}
}
else
{
return -1.0f; // TODO(Don't know how?): Need to handle the case the distance between the center of the circle and the line segement is samller than the circle radius.
}
}
else
{
return -F_UNDEFINE;
}
}
/*
This function reflects an animated point on a line segment.
It should first make sure that the animated point is intersecting with the line
- Parameters
- Ps: The point's starting location
- Pe: The point's ending location
- LS: The line segment
- Pi: This will be used to store the intersection point's coordinates (In case there's an intersection)
- R: Reflected vector R
- Returned value: Intersection time t
- -1.0f: If there's no intersection
- Intersection time: If there's an intersection
*/
float My::ReflectAnimatedPointOnStaticLineSegment(Vector2D* Ps, Vector2D* Pe, LineSegment2D* LS, Vector2D* Pi, Vector2D* R)
{
float t = AnimatedPointToStaticLineSegment(Ps, Pe, LS, Pi);
if (t >= 0.0f) // Intersection success
{
if (R)
{
Vector2D i;
Vector2DSub(&i, Pe, Pi); // i = Pe - Pi
Vector2DScaleAdd(R, &(LS->mN), &i, -2 * Vector2DDotProduct(&i, &(LS->mN))); // R = i - 2 (N dot i) N
return t;
}
else
{
return -1.0f;
}
}
else
{
return t;
}
}
/*
This function reflects an animated circle on a line segment.
It should first make sure that the animated point is intersecting with the line
- Parameters
- Ps: The center's starting location
- Pe: The center's ending location
- Radius: The circle's radius
- LS: The line segment
- Pi: This will be used to store the intersection point's coordinates (In case there's an intersection)
- R: Reflected vector R
- Returned value: Intersection time t
- -1.0f: If there's no intersection
- Intersection time: If there's an intersection
*/
float My::ReflectAnimatedCircleOnStaticLineSegment(Vector2D* Ps, Vector2D* Pe, float Radius, LineSegment2D* LS, Vector2D* Pi, Vector2D* R)
{
float t = AnimatedCircleToStaticLineSegment(Ps, Pe, Radius, LS, Pi);
if (t >= 0.0f) // Intersection success
{
if (R)
{
Vector2D i;
Vector2DSub(&i, Pe, Pi); // i = Pe - Pi
Vector2DScaleAdd(R, &(LS->mN), &i, -2 * Vector2DDotProduct(&i, &(LS->mN))); // R = i - 2 (N dot i) N
return t;
}
else
{
return -1.0f;
}
}
else
{
return t;
}
}
/*
This function checks whether an animated point is colliding with a static circle
- Parameters
- Ps: The point's starting location
- Pe: The point's ending location
- Center: The circle's center
- Radius: The circle's radius
- Pi: This will be used to store the intersection point's coordinates (In case there's an intersection)
- Returned value: Intersection time t
- -1.0f: If there's no intersection
- Intersection time: If there's an intersection
*/
float My::AnimatedPointToStaticCircle(Vector2D* Ps, Vector2D* Pe, Vector2D* Center, float Radius, Vector2D* Pi)
{
if (Ps && Pe && Center && Radius > 0.0f && Pi)
{
LineSegment2D LS;
float n, m, v_len_inv;
Vector2D v;
Vector2D Ps_Center;
BuildLineSegment2D(&LS, Ps, Pe);
Vector2DSub(&v, Pe, Ps);
Vector2DSub(&Ps_Center, Center, Ps);
v_len_inv = 1.0f / Vector2DLength(&v);
m = Vector2DDotProduct(&v, &Ps_Center) * v_len_inv;
n = Vector2DSquareLength(&Ps_Center) - powf(m, 2);
if (n <= powf(Radius,2) && !(m < 0.0f && Vector2DSquareLength(&Ps_Center) > powf(Radius,2)))
{
float s = sqrtf(powf(Radius, 2) - n);
float t = (m - s) * v_len_inv;
if (t >= 0.0f && t <= 1.0f)
{
Vector2DScaleAdd(Pi, &v, Ps, t);
return t;
}
else
{
return -1.0f;
}
}
else
{
return -1.0f;
}
}
else
{
return -1.0f;
}
}
/*
This function reflects an animated point on a static circle.
It should first make sure that the animated point is intersecting with the circle
- Parameters
- Ps: The point's starting location
- Pe: The point's ending location
- Center: The circle's center
- Radius: The circle's radius
- Pi: This will be used to store the intersection point's coordinates (In case there's an intersection)
- R: Reflected vector R
- Returned value: Intersection time t
- -1.0f: If there's no intersection
- Intersection time: If there's an intersection
*/
float My::ReflectAnimatedPointOnStaticCircle(Vector2D* Ps, Vector2D* Pe, Vector2D* Center, float Radius, Vector2D* Pi, Vector2D* R)
{
float t = AnimatedPointToStaticCircle(Ps, Pe, Center, Radius, Pi);
if (t >= 0.0f && t <= 1.0f && R)
{
Vector2D n, m;
Vector2DSub(&n, Pi, Center);
Vector2DNormalize(&n, &n);
Vector2DSub(&m, Ps, Pi);
Vector2DScale(&n, &n, 2 * Vector2DDotProduct(&m, &n));
Vector2DSub(R, &n, &m);
return t;
}
else
{
return -1.0f;
}
}
/*
This function checks whether an animated circle is colliding with a static circle
- Parameters
- Center0s: The starting position of the animated circle's center
- Center0e: The ending position of the animated circle's center
- Radius0: The animated circle's radius
- Center1: The static circle's center
- Radius1: The static circle's radius
- Pi: This will be used to store the intersection point's coordinates (In case there's an intersection)
- Returned value: Intersection time t
- -1.0f: If there's no intersection
- Intersection time: If there's an intersection
*/
float My::AnimatedCircleToStaticCircle(Vector2D* Center0s, Vector2D* Center0e, float Radius0, Vector2D* Center1, float Radius1, Vector2D* Pi)
{
return AnimatedPointToStaticCircle(Center0s, Center0e, Center1, Radius0 + Radius1, Pi);
}
/*
This function reflects an animated circle on a static circle.
It should first make sure that the animated circle is intersecting with the static one
- Parameters
- Center0s: The starting position of the animated circle's center
- Center0e: The ending position of the animated circle's center
- Radius0: The animated circle's radius
- Center1: The static circle's center
- Radius1: The static circle's radius
- Pi: This will be used to store the intersection point's coordinates (In case there's an intersection)
- R: Reflected vector R
- Returned value: Intersection time t
- -1.0f: If there's no intersection
- Intersection time: If there's an intersection
*/
float My::ReflectAnimatedCircleOnStaticCircle(Vector2D* Center0s, Vector2D* Center0e, float Radius0, Vector2D* Center1, float Radius1, Vector2D* Pi, Vector2D* R)
{
return ReflectAnimatedPointOnStaticCircle(Center0s, Center0e, Center1, Radius0 + Radius1, Pi, R);
}
<file_sep>/CS529_Game/src/Entity/Gameplay/Objects/UFO.cpp
#include "UFO.hpp"
#include "Common/Event/EventDispatcher.hpp"
#include "Common/Component/Physics/Body.hpp"
#include "src/Component/Graphics/Sprite.hpp"
#include "src/Component/Graphics/SceneComponent.hpp"
#include "src/Component/Gameplay/HealthPoint.hpp"
#include "src/Component/Logic/AIController.hpp"
#include "src/Entity/Gameplay/Interface/IWeapon.hpp"
#include "src/Platform/Win32_SDL/WinSDLAudioManager.hpp"
#include "src/Entity/Gameplay/Pack/Pack_HP.hpp"
#include "src/Entity/Gameplay/Pack/Pack_Shield.hpp"
#include "src/Entity/Gameplay/Pack/Pack_Upgrade.hpp"
#include "src/Entity/Gameplay/Pack/Pack_Score.hpp"
#include "src/SerializedLoader.hpp"
int My::Entity::UFO::Tick(double deltaTime)
{
auto hp_com = static_cast<Component::HealthPoint*>(GetComponent(COMPONENT_TYPE::HEALTHPOINT));
if (hp_com->IsDeplited())
{
// Send death event
auto death = std::make_shared<Events::DeathEvent>(this);
if (auto player = g_pGameObjectResourceManager->GetResourceByName("002_Player"))
{
death->AddSubscriber(player);
g_pEventDispatcher->DispatchToSubscribers(-1.0, death);
}
// Deactivate object (the gameObjectResourceManager will do gc)
SetGCToTrue();
// Play destory sound effect
g_pAudioManager->PlayChunck("Blast");
DropPack();
}
IMyGameObject::Tick(deltaTime);
return 0;
}
int My::Entity::UFO::Draw()
{
auto temp = GetComponent(COMPONENT_TYPE::SCENECOMPONENT);
if (temp)
{
static_cast<Component::SceneComponent*>(temp)->Draw();
return 0;
}
return 1;
}
void My::Entity::UFO::OnComponentHit(std::weak_ptr<Event> e)
{
std::shared_ptr<Event> _e = e.lock();
auto event = static_cast<Events::ComponentHitEvent*>(_e.get());
auto other = static_cast<IMyGameObject*>(event->other);
if (other->GetType() != MYGAMEOBJECT_TYPE::UFO)
{
static_cast<Component::Sprite*>(GetComponent(COMPONENT_TYPE::SPRITE))->StartHitFlash();
// damage to UFO
{
auto hp_com = static_cast<Component::HealthPoint*>(GetComponent(COMPONENT_TYPE::HEALTHPOINT));
std::lock_guard<std::mutex> lock1(hp_com->m_mutex);
hp_com->Reduce(COLLISION_HP_REDUCE);
}
}
}
void My::Entity::UFO::OnSwitchFireMode(std::weak_ptr<Event> e)
{
std::shared_ptr<Event> _e = e.lock();
auto event = static_cast<Events::AISwitchFireModeEvent*>(_e.get());
static_cast<Component::AIController*>(GetComponent(COMPONENT_TYPE::AICONTROLLER))->SetFireMode(event->mode);
static_cast<Component::AIController*>(GetComponent(COMPONENT_TYPE::AICONTROLLER))->switched_event_sent = false;
DEBUG_PRINT("UFO switches fire mode to: " + Str(event->mode) + "\n");
}
void My::Entity::UFO::DropPack()
{
for (int i = 0; i < m_drop_list.size() ; ++i)
{
std::string drop_name;
switch (m_drop_list[i])
{
case 0:
continue;
break;
case PACK_HP_INDEX:
drop_name = "Pack_HP";
break;
case PACK_UPGRADE_INDEX:
drop_name = "Pack_Upgrade";
break;
case PACK_SHIELD_INDEX:
drop_name = "Pack_Shield";
break;
default:
break;
}
// Serialize the game object and set its owner to be the root object.
if (g_myGameObjectSerializationMap.find(drop_name) != g_myGameObjectSerializationMap.end())
{
auto pNewObject = LoadIGameObjectFromFile(drop_name.c_str(), m_name + drop_name + Str(i));
// Add game object under the resource manager.
if (1 == g_pGameObjectResourceManager->AddResource(pNewObject, pNewObject->GetName()))
{
std::string msg("Adding resource : '" + std::string(drop_name) + "' has failed.");
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
auto p_new_transformCom = static_cast<Component::Body*>(pNewObject->GetComponent(COMPONENT_TYPE::BODY));
auto p_transformCom = static_cast<Component::Body*>(GetComponent(COMPONENT_TYPE::BODY));
{
std::lock_guard<std::mutex> lock1(p_transformCom->m_mutex);
std::lock_guard<std::mutex> lock2(p_new_transformCom->m_mutex);
Vector2DSet(&p_new_transformCom->m_position, &p_transformCom->m_position);
}
}
else
{
std::string msg("File does not provide a valid game object of type: " + std::string(drop_name));
throw EngineException(_CRT_WIDE(__FILE__), __LINE__, My::str2wstr(msg));
}
}
}
<file_sep>/GameEngine/Common/Component/Interface/IComponent.cpp
#include "IComponent.hpp"
My::IComponent::IComponent(COMPONENT_TYPE type, void* owner, std::string name) noexcept : m_type(type), m_owner(owner), m_active(true), m_name(name) {}
My::IComponent::~IComponent() {}
void My::IComponent::Serialize(std::ifstream& fstream)
{
for (std::string line; getline(fstream, line);)
{
if (line[0] == ']')
return;
}
}
My::COMPONENT_TYPE My::IComponent::GetType() noexcept { return m_type; }
void My::IComponent::SetName(std::string name) noexcept
{
m_name = name;
}
const std::string& My::IComponent::GetName() const noexcept
{
return m_name;
}
void* My::IComponent::GetOwner() const noexcept { return m_owner; }
bool My::IComponent::IsActive() noexcept { return m_active; }
void My::IComponent::SetActive(bool v) noexcept { m_active = v; }
void My::IComponent::SetOwner(void* owner) noexcept { m_owner = owner; }<file_sep>/CS529_Game/src/Entity/Gameplay/Objects/Player.cpp
#include "Player.hpp"
#include "Common/Utility/Utility.hpp"
#include "Common/BaseApplication.hpp"
#include "Common/Event/EventDispatcher.hpp"
#include "src/Component/Graphics/Sprite.hpp"
#include "src/Component/Graphics/SceneComponent.hpp"
#include "src/Component/Gameplay/HealthPoint.hpp"
#include "src/Component/Gameplay/WeaponarySystem.hpp"
#include "src/SceneManager.hpp"
int My::Entity::Player::Tick(double deltaTime)
{
auto hp_com = static_cast<Component::HealthPoint*>(GetComponent(COMPONENT_TYPE::HEALTHPOINT));
if (hp_com->IsDeplited())
{
// Deactivate object (the gameObjectResourceManager will do gc)
SetGCToTrue();
m_callBacks["Defeat"]();
}
IMyGameObject::Tick(deltaTime);
return 0;
}
int My::Entity::Player::Draw()
{
if (auto sceneCom = m_componentManager.GetComponent(COMPONENT_TYPE::SCENECOMPONENT))
{
static_cast<Component::SceneComponent*>(sceneCom)->Draw();
}
return 0;
}
void My::Entity::Player::OnComponentHit(std::weak_ptr<Event> e)
{
std::shared_ptr<Event> _e = e.lock();
auto event = static_cast<Events::DeathEvent*>(_e.get());
auto other = reinterpret_cast<IMyGameObject*>(event->other);
if (other->GetType() == MYGAMEOBJECT_TYPE::UFO)
{
DEBUG_PRINT("Player collides with ");
DEBUG_PRINT(other->GetName() << "\n");
{
// damange to self
auto hp_com = static_cast<Component::HealthPoint*>(GetComponent(COMPONENT_TYPE::HEALTHPOINT));
if (!hp_com->IsLockHP())
{
static_cast<Component::Sprite*>(GetComponent(COMPONENT_TYPE::SPRITE))->StartHitFlash();
std::lock_guard<std::mutex> lock1(hp_com->m_mutex);
hp_com->Reduce(COLLISION_HP_REDUCE);
}
}
}
else if (other->GetType() == MYGAMEOBJECT_TYPE::Item_HP)
{
auto hp_com = static_cast<Component::HealthPoint*>(GetComponent(COMPONENT_TYPE::HEALTHPOINT));
std::lock_guard<std::mutex> lock1(hp_com->m_mutex);
hp_com->Restore(PLAYER_HP_RESTORE);
}
else if (other->GetType() == MYGAMEOBJECT_TYPE::Item_SHIELD)
{
g_pEventDispatcher->DispatchToGameObject(-1.0, std::make_shared<Events::LockHPEvent>(), this);
g_pEventDispatcher->DispatchToGameObject(PLAYER_LOCKHP_PERIOD, std::make_shared<Events::UnLockHPEvent>(), this);
}
else if (other->GetType() == MYGAMEOBJECT_TYPE::Item_UPGRADE)
{
auto p_weapon_com = static_cast<Component::WeaponarySystem*>(GetComponent(COMPONENT_TYPE::WEAPONARYSYSTEM));
p_weapon_com->UpgradeWeapons();
}
}
void My::Entity::Player::OnEnemyDeath(std::weak_ptr<Event> e)
{
std::shared_ptr<Event> _e = e.lock();
auto event = static_cast<Events::ComponentHitEvent*>(_e.get());
auto other = reinterpret_cast<IMyGameObject*>(event->other);
if (other->GetType() == MYGAMEOBJECT_TYPE::UFO)
{
wPRINT(str2wstr(other->GetName() + " has been destroied\n"));
// TODO : Change victory condition
if (++head_count == WINNING_HEAD_COUNT)
{
m_callBacks["Victory"]();
}
LoadWaveByHeadCount(head_count);
}
}
void My::Entity::Player::OnLockHP(std::weak_ptr<Event> e)
{
static_cast<Component::Sprite*>(GetComponent(COMPONENT_TYPE::SPRITE))->SetCurrentSpriteByName("Shield");
static_cast<Component::HealthPoint*>(GetComponent(COMPONENT_TYPE::HEALTHPOINT))->LockHP();
}
void My::Entity::Player::OnUnLockHP(std::weak_ptr<Event> e)
{
static_cast<Component::Sprite*>(GetComponent(COMPONENT_TYPE::SPRITE))->SetCurrentSpriteByName("Default");
static_cast<Component::HealthPoint*>(GetComponent(COMPONENT_TYPE::HEALTHPOINT))->UnLockHP();
}
// TODO : Change load wave conditions
void My::LoadWaveByHeadCount(int head_count)
{
switch (head_count)
{
case 0:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave1";
break;
case 2:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave2";
break;
case 5:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave3";
break;
case 8:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave4";
break;
case 11:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave5";
break;
case 14:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave6";
break;
case 25:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave7";
break;
case 26:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave8";
break;
case 31:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave9";
break;
case 33:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave10";
break;
case 35:
g_pSceneManager->m_queueWaveConfigPath = "Level1_Wave11";
break;
default:
break;
}
}
<file_sep>/CS529_Game/src/Entity/Gameplay/Interface/WeaponType.hpp
#pragma once
#include <string>
#include <map>
#include <memory>
#include "Common/Geommath/2D/Math.hpp"
// Lazer
#define WEAPON_LAZER_ORIGIN_HIEGHT RAND_I(450,550)
#define WEAPON_LAZER_DAM_BASE 2.5f
#define WEAPON_LAZER_FIRE_PERIOD 0.5
#define WEAPON_LAZER_BULLET_SPEED 800.0f
#define WEAPON_LAZER_BULLE_DAM_BASE 15.0f
// Kinetic Gun
#define WEAPON_KINETICGUN_FIRE_PERIOD 0.1
#define WEAPON_KINETICGUN_BULLET_SPEED 800.0f
#define WEAPON_KINETICGUN_DAM_BASE 7.5f
#define WEAPON_KINETICGUN_SPREAD 3.14159265359f / 8.0f
#define WEAPON_KINETICGUN_EXPLOSION_LIFETIME 0.1
// Missile
#define WEAPON_MISSILE_FIRE_PERIOD 0.5
#define WEAPON_MISSILE_BULLET_ACC 800.0f
#define WEAPON_MISSILE_DAM_BASE 15.0f
#define WEAPON_MISSILE_EXPLOSION_LIFETIME 0.2
// UFO
#define UFO_ROT_SPEED PI
#define UFO_SPEED_1 200.0f
#define UFO_SPEED_2 400.0f
#define UFO_SPEED_3 600.0f
#define UFO_FIRE_MODE_1_FIRE_PERIOD .5f
#define UFO_FIRE_MODE_2_FIRE_PERIOD 1.0f
#define UFO_FIRE_MODE_3_FIRE_PERIOD .25f
#define UFO_BULLET_BASE_DAMAGE 25.0f
namespace My
{
enum class WEAPON_TYPE
{
WEAPON_MISSILE = 0,
WEAPON_LAZER,
WEAPON_KINETICGUN,
WEAPON_KINETICGUN_BULLET,
WEAPON_MISSILE_BULLET,
WEAPON_MISSILE_EXPLOSION,
WEAPON_KINETICGUN_EXPLOSION,
WEAPON_LAZER_BEAM,
UFO_BULLET,
NUM
};
}
<file_sep>/GameEngine/Common/Event/EventManager.hpp
#pragma once
#include <map>
#include <queue>
#include "Event.hpp"
#include "Common/Interface/IRunTimeModule.hpp"
/* Game objects must register a event type in order for the event manager to process it if USE_EventRegistry = 1 */
#define USE_EventRegistry 0
namespace My
{
class EventManager : public IRunTimeModule
{
public:
EventManager() noexcept;
EventManager(const EventManager&) = delete;
EventManager& operator=(const EventManager&) = delete;
virtual int Initialize() override;
virtual int Tick(double deltaTime) override;
virtual int Finalize() override;
virtual void Serialize(std::wostream& wostream) override;
/* Marking the event type as registered to be true */
void AddEventRegistry(EventType type);
/* Add certain event that will be managed by the event manager */
void AddEvent(std::weak_ptr<Event> e);
/* Owner is a IGameObject */
void* GetOwner() noexcept;
void SetOwner(void* owner) noexcept;
private:
// Owner is an entity (e.g. IGameObject)
void* m_owner;
std::queue<std::shared_ptr<Event>> m_eventsQueue;
std::map<EventType, bool> m_eventsRegistry;
};
}<file_sep>/CS529_Game/src/GameApplication.hpp
/* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
File Name: GameApplication.hpp
Purpose: header file of GameApplication
Language: c++ 11
Platform: win32 x86
Project: CS529_final_project
Author: <NAME> hang.yu 60001119
Creation date: 10/13/2019
- End Header ----------------------------*/
#pragma once
#include "src/Platform/Win32_SDL/WinSDLOpenGLApplication.hpp"
#define MY_CALL_BACK void
namespace My
{
// Dummy Class
class GameApplication : public WinSDLOpenGLApplication
{
public:
GameApplication() = delete;
GameApplication(const GameApplication&) = delete;
GameApplication& operator=(const GameApplication&) = delete;
explicit GameApplication(const GfxConfiguration& config) : WinSDLOpenGLApplication(config)
{}
};
extern MY_CALL_BACK Initialize();
extern MY_CALL_BACK GameLoop();
extern MY_CALL_BACK Finalize();
}<file_sep>/GameEngine/Common/Utility/Utility.cpp
#include "Utility.hpp"
void My::print_fstream(std::ifstream& fstream)
{
fstream.clear();
fstream.seekg(0);
std::cout << fstream.rdbuf();
}
void My::rewind_fstream(std::ifstream& fstream)
{
fstream.clear();
fstream.seekg(0);
}
<file_sep>/GameEngine/Common/GraphicsManager.cpp
#include "GraphicsManager.hpp"
My::GraphicsManager::GraphicsManager() noexcept
{
}
int My::GraphicsManager::Initialize()
{
return 0;
}
int My::GraphicsManager::Tick(double deltaTime)
{
return 0;
}
int My::GraphicsManager::Finalize()
{
return 0;
}
|
665cf1338e4fc2fa703095f25f7362e29474bdf0
|
[
"C",
"Text",
"C++"
] | 111
|
C++
|
yhyu13/DigiPen-CS529-PersonalGameProject
|
6d6233a98cddd28f5f06bd1363654b1684f129c4
|
fd37b3515b5fe947c76f4e8fa607f9e2266fd61a
|
refs/heads/master
|
<file_sep>#ifndef VNH5019MotorShield_h
#define VNH5019MotorShield_h
#include <Arduino.h>
#define WD6_MIN_SPEED 60
typedef void (*isr_ft)(void);
/*
typedef struct tagMYAVRTIMER {
volatile uint8_t *tccr;
volatile uint16_t *icr;
volatile uint16_t *ocr;
} MYAVRTIMER;
*/
class VNH5019MD
{
public:
// CONSTRUCTORS
VNH5019MD(unsigned char INA, unsigned char INB, unsigned char PWM, unsigned char EN1DIAG, unsigned char EN2DIAG,
unsigned char CS, volatile uint16_t *OCR, int REINT, isr_ft isr_f); // User-defined pin selection.
// PUBLIC METHODS
void init(int ena=1); // Initialize TIMER, set the PWM to 20kHZ.
void setSpeed(int speed); // Set speed.
void incSpeed(int step, int dir); // Increment speed.
int getSpeed(void); // Get speed.
void setBrake(int brake); // Brake.
unsigned int getCurrentMilliamps(); // Get current reading.
unsigned char getFaultH1(); // Get fault reading.
unsigned char getFaultH2(); // Get fault reading.
void enableH1();
void enableH2();
void enable();
void disableH1();
void disableH2();
void disable();
private:
unsigned char _INA;
unsigned char _INB;
unsigned char _PWM;
unsigned char _EN1DIAG;
unsigned char _EN2DIAG;
unsigned char _CS;
volatile uint16_t *_OCR;
int _REINT;
isr_ft _ISR_F;
int _speed;
int _prev_speed;
unsigned char _enabledH1;
unsigned char _enabledH2;
};
int vnh5019_initTimers(void);
#endif
<file_sep>void eval_setup(void)
{
tmr_init(&g_tmr_lightpos,100);
}
int eval_doit(void)
{
static uint8_t sw=0;
static int l_lastlightpos=UCCB_PL_OFF;
// if(g_recv_ready != 1) return(0);
if((g_cb_fsBE == 11) && (g_recv_ready == 1)) {
// pmw3901_rot_start();
sw++;
sw%=2;
if(sw == 1) {
light_pos_on();
} else {
light_pos_off();
}
// md_go();
}
if((g_cb_b6pBE == 21) && (g_recv_ready == 1)) {
g_piro_scan=PIRO_SCAN_START;
}
if((g_cb_b6pBE == 61) && (g_recv_ready == 1)) {
g_piro_scan=PIRO_SCAN_STOP;
}
//md_setspeed();
//servo_rudder();
servo_holder();
piro_doit();
vl53l1x_read();
pmw3901_read();
// pmw3901_test();
/*
if(g_cb_b6pBE == 11) {
light_pos_on();
}
if(g_cb_b6pBE == 41) {
light_pos_off();
}
*/
if(g_cb_lightpos != l_lastlightpos) {
if(g_cb_lightpos == UCCB_PL_OFF) {
light_pos_off();
} else if(g_cb_lightpos == UCCB_PL_ON) {
light_pos_on();
}
l_lastlightpos=g_cb_lightpos;
}
if(g_cb_lightpos == UCCB_PL_BLINK) {
if(tmr_do(&g_tmr_lightpos) == 1) {
if(g_tmr_lightpos.cnt%2 == 0) {
light_pos_on();
} else {
light_pos_off();
}
}
}
return(1);
}
<file_sep>int um6_checksum(UM6_packet *um6p);
int um6_makepacket(UM6_packet *um6p, uint8_t addr, byte *data);
int um6_makecommpacket(UM6_packet *um6p, uint8_t broadcast_rate, uint8_t baud_rate, uint8_t GPS_baud_rate,
uint8_t SAT, uint8_t SUM, uint8_t VEL, uint8_t REL, uint8_t POS,
uint8_t TEMP, uint8_t COV, uint8_t EU, uint8_t QT, uint8_t MP, uint8_t AP,
uint8_t GP, uint8_t MR, uint8_t AR, uint8_t GR, uint8_t BEN);
int parse_serial_data(uint8_t* rx_data, uint8_t rx_length, UM6_packet * packet);
int readum6(UM6_packet *um6p);
int read_um6_packet(uint8_t addr, UM6_packet *um6p);
int read_um6_packet_any(UM6_packet *um6p);
UM6_packet g_um6pr={0},g_um6pw={0};
int um6_checksum(UM6_packet *um6p)
{
um6p->Checksum='s'+'n'+'p'+um6p->PT+um6p->Address;
return(0);
}
int um6_makepacket(UM6_packet *um6p, uint8_t addr, byte *data)
{
uint8_t i;
um6p->Address=addr;
if(data == NULL) {
um6p->PT=0;
} else {
um6p->PT=1<<7;
}
um6_checksum(um6p);
um6p->data[0]='s';
um6p->data[1]='n';
um6p->data[2]='p';
um6p->data[3]=um6p->PT;
um6p->data[4]=um6p->Address;
if(data == NULL) {
i=5;
} else {
for(i=0;i < 4;i++) {
um6p->data[5+i]=data[3-i];
um6p->Checksum+=data[3-i];
}
i=9;
}
um6p->data[i]=(uint8_t)(um6p->Checksum>>8);
um6p->data[i+1]=(uint8_t)um6p->Checksum;
um6p->data_length=i+2;
return(0);
}
int um6_makecommpacket(UM6_packet *um6p, uint8_t broadcast_rate, uint8_t baud_rate, uint8_t GPS_baud_rate,
uint8_t SAT, uint8_t SUM, uint8_t VEL, uint8_t REL, uint8_t POS,
uint8_t TEMP, uint8_t COV, uint8_t EU, uint8_t QT, uint8_t MP, uint8_t AP,
uint8_t GP, uint8_t MR, uint8_t AR, uint8_t GR, uint8_t BEN)
{
uint8_t i;
um6p->Address=UM6_REG_COMMUNICATION;
um6p->PT=1<<7;
um6p->data[0]='s';
um6p->data[1]='n';
um6p->data[2]='p';
um6p->data[3]=um6p->PT;
um6p->data[4]=um6p->Address;
um6p->data[5]=BEN<<6|GR<<5|AR<<4|MR<<3|GP<<2|AP<<1|MP;
um6p->data[6]=QT<<7|EU<<6|COV<<5|TEMP<<4|POS<<3|REL<<2|VEL<<1|SUM;
um6p->data[7]=SAT<<7|GPS_baud_rate<<3|baud_rate;
um6p->data[8]=broadcast_rate;
um6p->Checksum=um6p->data[0];
for(i=1;i < 9;i++) {
um6p->Checksum+=um6p->data[i];
}
um6p->data[9]=(uint8_t)(um6p->Checksum>>8);
um6p->data[10]=(uint8_t)um6p->Checksum;
um6p->data_length=11;
return(0);
}
int parse_serial_data(uint8_t* rx_data, uint8_t rx_length, UM6_packet * packet)
{
uint8_t index;
uint8_t packet_index;
uint8_t PT;
uint8_t packet_has_data;
uint8_t packet_is_batch;
uint8_t batch_length;
uint8_t data_length;
uint16_t computed_checksum;
uint16_t received_checksum;
// Make sure that the data buffer provided is long enough to contain a full packet
// The minimum packet length is 7 bytes
if( rx_length < 7 ) {
return(-1);
}
// Try to find the ‘snp’ start sequence for the packet
for( index = 0; index < (rx_length-2); index++ ) {
// Check for ‘snp’. If found, immediately exit the loop
if( rx_data[index] == 's' && rx_data[index+1] == 'n' && rx_data[index+2] == 'p' ) {
break;
}
}
packet_index=index;
// Check to see if the variable ‘packet_index’ is equal to (rx_length -2). If it is, then the above
// loop executed to completion and never found a packet header.
if( packet_index ==(rx_length-2) ) {
return(-2);
}
// If we get here, a packet header was found. Now check to see if we have enough room
// left in the buffer to contain a full packet. Note that at this point, the variable ‘packet_index’
// contains the location of the ‘s’ character in the buffer (the first byte in the header)
if( (rx_length-packet_index) < 7 ) {
return(-3);
}
// We’ve found a packet header, and there is enough space left in the buffer for at least
// the smallest allowable packet length (7 bytes). Pull out the packet type byte to determine
// the actual length of this packet
PT = rx_data[packet_index + 3];
// Do some bit-level manipulation to determine if the packet contains data and if it is a batch
// We have to do this because the individual bits in the PT byte specify the contents of the
// packet.
packet_has_data = (PT >> 7) & 0x01;
// Check bit 7 (HAS_DATA)
packet_is_batch = (PT >> 6) & 0x01;
// Check bit 6 (IS_BATCH)
batch_length = (PT >> 2) & 0x0F;
// Extract the batch length (bits 2 through 5)
// Now finally figure out the actual packet length
data_length = 0;
if( packet_has_data ) {
if( packet_is_batch ) {
// Packet has data and is a batch. This means it contains ‘batch_length'registers, each
// of which has a length of 4 bytes
data_length = 4*batch_length;
} else {
// Packet has data but is not a batch. This means it contains one register (4 bytes)
data_length = 4;
}
} else {
// Packet has no data
data_length = 0;
}
// At this point, we know exactly how long the packet is. Now we can check to make sure
// we have enough data for the full packet.
if( (rx_length-packet_index) < (data_length + 5) ) {
return(-4);
}
// If we get here, we know that we have a full packet in the buffer. All that remains is to pull
// out the data and make sure the checksum is good.
// Start by extracting all the data
packet->Address = rx_data[packet_index + 4];
packet->PT = PT;
// Get the data bytes and compute the checksum all in one step
packet->data_length = data_length;
//computed_checksum = 's' + 'n' + 'p'+ packet_data->PT + packet_data->Address;
computed_checksum = 's' + 'n' + 'p'+ packet->PT + packet->Address;
for( index = 0; index < data_length; index++ ) {
// Copy the data into the packet structure’s data array
packet ->data[index] = rx_data[packet_index + 5 + index];
// Add the new byte to the checksum
computed_checksum+= packet->data[index];
}
// Now see if our computed checksum matches the received checksum
// First extract the checksum from the packet
received_checksum = (rx_data[packet_index + 5 + data_length] << 8);
received_checksum |= rx_data[packet_index + 6 + data_length];
// Now check to see if they don’t match
if( received_checksum != computed_checksum ) {
return(-5);
}
// At this point, we’ve received a full packet with a good checksum. It is already
// fully parsed and copied to the ‘packet’ structure, so return 0 to indicate that a packet was
// processed.
return(0);
}
int readum6(UM6_packet *um6p)
{
int psd;
unsigned char c1;
while(Serial2.available()) {
c1=(unsigned char)Serial2.read();
if(um6p->spl >= sizeof(um6p->spd)) return(-1);
um6p->spd[um6p->spl++]=c1;
if(um6p->spl == 1) {
if(c1 != 's') {
um6p->spl=0;
}
return(1);
}
if(um6p->spl == 2) {
if(c1 != 'n') {
um6p->spl=0;
}
return(2);
}
if(um6p->spl == 3) {
if(c1 != 'p') {
um6p->spl=0;
}
return(3);
}
psd=parse_serial_data(um6p->spd,um6p->spl,um6p);
return(psd);
}
return(4);
}
int read_um6_packet(uint8_t addr, UM6_packet *um6p)
{
int psd,zc=0;
um6p->spl=0;
for(;;) {
psd=readum6(um6p);
if(psd == 0) {
zc=0;
if(um6p->Address == addr) return(1);
} else {
if(psd == -1) zc++;
if(zc > 3) break;
}
}
return(0);
}
int read_um6_packet_any(UM6_packet *um6p)
{
int psd,zc=0;
um6p->spl=0;
for(;;) {
psd=readum6(um6p);
if(psd == 0) {
zc=0;
return(1);
} else {
if(psd == -1) zc++;
if(zc > 3) break;
}
}
return(0);
}
int um6_setup(void)
{
Serial2.begin(115200);
um6_makecommpacket(&g_um6pw,0,5,0,0,0,0,0,0,1,0,1,0,1,0,0,1,1,1,0);
Serial2.write(g_um6pw.data,g_um6pw.data_length);
for(;;) {
if(read_um6_packet_any(&g_um6pr) != 1) {
Serial.println("***** UM6 comm packet read FAIL!");
return(-1);
}
if(g_um6pr.Address == UM6_REG_COMMUNICATION) break;
}
um6_makepacket(&g_um6pw,UM6_CMD_GET_FW_VERSION,NULL);
Serial2.write(g_um6pw.data,g_um6pw.data_length);
read_um6_packet_any(&g_um6pr);
um6_makepacket(&g_um6pw,UM6_CMD_GET_FW_VERSION,NULL);
Serial2.write(g_um6pw.data,g_um6pw.data_length);
if(read_um6_packet_any(&g_um6pr) == 1) {
Serial.print("***** UM6 fw: ");
Serial.print(g_um6pr.data[0]);
Serial.print(g_um6pr.data[1]);
Serial.print(g_um6pr.data[2]);
Serial.print(g_um6pr.data[3]);
Serial.println();
} else {
Serial.println("***** UM6 fw packet read FAIL!");
}
return(0);
}
<file_sep>#define VL53L1X_RANGE_SHORT 1
#define VL53L1X_RANGE_LONG 2
typedef struct tagVL53L1XDIST {
unsigned long t;
unsigned int d;
} VL53L1XDIST;
VL53L1XDIST g_vl53l1xdist_d[5]={0};
int g_vl53l1xdist_i=0;
int16_t g_vl53l1x_offset=24;
uint16_t g_vl53l1x_xtalk=0;
uint8_t g_vl53l1x_rangemode=VL53L1X_RANGE_LONG;
volatile uint8_t g_vl53l1x_dataready=0;
#define VL53L1X_BOOT_READY 3
VL53L1X vl53l1x(&Wire);
void ISR_vl53l1x_dataready(void)
{
g_vl53l1x_dataready=1;
}
int vl53l1x_calibration(void)
{
VL53L1X_ERROR err;
int16_t offset;
uint16_t xtalk;
Serial.println("Waiting for servo ...");
delay(2000);
Serial.println("Calibrating offset ...");
err=vl53l1x.VL53L1X_CalibrateOffset(140,&offset);
if(err != 0) return(-1);
Serial.print("Offset1: ");
Serial.println(offset);
err=vl53l1x.VL53L1X_GetOffset(&offset);
Serial.print("Offset2: ");
Serial.println(offset);
Serial.println("Calibrating xtalk ...");
err=vl53l1x.VL53L1X_CalibrateXtalk(140,&xtalk);
if(err != 0) return(-1);
Serial.print("Xtalk1: ");
Serial.println(xtalk);
err=vl53l1x.VL53L1X_GetXtalk(&xtalk);
Serial.print("Xtalk2: ");
Serial.println(xtalk);
err=vl53l1x.VL53L1X_StartTemperatureUpdate();
return(0);
}
// convert a RangeStatus to a readable string
// Note that on an AVR, these strings are stored in RAM (dynamic memory), which
// makes working with them easier but uses up 200+ bytes of RAM (many AVR-based
// Arduinos only have about 2000 bytes of RAM). You can avoid this memory usage
// if you do not call this function in your sketch.
const char *vl53l1x_rangeStatusToString(uint8_t status)
{
switch (status)
{
case 0:
return "range valid";
case 1:
return "sigma fail";
case 2:
return "signal fail";
case 4:
return "out of bounds";
case 7:
return "wraparound";
default:
return "unknown status";
}
}
int vl53l1x_setrange(uint16_t mode, uint32_t im, uint16_t tb)
{
VL53L1X_ERROR err;
if(im < tb) return(-1);
err=vl53l1x.VL53L1X_SetDistanceMode(mode);
if(err != 0) return(-1);
err=vl53l1x.VL53L1X_SetInterMeasurementInMs(im);
if(err != 0) return(-1);
err=vl53l1x.VL53L1X_SetTimingBudgetInMs(tb);
if(err != 0) return(-1);
return(0);
}
int vl53l1x_shortrange(uint32_t im, uint16_t tb)
{
if(vl53l1x_setrange(1,im,tb) != 0) return(-1);
return(0);
}
int vl53l1x_longrange(uint32_t im, uint16_t tb)
{
if(vl53l1x_setrange(2,im,tb) != 0) return(-1);
return(0);
}
void showroi(void)
{
VL53L1X_ERROR err;
uint16_t x,y;
err=vl53l1x.VL53L1X_GetROI_XY(&x,&y);
if(err != 0) return;
Serial.print("ROI.x=");
Serial.println(x);
Serial.print("ROI.y=");
Serial.println(y);
}
void vl53l1x_setup(void)
{
uint8_t state;
VL53L1X_ERROR err;
VL53L1X_Version_t ver={0};
uint16_t id=0;
unsigned long t0;
uint16_t xtalk;
int16_t offset;
Wire.begin();
Wire.setClock(400000); // use 400 kHz I2C
Wire.setSCL(16);
Wire.setSDA(17);
t0=millis();
for(;;) {
err=vl53l1x.VL53L1X_BootState(&state);
if((err == 0) && (state == VL53L1X_BOOT_READY)) break;
if((millis()-t0) > 1000) break;
delay(10);
}
if(state == VL53L1X_BOOT_READY) {
Serial.println("vl53l1x ready!");
} else {
Serial.print(err);
Serial.print(" ");
Serial.print(state);
Serial.print(" ");
Serial.println("vl53l1x boot failure!");
}
tmr_init(&g_tmr_vl53l1x,1000);
err=vl53l1x.VL53L1X_GetSWVersion(&ver);
Serial.print("SW version: 0x");
Serial.print(ver.major,HEX);
Serial.print(" 0x");
Serial.print(ver.minor,HEX);
Serial.print(" 0x");
Serial.print(ver.build,HEX);
Serial.print(" 0x");
Serial.println(ver.revision,HEX);
err=vl53l1x.VL53L1X_GetSensorId(&id);
Serial.print("ID: 0x");
Serial.println(id,HEX);
err=vl53l1x.VL53L1X_SensorInit();
//vl53l1x_calibration();
/*
//1 short 1300 mm, 2 long 4000 mm
err=vl53l1x.VL53L1X_SetDistanceMode(2);
err=vl53l1x.VL53L1X_SetInterMeasurementInMs(50);
err=vl53l1x.VL53L1X_SetTimingBudgetInMs(50);
*/
pinMode(24,INPUT_PULLUP);
attachInterrupt(24,ISR_vl53l1x_dataready,RISING);
vl53l1x_setrange(g_vl53l1x_rangemode,50,50);
err=vl53l1x.VL53L1X_SetOffset(g_vl53l1x_offset);
err=vl53l1x.VL53L1X_SetXtalk(g_vl53l1x_xtalk);
err=vl53l1x.VL53L1X_GetOffset(&offset);
Serial.print("Offset: ");
Serial.println(offset);
err=vl53l1x.VL53L1X_GetXtalk(&xtalk);
Serial.print("Xtalk: ");
Serial.println(xtalk);
showroi();
vl53l1x.VL53L1X_SetROI(16,16);
showroi();
err=vl53l1x.VL53L1X_StartRanging();
Serial.println("vl53l1x setup OK!");
}
int vl53l1x_read(void)
{
VL53L1X_ERROR err;
uint8_t rs=0;
uint16_t dist;
// if(tmr_do(&g_tmr_vl53l1x) != 1) return(0);
/*
err=vl53l1x.VL53L1X_CheckForDataReady(&dr);
if(err != 0) return(0);
if(dr != 1) return(0);
*/
if(g_vl53l1x_dataready != 1) return(0);
err=vl53l1x.VL53L1X_GetRangeStatus(&rs);
if(err != 0) {
Serial.println("rangestatuserror");
return(0);
}
err=vl53l1x.VL53L1X_GetDistance(&dist);
if(err != 0) {
Serial.println("getdistanceerror");
return(0);
}
vl53l1x.VL53L1X_ClearInterrupt();
g_vl53l1x_dataready=0;
g_vl53l1xdist_d[g_vl53l1xdist_i].t=g_millis;
g_vl53l1xdist_d[g_vl53l1xdist_i].d=dist;
g_vl53l1xdist_i++;
g_vl53l1xdist_i%=(sizeof(g_vl53l1xdist_d)/sizeof(g_vl53l1xdist_d[0]));
g_wd6_vl53l1x_dist=dist;
if(tmr_do(&g_tmr_vl53l1x) != 1) return(0);
/*
Serial.print(vl53l1x_rangeStatusToString(rs));
Serial.print(": ");
Serial.print(dist);
Serial.println();
*/
if((dist < 1000) && (g_vl53l1x_rangemode != VL53L1X_RANGE_SHORT)) {
Serial.println("setting short range");
vl53l1x_shortrange(50,50);
g_vl53l1x_rangemode=VL53L1X_RANGE_SHORT;
} else if((dist > 1300) && (g_vl53l1x_rangemode != VL53L1X_RANGE_LONG)) {
Serial.println("setting long range");
vl53l1x_longrange(100,100);
g_vl53l1x_rangemode=VL53L1X_RANGE_LONG;
}
return(1);
}
<file_sep>#ifndef __WD6MTR_H_INCLUDED__
#define __WD6MTR_H_INCLUDED__
#include "sh1tmr.h"
typedef struct tagWD6MTR {
const char *name;
VNH5019MD *md;
WD6RE *re;
MYTMR tmr_rpm;
} WD6MTR;
#endif /* __WD6MTR_H_INCLUDED__ */
<file_sep>void loop_counter(void)
{
g_loop_cnt++;
if((g_millis-g_loop_ct) > 1000) {
g_loop_cps=g_loop_cnt;
g_loop_cnt=0;
g_loop_ct=g_millis;
// Serial.print("loopcps ");
// Serial.println(g_loop_cps);
// Serial.print("battV ");
// Serial.println(g_battV);
}
}
void setup()
{
pinMode(RESET_MD_PIN,INPUT_PULLUP);
delay(500);
analogReadResolution(10);
Serial.begin(115200);
// Configure SPI Flash chip select
pinMode(WD6CU_SPI_CS_PIN,OUTPUT);
digitalWrite(WD6CU_SPI_CS_PIN,HIGH);
SPI.begin(); // initiate SPI
smar_setup();
batt_setup();
eval_setup();
comm_setup();
servo_setup();
light_setup();
temp_setup();
piro_setup();
vl53l1x_setup();
pmw3901_setup();
cumc_comm_setup();
pinMode(RESET_MD_PIN,OUTPUT);
digitalWrite(RESET_MD_PIN,LOW);
delay(10);
pinMode(RESET_MD_PIN,INPUT_PULLUP);
delay(1000);
g_loop_ct=millis();
}
void loop()
{
g_millis=millis();
loop_counter();
batt_read(&g_battV,&g_battA);
// temp_read();
bxcu_comm();
eval_doit();
cumc_comm();
}
<file_sep>int pyro=0;
int ar(int pin)
{
ADMUX=(1<<REFS0)|(1<<REFS1)|pin;
ADCSRA|=(1<<ADSC);
while(!(ADCSRA&(1<<ADIF)));
ADCSRA|=(1<<ADIF);
pyro=ADCL+(ADCH<<8);
}
void loop_counter(void)
{
g_millis=millis();
g_loop_cnt++;
if((g_millis-g_loop_ct) > 1000) {
Serial.print("loopcps ");
Serial.println(g_loop_cps);
// pyro=ar(61);
// pyro=analogRead(A7);
// Serial.println(pyro);
// Serial.print("battV: ");
// Serial.println(g_cb_battV);
/*
Serial.print("J1 curr: ");
Serial.print(g_wd6md_J1.curr->getRawValue());
Serial.print("\t");
Serial.println(g_wd6md_J1.curr->getValue());
Serial.print("J2 curr: ");
Serial.print(g_wd6md_J2.curr->getRawValue());
Serial.print("\t");
Serial.println(g_wd6md_J2.curr->getValue());
*/
/*
Serial.print(g_wd6md_J1.md->getSpeed());
Serial.print(" ");
Serial.print(g_wd6md_J2.md->getSpeed());
Serial.print(" ");
Serial.print(g_wd6md_J3.md->getSpeed());
Serial.print(" ");
Serial.print(g_wd6md_B1.md->getSpeed());
Serial.print(" ");
Serial.print(g_wd6md_B2.md->getSpeed());
Serial.print(" ");
Serial.println(g_wd6md_B3.md->getSpeed());
*/
/*
Serial.print(g_wd6md_J1.re->rpm);
Serial.print(" ");
Serial.print(g_wd6md_J2.re->rpm);
Serial.print(" ");
Serial.print(g_wd6md_J3.re->rpm);
Serial.print(" ");
Serial.print(g_wd6md_B1.re->rpm);
Serial.print(" ");
Serial.print(g_wd6md_B2.re->rpm);
Serial.print(" ");
Serial.println(g_wd6md_B3.re->rpm);
*/
/*
Serial.print(g_wd6md_J1.curr->getRawValue());
Serial.print(" ");
Serial.print(g_wd6md_J2.curr->getRawValue());
Serial.print(" ");
Serial.print(g_wd6md_J3.curr->getRawValue());
Serial.print(" ");
Serial.print(g_wd6md_B1.curr->getRawValue());
Serial.print(" ");
Serial.print(g_wd6md_B2.curr->getRawValue());
Serial.print(" ");
Serial.println(g_wd6md_B3.curr->getRawValue());
*/
/*
Serial.print("m1s: ");
Serial.print(g_cb_m1s);
Serial.print(" m2s:");
Serial.println(g_cb_m2s);
*/
g_force_send=1;
comm_send();
g_loop_cps=g_loop_cnt;
g_loop_cnt=0;
g_loop_ct=g_millis;
}
}
void setup()
{
// delay(500);
digitalWrite(LED_BUILTIN,HIGH);
delay(200);
pinMode(LED_BUILTIN,OUTPUT);
smar_setup();
//digitalWrite(LED_BUILTIN, HIGH);
// batt_setup();
// md_setup();
comm_setup();
Serial.begin(115200);
//digitalWrite(LED_BUILTIN, HIGH);
g_md_J1.init();
g_md_J2.init();
g_md_J3.init();
g_md_B1.init();
g_md_B2.init();
g_md_B3.init();
vnh5019_initTimers();
wd6re_setup();
wd6md_setup();
delay(1000);
g_loop_ct=millis();
Serial.println("Motor controller ready!");
g_wd6md_am=0;
g_wd6md_am_go=0;
}
void loop()
{
int rpm,dir,speed;
loop_counter();
wd6re_loop();
wd6md_readcurrent();
// temp_read();
#if 0
rpm=0;
if((g_cb_fsY > 530) && (g_cb_fsY < 1024)) {
rpm=map(g_cb_fsY,530,1024,4,65);
dir=-1;
} else if((g_cb_fsY < 500) && (g_cb_fsY >= 0)) {
rpm=map(g_cb_fsY,0,500,65,4);
dir=1;
}
// Serial.print("rpm: ");
// Serial.println(rpm);
// pwr=7;
// dir=-1;
if(rpm == 0) {
g_wd6md_J1.md->setSpeed(0);
g_wd6md_J2.md->setSpeed(0);
g_wd6md_J3.md->setSpeed(0);
g_wd6md_B1.md->setSpeed(0);
g_wd6md_B2.md->setSpeed(0);
g_wd6md_B3.md->setSpeed(0);
} else {
speed=400;
g_wd6md_J1.md->setSpeed(speed);
g_wd6md_J2.md->setSpeed(speed);
g_wd6md_J3.md->setSpeed(speed);
g_wd6md_B1.md->setSpeed(speed);
g_wd6md_B2.md->setSpeed(speed);
g_wd6md_B3.md->setSpeed(speed);
/*
wd6md_setrpm(&g_wd6md_J1,rpm,dir);
wd6md_setrpm(&g_wd6md_J2,rpm,dir);
wd6md_setrpm(&g_wd6md_J3,rpm,dir);
wd6md_setrpm(&g_wd6md_B1,rpm,dir);
wd6md_setrpm(&g_wd6md_B2,rpm,dir);
wd6md_setrpm(&g_wd6md_B3,rpm,dir);
*/
}
#endif
// wd6md_setspeedx();
// wd6md_go(50,-100);
wd6md_am();
wd6md_mm();
wd6cumd_comm();
}
<file_sep>#define WD6_HOLDERPAN_CENTER 1500
#define WD6_HOLDERPAN_MIN 580
#define WD6_HOLDERPAN_MAX 2420
#define WD6_HOLDERTILT_CENTER 1500
#define WD6_HOLDERTILT_MIN 1130
#define WD6_HOLDERTILT_MAX 1870
#define WD6_HOLDERTILT_LEVEL 1370
Servo holderpan;
Servo holdertilt;
int g_wd6_holderpan_pos=WD6_HOLDERPAN_CENTER;
int g_wd6_holdertilt_pos=WD6_HOLDERTILT_LEVEL;
unsigned long g_wd6_holder_t=0;
int servo_setup(void)
{
holderpan.attach(5,WD6_HOLDERPAN_MIN,WD6_HOLDERPAN_MAX);
holdertilt.attach(6,WD6_HOLDERTILT_MIN,WD6_HOLDERTILT_MAX);
holderpan.writeMicroseconds(g_wd6_holderpan_pos);
holdertilt.writeMicroseconds(g_wd6_holdertilt_pos);
return(0);
}
int servo_holder(void)
{
int vx,vy;
vx=constrain(g_cb_tsxp,-100,100);
vy=constrain(g_cb_tsyp,-100,100);
if((vx == 0) && (vy == 0)) return(0);
if((g_millis-g_wd6_holder_t) < 40) return(0);
vx=vx/3;
g_wd6_holderpan_pos+=vx;
if(g_wd6_holderpan_pos < WD6_HOLDERPAN_MIN) g_wd6_holderpan_pos=WD6_HOLDERPAN_MIN;
else if(g_wd6_holderpan_pos > WD6_HOLDERPAN_MAX) g_wd6_holderpan_pos=WD6_HOLDERPAN_MAX;
holderpan.writeMicroseconds(g_wd6_holderpan_pos);
vy=-vy/3;
g_wd6_holdertilt_pos+=vy;
if(g_wd6_holdertilt_pos < WD6_HOLDERTILT_MIN) g_wd6_holdertilt_pos=WD6_HOLDERTILT_MIN;
else if(g_wd6_holdertilt_pos > WD6_HOLDERTILT_MAX) g_wd6_holdertilt_pos=WD6_HOLDERTILT_MAX;
holdertilt.writeMicroseconds(g_wd6_holdertilt_pos);
g_wd6_holder_t=g_millis;
return(0);
}
int servo_scan_start(void)
{
g_piro_scan_start_t0=g_millis;
g_wd6_holderpan_pos=WD6_HOLDERPAN_MIN;
holderpan.writeMicroseconds(g_wd6_holderpan_pos);
g_wd6_holdertilt_pos=WD6_HOLDERTILT_LEVEL;
holdertilt.writeMicroseconds(g_wd6_holdertilt_pos);
return(0);
}
int servo_scan_onprogress(int val, int *min_val, int *max_val, int *max_pos)
{
int rval=-1;
if(g_millis < g_piro_scan_start_t0+500) return(1);
/*
if(g_piro_scan_start_t0 > 0) {
Serial.println("start measurement");
g_piro_scan_start_t0=0;
}
*/
if(g_wd6_holderpan_pos <= WD6_HOLDERPAN_MIN) {
g_wd6_holderpan_pos=WD6_HOLDERPAN_MIN;
*min_val=val;
*max_val=val;
*max_pos=g_wd6_holderpan_pos;
} else if(val > *max_val) {
*max_val=val;
*max_pos=g_wd6_holderpan_pos;
} else if(val < *min_val) {
*min_val=val;
}
if(g_wd6_holderpan_pos >= WD6_HOLDERPAN_MAX) {
g_wd6_holderpan_pos=WD6_HOLDERPAN_MAX;
return(0);
}
if(g_wd6_holderpan_pos < WD6_HOLDERPAN_MAX) {
g_wd6_holderpan_pos+=50;
rval=1;
}
if(g_wd6_holderpan_pos >= WD6_HOLDERPAN_MAX) {
g_wd6_holderpan_pos=WD6_HOLDERPAN_MAX;
rval=1;
}
holderpan.writeMicroseconds(g_wd6_holderpan_pos);
return(rval);
}
int servo_scan_stop(int pos)
{
g_piro_scan_stop_t0=g_millis;
g_wd6_holderpan_pos=pos;
if(g_wd6_holderpan_pos >= WD6_HOLDERPAN_MAX) {
g_wd6_holderpan_pos=WD6_HOLDERPAN_MAX;
}
holderpan.writeMicroseconds(g_wd6_holderpan_pos);
return(0);
}
int servo_course(int diff)
{
int d;
if(g_millis < g_piro_scan_stop_t0+500) return(1);
if(diff > 0) {
if(diff > 6) diff=6;
d=map(diff,1,6,100,200);
g_cb_m1s=-d;
g_cb_m2s=d;
} else if(diff < 0) {
if(diff < -6) diff=-6;
d=map(-diff,1,6,100,200);
g_cb_m1s=d;
g_cb_m2s=-d;
} else {
g_cb_m1s=0;
g_cb_m2s=0;
}
if(g_wd6_holderpan_pos < WD6_HOLDERPAN_CENTER) {
g_wd6_holderpan_pos+=20;
if(g_wd6_holderpan_pos > WD6_HOLDERPAN_CENTER) {
g_wd6_holderpan_pos=WD6_HOLDERPAN_CENTER;
}
} else if(g_wd6_holderpan_pos > WD6_HOLDERPAN_CENTER) {
g_wd6_holderpan_pos-=20;
if(g_wd6_holderpan_pos < WD6_HOLDERPAN_CENTER) {
g_wd6_holderpan_pos=WD6_HOLDERPAN_CENTER;
}
}
holderpan.writeMicroseconds(g_wd6_holderpan_pos);
if(g_wd6_holderpan_pos == WD6_HOLDERPAN_CENTER) {
return(0);
}
return(1);
}
int servo_follow(int diff)
{
int d;
if(g_millis < g_piro_scan_stop_t0+500) return(0);
/*
if(diff != 0) {
Serial.println(diff);
}
*/
if(diff > 0) {
if(diff > 7) diff=7;
d=map(diff,1,7,5,150);
g_wd6_holderpan_pos+=d;
} else if(diff < 0) {
if(diff < -7) diff=-7;
d=map(-diff,1,7,5,150);
g_wd6_holderpan_pos-=d;
}
if(g_wd6_holderpan_pos < WD6_HOLDERPAN_MIN) {
g_wd6_holderpan_pos=WD6_HOLDERPAN_MIN;
} else if(g_wd6_holderpan_pos > WD6_HOLDERPAN_MAX) {
g_wd6_holderpan_pos=WD6_HOLDERPAN_MAX;
}
holderpan.writeMicroseconds(g_wd6_holderpan_pos);
return(0);
}
<file_sep>#include "vnh5019.h"
int vnh5019_initTimers(void)
{
// Timer 1 configuration
// prescaler: clockI/O / 1
// outputs enabled
// phase-correct PWM
// top of 400
//
// PWM frequency calculation
// 16MHz / 1 (prescaler) / 2 (phase-correct) / 400 (top) = 20kHz
TCCR4A = 0b10101000;
TCCR4B = 0b00010001;
ICR4 = 400;
TCCR5A = 0b10101000;
TCCR5B = 0b00010001;
ICR5 = 400;
return(0);
}
// Constructors ////////////////////////////////////////////////////////////////
VNH5019MD::VNH5019MD(unsigned char INA, unsigned char INB, unsigned char PWM, unsigned char EN1DIAG, unsigned char EN2DIAG,
unsigned char CS, volatile uint16_t *OCR, int REINT, isr_ft isr_f)
{
//Pin map
_INA=INA;
_INB=INB;
_PWM=PWM;
_EN1DIAG=EN1DIAG;
_EN2DIAG=EN2DIAG;
_CS=CS;
_OCR=OCR;
_REINT=REINT;
_ISR_F=isr_f;
_speed=0;
_prev_speed=0;
}
// Public Methods //////////////////////////////////////////////////////////////
void VNH5019MD::init(int ena)
{
// Define pinMode for the pins and set the frequency for timer1.
pinMode(_INA,OUTPUT);
pinMode(_INB,OUTPUT);
pinMode(_PWM,OUTPUT);
// pinMode(_EN1DIAG,INPUT_PULLUP);
// pinMode(_EN2DIAG,INPUT_PULLUP);
if(ena == 0) {
disable();
} else {
enable();
}
pinMode(_CS,INPUT);
attachInterrupt(_REINT,_ISR_F,CHANGE);
}
// Set speed for motor 1, speed is a number betwenn -400 and 400
void VNH5019MD::setSpeed(int speed)
{
unsigned char reverse=0;
if(_prev_speed == speed) return;
if(speed < 0) {
speed=-speed; // Make speed a positive quantity
reverse=1; // Preserve the direction
}
if(speed > 400) {// Max PWM dutycycle
speed=400;
}
*_OCR = speed;
if(reverse) {
digitalWrite(_INA,LOW);
digitalWrite(_INB,HIGH);
_speed=-speed;
} else {
digitalWrite(_INA,HIGH);
digitalWrite(_INB,LOW);
_speed=speed;
}
_prev_speed=_speed;
}
void VNH5019MD::incSpeed(int step, int dir)
{
int speed;
//Serial.print("speed=");
//Serial.println(_speed);
if(_speed >= 0) {
speed=_speed+step;
if(speed < 0) speed=0;
} else {
speed=_speed-step;
if(speed > 0) speed=0;
speed=-speed;
}
/*
if((step > 0) && (speed < 60)) {
speed=60;
}
*/
if(speed < WD6_MIN_SPEED) {
speed=WD6_MIN_SPEED;
}
if(dir < 0) {
speed=-speed;
}
setSpeed(speed);
}
int VNH5019MD::getSpeed(void)
{
return(_speed);
}
// Brake motor 1, brake is a number between 0 and 400
void VNH5019MD::setBrake(int brake)
{
// normalize brake
if(brake < 0) {
brake=-brake;
}
if(brake > 400) {// Max brake
brake=400;
}
digitalWrite(_INA,LOW);
digitalWrite(_INB,LOW);
*_OCR=brake;
}
// Return motor 1 current value in milliamps.
unsigned int VNH5019MD::getCurrentMilliamps()
{
// 5V / 1024 ADC counts / 144 mV per A = 34 mA per count
return analogRead(_CS) * 34;
}
// Return error status for half bridge 1
unsigned char VNH5019MD::getFaultH1()
{
if(_enabledH1 == 0) return(0xFB);
return !digitalRead(_EN1DIAG);
}
// Return error status for half bridge 2
unsigned char VNH5019MD::getFaultH2()
{
if(_enabledH2 == 0) return(0xFB);
return !digitalRead(_EN2DIAG);
}
void VNH5019MD::enableH1()
{
pinMode(_EN1DIAG,INPUT_PULLUP);
_enabledH1=1;
}
void VNH5019MD::enableH2()
{
pinMode(_EN2DIAG,INPUT_PULLUP);
_enabledH2=1;
}
void VNH5019MD::enable()
{
VNH5019MD::enableH1();
VNH5019MD::enableH2();
}
void VNH5019MD::disableH1()
{
pinMode(_EN1DIAG,OUTPUT);
_enabledH1=0;
}
void VNH5019MD::disableH2()
{
pinMode(_EN2DIAG,OUTPUT);
_enabledH2=0;
}
void VNH5019MD::disable()
{
VNH5019MD::disableH1();
VNH5019MD::disableH2();
}
<file_sep>#include <wd6st.h>
#include <sh1tmr.h>
#include <uccbcrc.h>
#include <piro.h>
#include <RunningAverage.h>
#include <Servo.h>
#include <Wire.h>
#include <SPI.h> // Include the SPI library
//#include <vl53l1_api.h>
//#include "SparkFun_VL53L1X.h"
//#include "VL53L1X.h"
#include "vl53l1x_class.h"
#include "Bitcraze_PMW3901.h"
#define WD6CU_VERSION "1.0.2"
#define RESET_MD_PIN 2
#define WD6CU_SPI_CS_PIN 15 // chip select for SPI
//battery
#define UCCB_BATTV_PORT A16
#define UCCB_BATTA_PORT A17
int16_t g_battV=-1;
int16_t g_battA=-1;
//temperature
#define UCCB_TEMPERATURE_PORT A4
int16_t g_temperature=-1;
MYTMR g_tmr_temperature={0};
//general
unsigned long g_millis=0;
unsigned long g_loop_cnt=0; //loop counter
unsigned long g_loop_cps=0; //loop counter per sec
unsigned long g_loop_ct=0;
int g_recv_ready=0; //uccb command received
//UCCB
//battery
int16_t g_cb_battV=-1;
//joy
int16_t g_cb_tsX=-1;
int16_t g_cb_tsY=-1;
int16_t g_cb_fsX=-1;
int16_t g_cb_fsY=-1;
int16_t g_cb_fsZ=-1;
int16_t g_cb_fsBS=-1;
int16_t g_cb_fsBE=-1;
//10p switch
int g_cb_sw10p=-1;
//6p button
int g_cb_b6p=-1;
int16_t g_cb_b6pBS=-1;
int16_t g_cb_b6pBE=-1;
//comm
unsigned long g_cb_w_commpkt_counter=0;
//servo
int16_t g_cb_tsxp=0;
int16_t g_cb_tsyp=0;
int16_t g_cb_rdd=0;
//lights
#define SH1_POSLIGHT_PORT 26
int g_cb_lightpos=UCCB_PL_OFF;
MYTMR g_tmr_lightpos={0};
//motor
int16_t g_cb_m1s=0;
int16_t g_cb_m2s=0;
uint16_t g_rpm_m1=0;
uint16_t g_rpm_m2=0;
uint16_t g_cur_m1=0;
uint16_t g_cur_m2=0;
int8_t g_dir_m1=0;
int8_t g_dir_m2=0;
MYTMR g_tmr_checkmc={0};
unsigned long g_mc_loopcps=0;
uint16_t g_mc_J1rpm=0;
uint16_t g_mc_B1rpm=0;
uint16_t g_mc_J2rpm=0;
uint16_t g_mc_B2rpm=0;
uint16_t g_mc_J3rpm=0;
uint16_t g_mc_B3rpm=0;
uint16_t g_mc_J1cur=0;
uint16_t g_mc_B1cur=0;
uint16_t g_mc_J2cur=0;
uint16_t g_mc_B2cur=0;
uint16_t g_mc_J3cur=0;
uint16_t g_mc_B3cur=0;
//piro
#define WD6CU_PIRO_LEFT A10
#define WD6CU_PIRO_RIGHT A11
MYTMR g_tmr_piro={0};
int g_piro_scan=PIRO_SCAN_STOP;
unsigned long g_piro_scan_start_t0=0;
unsigned long g_piro_scan_stop_t0=0;
int16_t g_wd6_piro_val=0;
//vl53l1x
MYTMR g_tmr_vl53l1x={0};
uint16_t g_wd6_vl53l1x_dist=0;
//pmw3901
MYTMR g_tmr_pmw3901={0};
<file_sep>#include "wd6re.h"
#define WD6RE_ICNC_TIME 400 //interrupt counter not changed, zero speed
#if 0
volatile uint8_t g_wd6re_ic1=0; // interrupt counter
volatile unsigned long g_wd6re_tbi1=1; //time between interrupts
uint8_t g_wd6re_ic1o=0;
uint8_t g_wd6re_num_tbi=WD6RE_TBI_NUM;
uint16_t g_wd6rpm_m1=0;
uint16_t g_wd6rpm_m1o=0;
void wd6re_setup() {
// put your setup code here, to run once:
// attachInterrupt(2, wd6re_isr1, CHANGE);
}
uint16_t qe_rpm1_tbi(void)
{
static uint8_t l_idx=0,l_r0=0;
static uint16_t l_rpm=0;
static unsigned long l_tbi[WD6RE_TBI_NUM]={0};
static unsigned long l_sum=0;
static unsigned long l_t0=0;
unsigned long tbi;
unsigned long atbi;
int i;
/*
Serial.print("xx ");
Serial.print(l_r0,DEC);
Serial.print(" ");
Serial.println(g_wd6re_ic1,DEC);
*/
if(l_r0 == g_wd6re_ic1) {
if(g_millis > l_t0+WD6RE_ICNC_TIME) {
l_sum=0;
l_tbi[0]=0;
l_idx=0;
l_rpm=0;
return(l_rpm);
} else {
return(l_rpm);
}
} else {
l_t0=g_millis;
l_r0=g_wd6re_ic1;
noInterrupts();
tbi=g_wd6re_tbi1;
interrupts();
}
/*
Serial.print("xx ");
Serial.print(l_r0,DEC);
Serial.print(" ");
Serial.print(g_wd6re_ic1,DEC);
Serial.print(" ");
Serial.print(dtx,DEC);
Serial.print(" ");
Serial.println(g_millis-l_t0,DEC);
*/
if(tbi > 1000UL*WD6RE_ICNC_TIME) {
l_sum=0;
l_tbi[0]=0;
l_idx=0;
l_rpm=0;
return(l_rpm);
}
l_sum+=tbi;
l_idx++;
l_idx%=g_wd6re_num_tbi;
if(l_tbi[0] == 0) {
if(l_idx == 0) {
atbi=l_sum/g_wd6re_num_tbi;
} else {
atbi=l_sum/l_idx;
}
} else {
l_sum-=l_tbi[l_idx];
atbi=l_sum/g_wd6re_num_tbi;
}
l_tbi[l_idx]=tbi;
/*
for(i=0;i < WD6RE_TBI_NUM;i++) {
Serial.print(l_tbi[i]);
Serial.print(" ");
}
Serial.println("");
*/
/*
Serial.print("1b ");
Serial.print(dt,DEC);
Serial.print(" ");
Serial.print(dtx,DEC);
Serial.print(" ");
Serial.print(l_sum,DEC);
Serial.print(" ");
Serial.println(atbi,DEC);
*/
l_rpm=1000000UL/atbi;
// l_rpm=2000000UL/atbi;
return(l_rpm);
}
void wd6re_loop()
{
g_wd6rpm_m1=qe_rpm1_tbi();
if(g_wd6rpm_m1 != g_wd6rpm_m1o) {
Serial.print(g_millis);
Serial.print(" rpm=");
Serial.println(g_wd6rpm_m1);
g_wd6rpm_m1o=g_wd6rpm_m1;
}
if(g_wd6re_ic1o != g_wd6re_ic1) {
// Serial.println(g_wd6re_ic1);
g_wd6re_ic1o=g_wd6re_ic1;
}
}
void wd6re_isrJ3(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_ic1++;
mm=micros();
g_wd6re_tbi1=mm-l_t0;
l_t0=mm;
}
void wd6re_isrB3(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_ic1++;
mm=micros();
g_wd6re_tbi1=mm-l_t0;
l_t0=mm;
}
#endif
//---------------------------------------------------------------------------------------------------------------------------
void wd6re_setup() {
// put your setup code here, to run once:
g_wd6re_J1.g_wd6re_tbi=1;
g_wd6re_J2.g_wd6re_tbi=1;
g_wd6re_J3.g_wd6re_tbi=1;
g_wd6re_B1.g_wd6re_tbi=1;
g_wd6re_B2.g_wd6re_tbi=1;
g_wd6re_B3.g_wd6re_tbi=1;
g_wd6re_J1.g_wd6re_num_tbi=WD6RE_TBI_NUM;
g_wd6re_J2.g_wd6re_num_tbi=WD6RE_TBI_NUM;
g_wd6re_J3.g_wd6re_num_tbi=WD6RE_TBI_NUM;
g_wd6re_B1.g_wd6re_num_tbi=WD6RE_TBI_NUM;
g_wd6re_B2.g_wd6re_num_tbi=WD6RE_TBI_NUM;
g_wd6re_B3.g_wd6re_num_tbi=WD6RE_TBI_NUM;
}
uint16_t qe_rpm_tbi(WD6RE *wd6re)
{
unsigned long tbi;
unsigned long atbi;
int i;
/*
Serial.print("xx ");
Serial.print(l_r0,DEC);
Serial.print(" ");
Serial.println(g_wd6re_ic1,DEC);
*/
if(wd6re->l_r0 == wd6re->ic) {
if(g_millis > wd6re->l_t0+WD6RE_ICNC_TIME) {
wd6re->l_sum=0;
wd6re->l_tbi[0]=0;
wd6re->l_idx=0;
wd6re->l_rpm=0;
return(wd6re->l_rpm);
} else {
return(wd6re->l_rpm);
}
} else {
wd6re->l_t0=g_millis;
wd6re->l_r0=wd6re->ic;
noInterrupts();
tbi=wd6re->g_wd6re_tbi;
interrupts();
}
/*
Serial.print("xx ");
Serial.print(l_r0,DEC);
Serial.print(" ");
Serial.print(g_wd6re_ic1,DEC);
Serial.print(" ");
Serial.print(dtx,DEC);
Serial.print(" ");
Serial.println(g_millis-l_t0,DEC);
*/
if(tbi > 1000UL*WD6RE_ICNC_TIME) {
wd6re->l_sum=0;
wd6re->l_tbi[0]=0;
wd6re->l_idx=0;
wd6re->l_rpm=0;
return(wd6re->l_rpm);
}
wd6re->l_sum+=tbi;
wd6re->l_idx++;
wd6re->l_idx%=wd6re->g_wd6re_num_tbi;
if(wd6re->l_tbi[0] == 0) {
if(wd6re->l_idx == 0) {
atbi=wd6re->l_sum/wd6re->g_wd6re_num_tbi;
} else {
atbi=wd6re->l_sum/wd6re->l_idx;
}
} else {
wd6re->l_sum-=wd6re->l_tbi[wd6re->l_idx];
atbi=wd6re->l_sum/wd6re->g_wd6re_num_tbi;
}
wd6re->l_tbi[wd6re->l_idx]=tbi;
/*
for(i=0;i < WD6RE_TBI_NUM;i++) {
Serial.print(l_tbi[i]);
Serial.print(" ");
}
Serial.println("");
*/
/*
Serial.print("1b ");
Serial.print(dt,DEC);
Serial.print(" ");
Serial.print(dtx,DEC);
Serial.print(" ");
Serial.print(l_sum,DEC);
Serial.print(" ");
Serial.println(atbi,DEC);
*/
wd6re->l_rpm=1000000UL/atbi;
// l_rpm=2000000UL/atbi;
return(wd6re->l_rpm);
}
void wd6re_loop()
{
g_wd6re_B3.rpm=qe_rpm_tbi(&g_wd6re_B3);
if(g_wd6re_B3.rpm != g_wd6re_B3.rpmo) {
Serial.print(g_millis);
Serial.print(" rpm=");
Serial.print(g_wd6re_B3.rpm);
Serial.print(" ");
Serial.println(g_wd6re_J3.rpm);
g_wd6re_B3.rpmo=g_wd6re_B3.rpm;
}
if(g_wd6re_B3.ico != g_wd6re_B3.ic) {
// Serial.println(g_wd6re_ic1);
g_wd6re_B3.ico=g_wd6re_B3.ic;
}
g_wd6re_J3.rpm=qe_rpm_tbi(&g_wd6re_J3);
if(g_wd6re_J3.rpm != g_wd6re_J3.rpmo) {
Serial.print(g_millis);
Serial.print(" rpm=");
Serial.print(g_wd6re_B3.rpm);
Serial.print(" ");
Serial.println(g_wd6re_J3.rpm);
g_wd6re_J3.rpmo=g_wd6re_J3.rpm;
}
if(g_wd6re_J3.ico != g_wd6re_J3.ic) {
// Serial.println(g_wd6re_ic1);
g_wd6re_J3.ico=g_wd6re_J3.ic;
}
}
void wd6re_isrJ1(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_J1.ic++;
mm=micros();
g_wd6re_J1.g_wd6re_tbi=mm-l_t0;
l_t0=mm;
}
void wd6re_isrJ2(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_J2.ic++;
mm=micros();
g_wd6re_J2.g_wd6re_tbi=mm-l_t0;
l_t0=mm;
}
void wd6re_isrJ3(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_J3.ic++;
mm=micros();
g_wd6re_J3.g_wd6re_tbi=mm-l_t0;
l_t0=mm;
}
void wd6re_isrB1(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_B1.ic++;
mm=micros();
g_wd6re_B1.g_wd6re_tbi=mm-l_t0;
l_t0=mm;
}
void wd6re_isrB2(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_B2.ic++;
mm=micros();
g_wd6re_B2.g_wd6re_tbi=mm-l_t0;
l_t0=mm;
}
void wd6re_isrB3(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_B3.ic++;
mm=micros();
g_wd6re_B3.g_wd6re_tbi=mm-l_t0;
l_t0=mm;
}
<file_sep>//wd6 arduino
#include "vnh5019.h"
#include "wd6re.h"
#include "wd6md.h"
#include "sh1tmr.h"
#include "uccbcrc.h"
#include "RunningAverage.h"
int wd6re_readrpm(WD6MD *wd6md);
int wd6md_setrpm(WD6MD *wd6md, int rpm, int dir);
int wd6md_setspeed1(int16_t ms, int16_t *ms_p, WD6MD *wd6md1, WD6MD *wd6md2, WD6MD *wd6md3);
uint16_t qe_rpm_tbi(WD6RE *wd6re);
VNH5019MD g_md_J1(47,48,6,42,43,A1,&OCR4A,0,wd6re_isrJ1);
VNH5019MD g_md_J2(24,25,7,22,23,A2,&OCR4B,1,wd6re_isrJ2);
VNH5019MD g_md_J3(28,29,8,26,27,A3,&OCR4C,5,wd6re_isrJ3);
VNH5019MD g_md_B1(32,33,44,30,31,A4,&OCR5C,4,wd6re_isrB1);
VNH5019MD g_md_B2(36,37,45,34,35,A5,&OCR5B,3,wd6re_isrB2);
VNH5019MD g_md_B3(40,41,46,38,39,A6,&OCR5A,2,wd6re_isrB3);
WD6RE g_wd6re_J1={0};
WD6RE g_wd6re_J2={0};
WD6RE g_wd6re_J3={0};
WD6RE g_wd6re_B1={0};
WD6RE g_wd6re_B2={0};
WD6RE g_wd6re_B3={0};
WD6MD g_wd6md_J1={0};
WD6MD g_wd6md_J2={0};
WD6MD g_wd6md_J3={0};
WD6MD g_wd6md_B1={0};
WD6MD g_wd6md_B2={0};
WD6MD g_wd6md_B3={0};
RunningAverage g_wd6md_J1_mc(5);
RunningAverage g_wd6md_J2_mc(5);
RunningAverage g_wd6md_J3_mc(5);
RunningAverage g_wd6md_B1_mc(5);
RunningAverage g_wd6md_B2_mc(5);
RunningAverage g_wd6md_B3_mc(5);
//general
unsigned long g_millis=0;
unsigned long g_loop_cnt=0; //loop counter
unsigned long g_loop_cps=0; //loop counter per sec
unsigned long g_loop_ct=0;
MYTMR g_tmr_comm={0};
MYTMR g_tmr_rmc={0}; //read motor current
int g_force_send=0;
unsigned char g_rb=0;
unsigned long g_chmst=0; //change motor speed time
int g_msn=0,g_mso=0;
unsigned long g_wcu_commpkt_counter=0;
//battery
int16_t g_cb_battV=-1;
//joy
int16_t g_cb_tsX=-1;
int16_t g_cb_tsY=-1;
int16_t g_cb_fsX=-1;
int16_t g_cb_fsY=-1;
int16_t g_cb_fsZ=-1;
int16_t g_cb_fsBS=-1;
int16_t g_cb_fsBE=-1;
int16_t g_cb_b6pBS=-1;
int16_t g_cb_b6pBE=-1;
int16_t g_cb_m1s=0;
int16_t g_cb_m2s=0;
int16_t g_cb_rdd=0;
int8_t g_wd6md_am=0;
int8_t g_wd6md_am_go=0;
int g_wd6md_am_goidx=-1;
<file_sep>void loop_counter(void)
{
g_loop_cnt++;
if((g_millis-g_loop_ct) > 1000) {
g_loop_cps=g_loop_cnt;
g_loop_cnt=0;
g_loop_ct=g_millis;
}
}
void setup()
{
delay(1000);
smar_setup();
batt_setup();
// md_setup();
eval_setup();
comm_setup();
// servo_setup();
light_setup();
temp_setup();
// Serial.begin(115200);
delay(2000);
g_loop_ct=millis();
}
void loop()
{
g_millis=millis();
loop_counter();
batt_read(&g_battV,&g_battA);
temp_read();
comm_send();
comm_recv();
eval_doit();
}
<file_sep>#ifndef VNH5019MotorShield_h
#define VNH5019MotorShield_h
#include <Arduino.h>
typedef void (*isr_ft)(void);
/*
typedef struct tagMYAVRTIMER {
volatile uint8_t *tccr;
volatile uint16_t *icr;
volatile uint16_t *ocr;
} MYAVRTIMER;
*/
class VNH5019MD
{
public:
// CONSTRUCTORS
VNH5019MD(unsigned char INA, unsigned char INB, unsigned char PWM, unsigned char EN1DIAG, unsigned char EN2DIAG,
unsigned char CS, volatile uint16_t *OCR, int REINT, isr_ft isr_f); // User-defined pin selection.
// PUBLIC METHODS
void init(); // Initialize TIMER, set the PWM to 20kHZ.
void setSpeed(int speed); // Set speed.
void incSpeed(int step); // Increment speed.
int getSpeed(void); // Get speed.
void setBrake(int brake); // Brake.
unsigned int getCurrentMilliamps(); // Get current reading.
unsigned char getFault(); // Get fault reading.
private:
unsigned char _INA;
unsigned char _INB;
unsigned char _PWM;
unsigned char _EN1DIAG;
unsigned char _EN2DIAG;
unsigned char _CS;
volatile uint16_t *_OCR;
int _REINT;
isr_ft _ISR_F;
int _speed;
};
int vnh5019_initTimers(void);
#endif
<file_sep>//wd6 teensy
const int ledPin=13;
unsigned long g_sendtmo=0;
unsigned long g_millis=0;
unsigned char g_wb=0;
unsigned char g_rb=0;
void setup() {
pinMode(ledPin,OUTPUT);
Serial.begin(115200); //usb
Serial1.begin(500000); //wd6 motor controller
Serial3.begin(19200); //wd6 RF
delay(1000);
}
void loop() {
g_millis=millis();
if(g_sendtmo == 0) {
Serial.println("Teensy serial test started.");
}
if(g_millis > (g_sendtmo+500)) {
Serial1.write((byte*)&g_wb,1);
g_wb=(g_wb+1)%10;
g_sendtmo=g_millis;
if(g_wb%2 == 0) {
digitalWrite(ledPin,HIGH);
} else {
digitalWrite(ledPin,LOW);
}
}
/*
if(Serial1.available() > 0) {
g_rb=(unsigned char)Serial1.read();
Serial.println(g_rb);
}
*/
if(Serial1.available() > 0) {
g_rb=(unsigned char)Serial1.read();
Serial.print("md: ");
Serial.println(g_rb);
Serial3.write((byte*)&g_rb,1);
}
if(Serial3.available() > 0) {
g_rb=(unsigned char)Serial3.read();
Serial.print("RF: ");
Serial.println(g_rb);
}
}
<file_sep>unsigned long g_piro_doit_tmo=60;
unsigned long g_piro_counter=0;
int g_piro_max_val=-1;
int g_piro_min_val=-1;
int g_piro_max_pos=0;
PIRO g_psl;
PIRO g_psr;
int piro_setup(void)
{
tmr_init(&g_tmr_piro,g_piro_doit_tmo);
memset((void*)&g_psl,0,sizeof(PIRO));
g_psl.port=WD6CU_PIRO_LEFT;
memset((void*)&g_psr,0,sizeof(PIRO));
g_psr.port=WD6CU_PIRO_RIGHT;
return(0);
}
int piro_doit(void)
{
int sum,diff,ret;
// static unsigned long t0=0;
piro_read(&g_psl);
piro_read(&g_psr);
if(tmr_do(&g_tmr_piro) != 1) return(0);
sum=g_psr.s_val0+g_psl.s_val0;
if(sum > 0) {
diff=(32*(g_psr.s_val0-g_psl.s_val0))/sum;
} else {
diff=0;
}
g_wd6_piro_val=sum;
if(g_piro_scan == PIRO_SCAN_START) {
servo_scan_start();
g_piro_scan=PIRO_SCAN_ONPROGRESS;
g_piro_max_val=-1;
} else if(g_piro_scan == PIRO_SCAN_ONPROGRESS) {
ret=servo_scan_onprogress(sum,&g_piro_min_val,&g_piro_max_val,&g_piro_max_pos);
if(ret == 0) {
servo_scan_stop(g_piro_max_pos);
/*
Serial.print(g_piro_min_val);
Serial.print(" ");
Serial.print(g_piro_max_val);
Serial.println();
*/
if((g_piro_max_val-g_piro_min_val) < 60) {
g_piro_scan=PIRO_SCAN_STOP;
} else {
g_piro_scan=PIRO_SCAN_FOLLOW;
g_piro_scan=PIRO_SCAN_COURSE;
}
}
} else if(g_piro_scan == PIRO_SCAN_COURSE) {
ret=servo_course(diff);
if(ret == 0) {
g_piro_scan=PIRO_SCAN_STOP;
g_piro_scan=PIRO_MOTOR_FOLLOW;
}
} else if(g_piro_scan == PIRO_SCAN_FOLLOW) {
servo_follow(diff);
} else if(g_piro_scan == PIRO_MOTOR_FOLLOW) {
cumc_follow(g_piro_min_val,g_piro_max_val,sum,diff);
/*
if((g_millis-t0) > 500) {
Serial.print(g_piro_max_val);
Serial.print(" ");
Serial.print(sum);
Serial.print(" ");
Serial.print(diff);
Serial.print(" ");
Serial.print(g_cb_m1s);
Serial.print(" ");
Serial.print(g_cb_m2s);
Serial.println();
t0=g_millis;
}
*/
}
// Serial.print(g_piro_counter);
/*
Serial.print(g_millis);
Serial.print(" ");
Serial.print(g_psl.s_val0);
Serial.print(" ");
Serial.print(g_psl.l_val0);
Serial.print(" ");
Serial.print(sum);
Serial.print(" ");
Serial.print(diff);
*/
/*
Serial.print(" ");
Serial.print(g_psl.s_val0);
Serial.print(" ");
Serial.print((3.3*g_psl.s_val0)/1024.0);
Serial.print(" ");
Serial.print(g_psr.s_val0);
Serial.print(" ");
Serial.print((3.3*g_psr.s_val0)/1024.0);
*/
/*
vall=analogRead(WD6CU_PIRO_LEFT);
valr=analogRead(WD6CU_PIRO_RIGHT);
Serial.print(g_piro_counter);
Serial.print(" ");
Serial.print(vall);
Serial.print(" ");
Serial.print((3.3*vall)/1024.0);
Serial.print(" ");
Serial.print(valr);
Serial.print(" ");
Serial.print((3.3*valr)/1024.0);
*/
// Serial.println();
g_piro_counter+=g_piro_doit_tmo;
return(0);
}
<file_sep>unsigned long g_pmw3901_doit_tmo=100;
int16_t g_deltaX=0,g_deltaY=0;
int32_t g_pmw3901_sumX=0;
int32_t g_pmw3901_sumY=0;
int g_pmw3901_rotinprogress=0;
int g_pmw3901_dataready=0;
Bitcraze_PMW3901 pmw3901(WD6CU_SPI_CS_PIN); // Instantiate PMW3901
int pmw3901_setup()
{
uint8_t product_ID;
uint8_t revision_ID;
uint8_t inverse_product_ID;
Serial.println("pmw3901 setup started");
SPI.beginTransaction(SPISettings(2000000,MSBFIRST,SPI_MODE0));
digitalWrite(WD6CU_SPI_CS_PIN,LOW);
SPI.transfer(0x00);
product_ID=SPI.transfer(0);
digitalWrite(WD6CU_SPI_CS_PIN,HIGH);
SPI.endTransaction();
Serial.print("Product ID = 0x");
Serial.print(product_ID,HEX);
Serial.println(" should be 0x49");
if(product_ID != 0x49) {
Serial.println("Initialization of the flow sensor failed1");
return(-1);
}
SPI.beginTransaction(SPISettings(2000000,MSBFIRST,SPI_MODE0));
digitalWrite(WD6CU_SPI_CS_PIN,LOW);
SPI.transfer(0x01);
revision_ID=SPI.transfer(0);
digitalWrite(WD6CU_SPI_CS_PIN,HIGH);
SPI.endTransaction();
Serial.print("Revision ID = 0x");
Serial.println(revision_ID, HEX);
SPI.beginTransaction(SPISettings(2000000,MSBFIRST,SPI_MODE0));
digitalWrite(WD6CU_SPI_CS_PIN,LOW);
SPI.transfer(0x5F);
inverse_product_ID=SPI.transfer(0);
digitalWrite(WD6CU_SPI_CS_PIN,HIGH);
SPI.endTransaction();
Serial.print("Inverse Product ID = 0x");
Serial.print(inverse_product_ID,HEX);
Serial.println(" should be 0xB6");
if(inverse_product_ID != 0xB6) {
Serial.println("Initialization of the flow sensor failed2");
return(-1);
}
if(!pmw3901.begin()) {
Serial.println("Initialization of the flow sensor failed3");
return(-1);
}
tmr_init(&g_tmr_pmw3901,g_pmw3901_doit_tmo);
Serial.println("pmw3901 setup completed");
/* end of setup */
return(0);
}
int pmw3901_read(void)
{
g_pmw3901_dataready=0;
if(tmr_do(&g_tmr_pmw3901) != 1) return(0);
pmw3901.readMotionCount(&g_deltaX,&g_deltaY);
g_pmw3901_dataready=1;
Serial.print("X: ");
Serial.print(g_deltaX);
Serial.print(", Y: ");
Serial.print(g_deltaY);
Serial.print("\n");
return(0);
}
int pmw3901_rot_start(void)
{
Serial.println("rot start");
g_pmw3901_sumX=0;
g_pmw3901_sumY=0;
g_pmw3901_rotinprogress=1;
return(0);
}
int pmw3901_rot_stop(int angle)
{
if(g_pmw3901_rotinprogress != 1) return(0);
if(g_pmw3901_dataready == 0) return(0);
g_pmw3901_sumX+=g_deltaX;
g_pmw3901_sumY+=g_deltaY;
if(g_pmw3901_sumX != 0) {
Serial.print("sum: ");
Serial.print(g_pmw3901_sumX);
Serial.print(" ");
Serial.println(g_pmw3901_sumY);
if(g_pmw3901_sumY >= 80.0*cos(3.14*angle/180.0)) {
g_pmw3901_rotinprogress=0;
}
}
return(1);
}
int pmw3901_test(void)
{
g_cb_m1s=-90;
g_cb_m2s=90;
pmw3901_rot_stop(15);
if(g_pmw3901_rotinprogress == 0) {
g_cb_m1s=0;
g_cb_m2s=0;
}
return(0);
}
<file_sep>byte g_w_commbuf[100]={0};
unsigned long g_w_sendtime=0;
unsigned long g_w_commpkt_counter=0; //total counter of sent packets
byte g_r_commbuf[100]={0};
int g_r_state=UCCB_PST_INIT;
unsigned int g_r_len=0;
byte g_commmode=1;
unsigned long g_commmode_t=0;
int comm_setup(void)
{
Serial3.begin(19200);
buildCRCTable();
return(0);
}
int comm_pack1(byte *d, uint16_t l, byte *buf, uint16_t *len)
{
if((*len+l) > sizeof(g_w_commbuf)) return(-1);
memcpy((void*)(buf+*len),(void*)d,l);
(*len)+=l;
return(0);
}
int comm_packsh1(uint16_t *len)
{
byte lead=UCCB_WD6CU_LEAD;
byte crc8;
int16_t rpm1,rpm2;
*len=0;
// md_getmc(&m1c,&m2c);
if(g_dir_m1 >= 0) rpm1=(int16_t)g_rpm_m1;
else rpm1=-(int16_t)g_rpm_m1;
if(g_dir_m2 >= 0) rpm2=(int16_t)g_rpm_m2;
else rpm2=-(int16_t)g_rpm_m2;
/*
Serial.print(g_loop_cnt);
Serial.print(" ");
Serial.println(g_loop_cps);
*/
comm_pack1((byte*)&lead,sizeof(lead),g_w_commbuf,len); //1:1
comm_pack1((byte*)&g_loop_cps,sizeof(g_loop_cps),g_w_commbuf,len); //4:5
comm_pack1((byte*)&g_battV,sizeof(g_battV),g_w_commbuf,len); //2:7
comm_pack1((byte*)&g_battA,sizeof(g_battA),g_w_commbuf,len); //2:9
comm_pack1((byte*)&g_cur_m1,sizeof(g_cur_m1),g_w_commbuf,len); //2:11
comm_pack1((byte*)&g_cur_m2,sizeof(g_cur_m2),g_w_commbuf,len); //2:13
comm_pack1((byte*)&rpm1,sizeof(rpm1),g_w_commbuf,len); //2:15
comm_pack1((byte*)&rpm2,sizeof(rpm2),g_w_commbuf,len); //2:17
comm_pack1((byte*)&g_temperature,sizeof(g_temperature),g_w_commbuf,len); //2:19
comm_pack1((byte*)&g_wd6_piro_val,sizeof(g_wd6_piro_val),g_w_commbuf,len); //2:21
comm_pack1((byte*)&g_wd6_vl53l1x_dist,sizeof(g_wd6_vl53l1x_dist),g_w_commbuf,len); //2:23
crc8=getCRC(g_w_commbuf,*len);
/*
Serial.print(" ");
Serial.print("crc ");
Serial.println(crc8);
*/
comm_pack1((byte*)&crc8,sizeof(crc8),g_w_commbuf,len); //1:24
//24 byte long
return(0);
}
int comm_send(void)
{
uint16_t len;
// g_w_commpkt_counter++;
//csakhogy ne kuggyon soha
//g_commmode=1;
if(g_commmode != 0) return(0);
/*
Serial.print("commmode ");
Serial.println(g_commmode);
*/
g_w_commpkt_counter++;
comm_packsh1(&len);
// delay(50);
Serial3.write((byte*)&g_w_commbuf[0],len);
// g_w_commpkt_counter=0;
g_commmode=1;
return(1);
}
int comm_read(int *state, unsigned char *buf, unsigned int *len)
{
int rval=-1,nr=0;
unsigned char c1;
unsigned char crc8;
// static unsigned long xx=0;
while(Serial3.available()) {
c1=(unsigned char)Serial3.read();
if(++nr >= 100) break;
switch(*state) {
case UCCB_PST_INIT:
case UCCB_PST_READY:
/*
Serial.print(*len);
Serial.print(" ");
Serial.print(c1);
Serial.println(" init/ready");
*/
if(c1 == UCCB_WD6BX_LEAD) {
*len=0;
buf[*len]=c1;
*state=UCCB_PST_DATA;
} else {
*state=UCCB_PST_INIT;
}
break;
case UCCB_PST_DATA:
/*
Serial.print(*len);
Serial.print(" ");
Serial.print(c1);
Serial.println(" data");
*/
(*len)++;
buf[*len]=c1;
if(*len == UCCB_WD6BX_PKTLAST) {
*state=UCCB_PST_CRC;
}
break;
case UCCB_PST_CRC:
/*
Serial.print(*len);
Serial.print(" ");
Serial.print(c1);
Serial.println(" crc1");
*/
if(*len != UCCB_WD6BX_PKTLAST) {
*state=UCCB_PST_INIT;
break;
}
(*len)++;
/*
Serial.print(*len);
Serial.print(" ");
Serial.print(c1);
Serial.println("crc2");
*/
crc8=getCRC(buf,*len);
/*
xx++;
Serial.print(xx);
Serial.print(" ");
Serial.print(c1);
Serial.print(" ");
Serial.println(crc8);
*/
if(crc8 != c1) {
*state=UCCB_PST_INIT;
break;
}
// Serial.println("crc3");
*state=UCCB_PST_READY;
return(UCCB_PST_READY);
default:
*state=UCCB_PST_INIT;
break;
}
}
return(rval);
}
int comm_unpack1(unsigned char *d, unsigned int l, unsigned char *buf, unsigned int *len)
{
memcpy((void*)d,(void*)(buf+*len),l);
(*len)+=l;
return(0);
}
int comm_unpackuccb(unsigned char *buf, unsigned long len,
unsigned long *commpkt_counter,
int16_t *battV,
int16_t *tsX,
int16_t *tsY,
int16_t *fsX,
int16_t *fsY,
int16_t *fsZ,
int16_t *fsBS,
int16_t *fsBE,
int16_t *stb,
int16_t *b6pBS,
int16_t *b6pBE,
int16_t *m1s,
int16_t *m2s,
int16_t *rdd,
int16_t *tsx,
int16_t *tsy,
byte *commmode)
{
unsigned int l;
l=1;
comm_unpack1((unsigned char *)commpkt_counter,sizeof(unsigned long),buf,&l);
comm_unpack1((unsigned char *)battV,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)tsX,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)tsY,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)fsX,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)fsY,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)fsZ,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)fsBS,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)fsBE,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)stb,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)b6pBS,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)b6pBE,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)m1s,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)m2s,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)rdd,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)tsx,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)tsy,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)commmode,sizeof(byte),buf,&l);
return(0);
}
int comm_recv(void)
{
int ret;
int16_t stb,m1s,m2s;
g_recv_ready=0;
if(g_commmode == 0) return(0);
ret=comm_read(&g_r_state,g_r_commbuf,&g_r_len);
if(ret == UCCB_PST_READY) {
comm_unpackuccb(g_r_commbuf,g_r_len,
&g_cb_w_commpkt_counter,
&g_cb_battV,
&g_cb_tsX,
&g_cb_tsY,
&g_cb_fsX,
&g_cb_fsY,
&g_cb_fsZ,
&g_cb_fsBS,
&g_cb_fsBE,
&stb,
&g_cb_b6pBS,
&g_cb_b6pBE,
&m1s,
&m2s,
&g_cb_rdd,
&g_cb_tsxp,
&g_cb_tsyp,
&g_commmode);
g_cb_sw10p=stb&UCCB_ST_SW10P;
if((int)(stb&UCCB_ST_M1) == 0) {
m1s=0;
g_cb_m1s=0;
}
if((int)(stb&UCCB_ST_M2) == 0) {
m2s=0;
g_cb_m2s=0;
}
g_cb_lightpos=(int)((stb&UCCB_ST_POSLIGHT)>>UCCB_PL_STPOS);
if(g_piro_scan == PIRO_MOTOR_FOLLOW) {
if((m1s != 0) || (m2s != 0)) {
g_piro_scan=PIRO_SCAN_STOP;
g_cb_m1s=m1s;
g_cb_m2s=m2s;
}
} else {
g_cb_m1s=m1s;
g_cb_m2s=m2s;
}
/*
Serial.print("fsY=");
Serial.println(g_cb_fsY);
*/
g_recv_ready=1;
return(1);
}
return(0);
}
int bxcu_comm(void)
{
comm_send();
comm_recv();
return(0);
}
<file_sep>#include "vnh5019.h"
int vnh5019_initTimers(void)
{
// Timer 1 configuration
// prescaler: clockI/O / 1
// outputs enabled
// phase-correct PWM
// top of 400
//
// PWM frequency calculation
// 16MHz / 1 (prescaler) / 2 (phase-correct) / 400 (top) = 20kHz
TCCR4A = 0b10101000;
TCCR4B = 0b00010001;
ICR4 = 400;
TCCR5A = 0b10101000;
TCCR5B = 0b00010001;
ICR5 = 400;
return(0);
}
// Constructors ////////////////////////////////////////////////////////////////
VNH5019MD::VNH5019MD(unsigned char INA, unsigned char INB, unsigned char PWM, unsigned char EN1DIAG, unsigned char EN2DIAG,
unsigned char CS, volatile uint16_t *OCR, int REINT, isr_ft isr_f)
{
//Pin map
_INA=INA;
_INB=INB;
_PWM=PWM;
_EN1DIAG=EN1DIAG;
_EN2DIAG=EN2DIAG;
_CS=CS;
_OCR=OCR;
_REINT=REINT;
_ISR_F=isr_f;
_speed=0;
}
// Public Methods //////////////////////////////////////////////////////////////
void VNH5019MD::init()
{
// Define pinMode for the pins and set the frequency for timer1.
pinMode(_INA,OUTPUT);
pinMode(_INB,OUTPUT);
pinMode(_PWM,OUTPUT);
pinMode(_EN1DIAG,INPUT_PULLUP);
pinMode(_EN2DIAG,INPUT_PULLUP);
pinMode(_CS,INPUT);
attachInterrupt(_REINT,_ISR_F,CHANGE);
/*
#if defined(__AVR_ATmega168__)|| defined(__AVR_ATmega328P__)
TCCR1A = 0b10100000;
TCCR1B = 0b00010001;
ICR1 = 400;
#endif
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
// Mega board specific stuff here - assumes assigning timer3, using pins 3 &5
TCCR1A = 0b10100000; // Mega pin 5
TCCR1B = 0b00010001; // Mega pin 3
ICR1 = 400;
#endif
*/
/*
TCCR1A = 0b10100000;
TCCR1B = 0b00010001;
ICR1 = 400;
*/
}
// Set speed for motor 1, speed is a number betwenn -400 and 400
void VNH5019MD::setSpeed(int speed)
{
unsigned char reverse = 0;
if(speed < 0) {
speed=-speed; // Make speed a positive quantity
reverse=1; // Preserve the direction
}
if(speed > 400) {// Max PWM dutycycle
speed=400;
}
*_OCR = speed;
if(reverse) {
digitalWrite(_INA,LOW);
digitalWrite(_INB,HIGH);
_speed=-speed;
} else {
digitalWrite(_INA,HIGH);
digitalWrite(_INB,LOW);
_speed=speed;
}
}
void VNH5019MD::incSpeed(int step)
{
int speed;
if(_speed >= 0) speed=_speed+step;
else speed=_speed-step;
setSpeed(speed);
}
int VNH5019MD::getSpeed(void)
{
return(_speed);
}
// Brake motor 1, brake is a number between 0 and 400
void VNH5019MD::setBrake(int brake)
{
// normalize brake
if(brake < 0) {
brake=-brake;
}
if(brake > 400) {// Max brake
brake=400;
}
digitalWrite(_INA,LOW);
digitalWrite(_INB,LOW);
*_OCR=brake;
}
// Return motor 1 current value in milliamps.
unsigned int VNH5019MD::getCurrentMilliamps()
{
// 5V / 1024 ADC counts / 144 mV per A = 34 mA per count
return analogRead(_CS) * 34;
}
// Return error status for motor 1
unsigned char VNH5019MD::getFault()
{
return !digitalRead(_EN1DIAG);
}
<file_sep>#include "wd6cumc.h"
byte g_wmd_commbuf[100]={0};
unsigned long g_wmd_sendtime=0;
unsigned long g_wmd_commpkt_send_counter=0; //total counter of sent packets
unsigned long g_wmd_commpkt_recv_counter=0; //total counter of received packets
byte g_rmd_commbuf[100]={0};
int g_rmd_state=WD6CUMC_PST_INIT;
unsigned int g_rmd_len=0;
int comm_setup(void)
{
Serial2.begin(500000);
buildCRCTable();
// tmr_init(&g_tmr_comm,250);
// tmr_init(&g_tmr_comm,125);
tmr_init(&g_tmr_comm,100);
}
int wd6md_comm_pack1(byte *d, uint16_t l, byte *buf, uint16_t *len)
{
if((*len+l) > sizeof(g_wmd_commbuf)) return(-1);
memcpy((void*)(buf+*len),(void*)d,l);
(*len)+=l;
return(0);
}
int wd6md_comm_packtscr(uint16_t *len)
{
byte lead=WD6CUMC_MC_LEAD;
byte crc8;
uint16_t x;
*len=0;
/*
Serial.print(rpm1);
Serial.print(" ");
Serial.println(rpm2);
*/
wd6md_comm_pack1((byte*)&lead,sizeof(lead),g_wmd_commbuf,len); //1:1
wd6md_comm_pack1((byte*)&g_loop_cps,sizeof(g_loop_cps),g_wmd_commbuf,len); //4:5
wd6md_comm_pack1((byte*)&g_wd6md_J1.re->rpm,sizeof(uint16_t),g_wmd_commbuf,len); //2:7
wd6md_comm_pack1((byte*)&g_wd6md_J2.re->rpm,sizeof(uint16_t),g_wmd_commbuf,len); //2:9
wd6md_comm_pack1((byte*)&g_wd6md_J3.re->rpm,sizeof(uint16_t),g_wmd_commbuf,len); //2:11
wd6md_comm_pack1((byte*)&g_wd6md_B1.re->rpm,sizeof(uint16_t),g_wmd_commbuf,len); //2:13
wd6md_comm_pack1((byte*)&g_wd6md_B2.re->rpm,sizeof(uint16_t),g_wmd_commbuf,len); //2:15
wd6md_comm_pack1((byte*)&g_wd6md_B3.re->rpm,sizeof(uint16_t),g_wmd_commbuf,len); //2:17
x=g_wd6md_J1.ra_mc->getAverage();
if(x < 50) x=0;
wd6md_comm_pack1((byte*)&x,sizeof(uint16_t),g_wmd_commbuf,len); //2:19
x=g_wd6md_J2.ra_mc->getAverage();
if(x < 50) x=0;
wd6md_comm_pack1((byte*)&x,sizeof(uint16_t),g_wmd_commbuf,len); //2:21
x=g_wd6md_J3.ra_mc->getAverage();
if(x < 50) x=0;
wd6md_comm_pack1((byte*)&x,sizeof(uint16_t),g_wmd_commbuf,len); //2:23
x=g_wd6md_B1.ra_mc->getAverage();
if(x < 50) x=0;
wd6md_comm_pack1((byte*)&x,sizeof(uint16_t),g_wmd_commbuf,len); //2:25
x=g_wd6md_B2.ra_mc->getAverage();
if(x < 50) x=0;
wd6md_comm_pack1((byte*)&x,sizeof(uint16_t),g_wmd_commbuf,len); //2:27
x=g_wd6md_B3.ra_mc->getAverage();
if(x < 50) x=0;
wd6md_comm_pack1((byte*)&x,sizeof(uint16_t),g_wmd_commbuf,len); //2:29
crc8=getCRC(g_wmd_commbuf,*len);
wd6md_comm_pack1((byte*)&crc8,sizeof(crc8),g_wmd_commbuf,len); //1:30
//30 byte long
return(0);
}
int comm_send(void)
{
unsigned int len;
if(g_force_send == 0) {
if(tmr_do(&g_tmr_comm) != 1) return(0);
}
g_force_send=0;
wd6md_comm_packtscr(&len);
Serial2.write((byte*)&g_wmd_commbuf[0],len);
g_wmd_commpkt_send_counter++;
return(1);
}
int comm_read(int *state, unsigned char *buf, unsigned int *len)
{
int rval=-1,ret,nr=0,i;
unsigned char c1;
unsigned char crc8;
// static unsigned long xx=0;
while(Serial2.available()) {
c1=(unsigned char)Serial2.read();
if(++nr >= 100) break;
switch(*state) {
case WD6CUMC_PST_INIT:
case WD6CUMC_PST_READY:
/*
Serial.print(*len);
Serial.print(" ");
Serial.print(c1);
Serial.println(" init/ready");
*/
if(c1 == WD6CUMC_CU_LEAD) {
*len=0;
buf[*len]=c1;
*state=WD6CUMC_PST_DATA;
} else {
*state=WD6CUMC_PST_INIT;
}
break;
case WD6CUMC_PST_DATA:
/*
Serial.print(*len);
Serial.print(" ");
Serial.print(c1);
Serial.println(" data");
*/
(*len)++;
buf[*len]=c1;
if(*len == WD6CUMC_CU_PKTLAST) {
*state=WD6CUMC_PST_CRC;
}
break;
case WD6CUMC_PST_CRC:
/*
Serial.print(*len);
Serial.print(" ");
Serial.print(c1);
Serial.println(" crc1");
*/
if(*len != WD6CUMC_CU_PKTLAST) {
*state=WD6CUMC_PST_INIT;
break;
}
(*len)++;
/*
Serial.print(*len);
Serial.print(" ");
Serial.print(c1);
Serial.println("crc2");
*/
crc8=getCRC(buf,*len);
// xx++;
// Serial.print(xx);
/*
Serial.print("crc= ");
Serial.print(millis());
Serial.print(" ");
Serial.print(*len);
Serial.print(" ");
Serial.print(c1);
Serial.print(" ");
Serial.println(crc8);
for(i=0;i < *len;i++) {
Serial.print(buf[i]);
Serial.print(" ");
}
Serial.println();
*/
if(crc8 != c1) {
*state=WD6CUMC_PST_INIT;
break;
}
// Serial.println("crc3");
*state=WD6CUMC_PST_READY;
return(WD6CUMC_PST_READY);
default:
*state=WD6CUMC_PST_INIT;
break;
}
}
return(rval);
}
int comm_unpack1(unsigned char *d, unsigned int l, unsigned char *buf, unsigned int *len)
{
memcpy((void*)d,(void*)(buf+*len),l);
(*len)+=l;
return(0);
}
int comm_unpackcu(unsigned char *buf, unsigned long len,
unsigned long *commpkt_counter,
int16_t *battV,
int16_t *tsX,
int16_t *tsY,
int16_t *fsX,
int16_t *fsY,
int16_t *fsZ,
int16_t *fsBS,
int16_t *fsBE,
int16_t *stb,
int16_t *b6pBS,
int16_t *b6pBE,
int16_t *m1s,
int16_t *m2s,
int16_t *rdd)
{
unsigned int l;
l=1;
comm_unpack1((unsigned char *)commpkt_counter,sizeof(unsigned long),buf,&l);
comm_unpack1((unsigned char *)battV,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)tsX,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)tsY,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)fsX,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)fsY,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)fsZ,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)fsBS,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)fsBE,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)stb,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)b6pBS,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)b6pBE,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)m1s,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)m2s,sizeof(int16_t),buf,&l);
comm_unpack1((unsigned char *)rdd,sizeof(int16_t),buf,&l);
return(0);
}
int comm_recv(void)
{
int ret,stb,pwr0,poslight;
ret=comm_read(&g_rmd_state,g_rmd_commbuf,&g_rmd_len);
if(ret == WD6CUMC_PST_READY) {
g_wmd_commpkt_recv_counter++;
if(g_wmd_commpkt_recv_counter < 5) return(0);
//Serial.print("read from central: ");
//Serial.println(millis());
comm_unpackcu(g_rmd_commbuf,g_rmd_len,
&g_wcu_commpkt_counter,
&g_cb_battV,
&g_cb_tsX,
&g_cb_tsY,
&g_cb_fsX,
&g_cb_fsY,
&g_cb_fsZ,
&g_cb_fsBS,
&g_cb_fsBE,
&stb,
&g_cb_b6pBS,
&g_cb_b6pBE,
&g_cb_m1s,
&g_cb_m2s,
&g_cb_rdd);
/*
if(g_cb_m1s > 500) {
Serial.print("xxm1s: ");
Serial.print(g_rmd_len);
Serial.print(" ");
Serial.println(g_cb_m1s);
}
*/
return(1);
}
return(0);
}
int wd6cumd_comm(void)
{
comm_send();
comm_recv();
}
<file_sep>#define SMAR_TOT_IDX 10
#define SMAR_TOT_NUM 31
typedef struct tagSMAR {
int tbl[SMAR_TOT_NUM];
int idx;
int sum;
int portmap;
int lvv;
unsigned int lvc;
unsigned int avn;
unsigned int eqn;
unsigned long lvt;
} SMAR;
SMAR smar[SMAR_TOT_IDX]={0};
int smar_setportidx(int port)
{
int rval=-1,i;
for(i=0;i < SMAR_TOT_IDX;i++) {
if(smar[i].portmap == -1) {
smar[i].portmap=port;
rval=i;
break;
}
}
return(rval);
}
int smar_getportidx(int port)
{
int rval=-1,i;
for(i=0;i < SMAR_TOT_IDX;i++) {
if(smar[i].portmap == port) {
rval=i;
break;
}
}
return(rval);
}
int smar_setup(void)
{
int i;
for(i=0;i < SMAR_TOT_IDX;i++) {
smar[i].portmap=-1;
smar[i].lvv=-1;
smar[i].avn=1;
smar[i].eqn=1;
smar[i].lvt=0;
}
// Serial.begin(9600);
return(0);
}
int smar_init(int port, unsigned int avn, unsigned int eqn)
{
int rval=-1,i,iport;
iport=smar_setportidx(port);
if((iport < 0) || (iport >= SMAR_TOT_IDX)) goto end;
if(avn > SMAR_TOT_NUM) goto end;
if(eqn > 20) goto end;
for(i=0;i < SMAR_TOT_NUM;i++) {
smar[iport].tbl[i]=0;
}
smar[iport].avn=avn;
smar[iport].eqn=eqn;
rval=0;
end:
return(rval);
}
int smar_analogRead(int port)
{
int rval=-1,iport,v,lvch=0,d;
iport=smar_getportidx(port);
if((iport < 0) || (iport >= SMAR_TOT_IDX)) goto end;
smar[iport].sum-=smar[iport].tbl[smar[iport].idx];
smar[iport].tbl[smar[iport].idx]=analogRead(port);
// Serial.println(smar_tbl[iport][smar_idx[iport]]);
smar[iport].sum+=smar[iport].tbl[smar[iport].idx];
smar[iport].idx=(smar[iport].idx+1)%smar[iport].avn;
v=smar[iport].sum/smar[iport].avn;
/*
if(iport == 0) {
Serial.print(smar[iport].tbl[smar[iport].idx]);
Serial.print(" ");
Serial.print(smar[iport].lvv);
Serial.print(" ");
Serial.print(smar[iport].lvc);
Serial.print(" ");
Serial.println(v);
}
*/
if(smar[iport].lvv < 0) {
smar[iport].lvv=v;
smar[iport].lvc=0;
rval=v;
} else {
if(smar[iport].lvv == v) {
smar[iport].lvc=0;
smar[iport].lvt=g_millis;
rval=v;
} else {
if(smar[iport].lvc++ > smar[iport].eqn) {
d=smar[iport].lvv-v;
d=abs(d);
if(d <= 3) {
if((g_millis-smar[iport].lvt) > 300) lvch=1;
} else {
lvch=1;
}
if(lvch == 1) {
smar[iport].lvv=v;
smar[iport].lvc=0;
rval=v;
} else {
rval=smar[iport].lvv;
}
} else {
rval=smar[iport].lvv;
}
}
}
end:
return(rval);
}
<file_sep>#ifndef __WD6MD_H_INCLUDED__
#define __WD6MD_H_INCLUDED__
#include "sh1tmr.h"
#include "RunningAverage.h"
typedef struct tagWD6MDAM {
uint8_t go;
unsigned long ics;
unsigned long ic;
} WD6MDAM;
typedef struct tagWD6MD {
const char *name;
VNH5019MD *md;
WD6RE *re;
RunningAverage *ra_mc;
unsigned char overloaded;
WD6MDAM am;
MYTMR tmr_rpm;
} WD6MD;
typedef struct tagWD6MDTRACE {
float dist; // distance
int msr; // right speed
int msl; // left speed
} WD6MDTRACE;
#endif /* __WD6MD_H_INCLUDED__ */
<file_sep>//wd6 arduino
#include "vnh5019.h"
#include "wd6re.h"
#include "wd6mtr.h"
#include "sh1tmr.h"
VNH5019MD g_md_J3(28,29,8,26,27,A3,&OCR4C,5,wd6re_isrJ3);
VNH5019MD g_md_B3(40,41,46,38,39,A6,&OCR5A,2,wd6re_isrB3);
WD6RE g_wd6re_J1={0};
WD6RE g_wd6re_J2={0};
WD6RE g_wd6re_J3={0};
WD6RE g_wd6re_B1={0};
WD6RE g_wd6re_B2={0};
WD6RE g_wd6re_B3={0};
WD6MTR g_mtrJ3={0};
WD6MTR g_mtrB3={0};
unsigned long g_millis=0;
unsigned char g_rb=0;
unsigned long g_chmst=0; //change motor speed time
int g_msn=0,g_mso=0;
<file_sep>int batt_setup(void)
{
int i,avn;
avn=7;
smar_init(UCCB_BATTV_PORT,avn,5);
//fill the buffer
for(i=0;i < 2*avn;i++) {
smar_analogRead(UCCB_BATTV_PORT);
}
avn=11;
smar_init(UCCB_BATTA_PORT,avn,8);
//fill the buffer
for(i=0;i < 2*avn;i++) {
smar_analogRead(UCCB_BATTA_PORT);
}
return(0);
}
int batt_read(int16_t *battV, int16_t *battA)
{
static unsigned long l_brtv=0,l_brta=0;
static int l_bv=0;
static int l_ba=0;
if((g_millis-l_brtv) >= 500) {
l_bv=smar_analogRead(UCCB_BATTV_PORT);
l_brtv=g_millis;
}
if((g_millis-l_brta) >= 25) {
l_ba=smar_analogRead(UCCB_BATTA_PORT);
l_brta=g_millis;
}
*battV=l_bv;
*battA=l_ba;
return(0);
}
<file_sep>int stmdmtr_setup(void)
{
g_mtrJ3.name="J3";
g_mtrJ3.md=&g_md_J3;
g_mtrJ3.re=&g_wd6re_J3;
tmr_init(&g_mtrJ3.tmr_rpm,100);
g_mtrB3.name="B3";
g_mtrB3.md=&g_md_B3;
g_mtrB3.re=&g_wd6re_B3;
tmr_init(&g_mtrB3.tmr_rpm,100);
return(0);
}
int stmdmtr_setrpm(WD6MTR *mtr, int rpm)
{
if(tmr_do(&mtr->tmr_rpm) != 1) return(0);
if(mtr->re->rpm == rpm) return(0);
if(mtr->re->rpm < rpm) {
mtr->md->incSpeed(1);
Serial.print(mtr->name);
Serial.print("+");
Serial.print(g_millis);
Serial.print(" ");
Serial.print(mtr->re->rpm);
Serial.print(" ");
Serial.println(mtr->md->getSpeed());
} else {
Serial.print(mtr->name);
Serial.print("-");
Serial.print(g_millis);
Serial.print(" ");
Serial.print(mtr->re->rpm);
Serial.print(" ");
Serial.println(mtr->md->getSpeed());
mtr->md->incSpeed(-1);
}
return(1);
}
<file_sep>#include "wd6re.h"
#define WD6RE_ICNC_TIME 400 //interrupt counter not changed, zero speed
void wd6re_setup() {
g_wd6re_J1.tbi=1;
g_wd6re_J2.tbi=1;
g_wd6re_J3.tbi=1;
g_wd6re_B1.tbi=1;
g_wd6re_B2.tbi=1;
g_wd6re_B3.tbi=1;
g_wd6re_J1.num_tbi=WD6RE_TBI_NUM;
g_wd6re_J2.num_tbi=WD6RE_TBI_NUM;
g_wd6re_J3.num_tbi=WD6RE_TBI_NUM;
g_wd6re_B1.num_tbi=WD6RE_TBI_NUM;
g_wd6re_B2.num_tbi=WD6RE_TBI_NUM;
g_wd6re_B3.num_tbi=WD6RE_TBI_NUM;
}
uint16_t qe_rpm_tbi(WD6RE *wd6re)
{
unsigned long tbi;
unsigned long atbi;
// int i;
/*
Serial.print("xx ");
Serial.print(l_r0,DEC);
Serial.print(" ");
Serial.println(g_wd6re_ic1,DEC);
*/
if(wd6re->ico == wd6re->ic) {
if(g_millis > wd6re->l_t0+WD6RE_ICNC_TIME) {
wd6re->l_sum=0;
wd6re->l_tbi[0]=0;
wd6re->l_idx=0;
wd6re->l_rpm=0;
return(wd6re->l_rpm);
} else {
return(wd6re->l_rpm);
}
} else {
wd6re->l_t0=g_millis;
wd6re->ico=wd6re->ic;
noInterrupts();
tbi=wd6re->tbi;
interrupts();
}
/*
Serial.print("xx ");
Serial.print(l_r0,DEC);
Serial.print(" ");
Serial.print(g_wd6re_ic1,DEC);
Serial.print(" ");
Serial.print(dtx,DEC);
Serial.print(" ");
Serial.println(g_millis-l_t0,DEC);
*/
if(tbi > 1000UL*WD6RE_ICNC_TIME) {
wd6re->l_sum=0;
wd6re->l_tbi[0]=0;
wd6re->l_idx=0;
wd6re->l_rpm=0;
return(wd6re->l_rpm);
}
wd6re->l_sum+=tbi;
wd6re->l_idx++;
wd6re->l_idx%=wd6re->num_tbi;
if(wd6re->l_tbi[0] == 0) {
if(wd6re->l_idx == 0) {
atbi=wd6re->l_sum/wd6re->num_tbi;
} else {
atbi=wd6re->l_sum/wd6re->l_idx;
}
} else {
wd6re->l_sum-=wd6re->l_tbi[wd6re->l_idx];
atbi=wd6re->l_sum/wd6re->num_tbi;
}
wd6re->l_tbi[wd6re->l_idx]=tbi;
/*
for(i=0;i < WD6RE_TBI_NUM;i++) {
Serial.print(l_tbi[i]);
Serial.print(" ");
}
Serial.println("");
*/
/*
Serial.print("1b ");
Serial.print(dt,DEC);
Serial.print(" ");
Serial.print(dtx,DEC);
Serial.print(" ");
Serial.print(l_sum,DEC);
Serial.print(" ");
Serial.println(atbi,DEC);
*/
// wd6re->l_rpm=1000000UL/atbi;
wd6re->l_rpm=1400000UL/atbi;
// l_rpm=2000000UL/atbi;
return(wd6re->l_rpm);
}
int wd6re_readrpm(WD6MD *wd6md)
{
WD6RE *wd6re;
wd6re=wd6md->re;
wd6re->rpm=qe_rpm_tbi(wd6re);
if(wd6re->rpm != wd6re->rpmo) {
/*
Serial.print(g_millis);
Serial.print(" rpm=");
Serial.print(wd6re->rpmo);
Serial.print(" ");
Serial.println(wd6re->rpm);
*/
wd6re->rpmo=wd6re->rpm;
}
return(0);
}
void wd6re_loop()
{
wd6re_readrpm(&g_wd6md_J1);
wd6re_readrpm(&g_wd6md_J2);
wd6re_readrpm(&g_wd6md_J3);
wd6re_readrpm(&g_wd6md_B1);
wd6re_readrpm(&g_wd6md_B2);
wd6re_readrpm(&g_wd6md_B3);
/*
g_wd6re_B3.rpm=qe_rpm_tbi(&g_wd6re_B3);
if(g_wd6re_B3.rpm != g_wd6re_B3.rpmo) {
Serial.print(g_millis);
Serial.print(" rpm=");
Serial.print(g_wd6re_B3.rpm);
Serial.print(" ");
Serial.println(g_wd6re_J3.rpm);
g_wd6re_B3.rpmo=g_wd6re_B3.rpm;
}
if(g_wd6re_B3.ico != g_wd6re_B3.ic) {
g_wd6re_B3.ico=g_wd6re_B3.ic;
}
g_wd6re_J3.rpm=qe_rpm_tbi(&g_wd6re_J3);
if(g_wd6re_J3.rpm != g_wd6re_J3.rpmo) {
Serial.print(g_millis);
Serial.print(" rpm=");
Serial.print(g_wd6re_B3.rpm);
Serial.print(" ");
Serial.println(g_wd6re_J3.rpm);
g_wd6re_J3.rpmo=g_wd6re_J3.rpm;
}
if(g_wd6re_J3.ico != g_wd6re_J3.ic) {
// Serial.println(g_wd6re_ic1);
g_wd6re_J3.ico=g_wd6re_J3.ic;
}
*/
}
void wd6re_isrJ1(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_J1.ic++;
mm=micros();
g_wd6re_J1.tbi=mm-l_t0;
l_t0=mm;
}
void wd6re_isrJ2(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_J2.ic++;
mm=micros();
g_wd6re_J2.tbi=mm-l_t0;
l_t0=mm;
}
void wd6re_isrJ3(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_J3.ic++;
mm=micros();
g_wd6re_J3.tbi=mm-l_t0;
l_t0=mm;
}
void wd6re_isrB1(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_B1.ic++;
mm=micros();
g_wd6re_B1.tbi=mm-l_t0;
l_t0=mm;
}
void wd6re_isrB2(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_B2.ic++;
mm=micros();
g_wd6re_B2.tbi=mm-l_t0;
l_t0=mm;
}
void wd6re_isrB3(void)
{
static volatile unsigned long l_t0=0;
unsigned long mm;
g_wd6re_B3.ic++;
mm=micros();
g_wd6re_B3.tbi=mm-l_t0;
l_t0=mm;
}
<file_sep>#define WD6_MIN_NZ_SPEED ((WD6_MIN_SPEED)+4)
#define WD6_MIN_RPM 6
#define WD6_MAX_RPM 90
int wd6md_setup(void)
{
g_wd6md_J1.name="J1";
g_wd6md_J1.md=&g_md_J1;
g_wd6md_J1.re=&g_wd6re_J1;
tmr_init(&g_wd6md_J1.tmr_rpm,100);
g_wd6md_J1.ra_mc=&g_wd6md_J1_mc;
g_wd6md_J1.overloaded=0;
g_wd6md_J2.name="J2";
g_wd6md_J2.md=&g_md_J2;
g_wd6md_J2.re=&g_wd6re_J2;
tmr_init(&g_wd6md_J2.tmr_rpm,100);
g_wd6md_J2.ra_mc=&g_wd6md_J2_mc;
g_wd6md_J2.overloaded=0;
g_wd6md_J3.name="J3";
g_wd6md_J3.md=&g_md_J3;
g_wd6md_J3.re=&g_wd6re_J3;
tmr_init(&g_wd6md_J3.tmr_rpm,100);
g_wd6md_J3.ra_mc=&g_wd6md_J3_mc;
g_wd6md_J3.overloaded=0;
g_wd6md_B1.name="B1";
g_wd6md_B1.md=&g_md_B1;
g_wd6md_B1.re=&g_wd6re_B1;
tmr_init(&g_wd6md_B1.tmr_rpm,100);
g_wd6md_B1.ra_mc=&g_wd6md_B1_mc;
g_wd6md_B1.overloaded=0;
g_wd6md_B2.name="B2";
g_wd6md_B2.md=&g_md_B2;
g_wd6md_B2.re=&g_wd6re_B2;
tmr_init(&g_wd6md_B2.tmr_rpm,100);
g_wd6md_B2.ra_mc=&g_wd6md_B2_mc;
g_wd6md_B2.overloaded=0;
g_wd6md_B3.name="B3";
g_wd6md_B3.md=&g_md_B3;
g_wd6md_B3.re=&g_wd6re_B3;
tmr_init(&g_wd6md_B3.tmr_rpm,100);
g_wd6md_B3.ra_mc=&g_wd6md_B3_mc;
g_wd6md_B3.overloaded=0;
tmr_init(&g_tmr_rmc,20);
return(0);
}
int wd6md_setrpm(WD6MD *wd6md, int rpm, int dir)
{
int sd,rpmd,stp;
if(tmr_do(&wd6md->tmr_rpm) != 1) return(0);
if(wd6md->re->rpm == rpm) return(0);
/*
if(wd6md->re->rpm == 0){
if(wd6md->tmr_rpm.cnt%2 == 0) return(0);
}
*/
//Serial.print(wd6md->name);
if(wd6md->re->rpm < rpm) {
sd=1;
//Serial.print("+");
} else {
sd=-1;
//Serial.print("-");
}
rpmd=wd6md->re->rpm-rpm;
rpmd=abs(rpmd);
//Serial.print(rpmd);
//Serial.print(" ");
if(wd6md->re->rpm == 0) {
stp=4;
} else {
if(rpmd <= 1) stp=1;
else if(rpmd <= 2) stp=2;
else if(rpmd <= 3) stp=4;
else if(rpmd <= 10) stp=rpmd*2;
else stp=rpmd*3;
}
stp=stp*sd;
/*
Serial.print(wd6md->re->rpm);
Serial.print(" ");
Serial.print(rpm);
Serial.print(" ");
Serial.print(stp);
Serial.print(" ");
Serial.println(wd6md->md->getSpeed());
*/
wd6md->md->incSpeed(stp,dir);
return(1);
}
int wd6md_readcurrent(void)
{
static char l_idx=0;
WD6MD *wd6md;
unsigned int mc;
if(tmr_do(&g_tmr_rmc) != 1) return(0);
if(l_idx == 0) {
wd6md=&g_wd6md_J1;
} else if(l_idx == 1) {
wd6md=&g_wd6md_J2;
} else if(l_idx == 2) {
wd6md=&g_wd6md_J3;
} else if(l_idx == 3) {
wd6md=&g_wd6md_B1;
} else if(l_idx == 4) {
wd6md=&g_wd6md_B2;
} else if(l_idx == 5) {
wd6md=&g_wd6md_B3;
} else return(-1);
mc=wd6md->md->getCurrentMilliamps();
wd6md->ra_mc->addValue(mc);
if(wd6md->ra_mc->getAverage() > 4000) {
if(wd6md->overloaded < 10) wd6md->overloaded++;
} else {
wd6md->overloaded=0;
}
l_idx++;
l_idx%=6;
return(0);
}
int wd6md_setspeed1(int16_t ms, int16_t *ms_p, WD6MD *wd6md1, WD6MD *wd6md2, WD6MD *wd6md3)
{
uint16_t rpm;
int dir=1,msd;
if((ms >= 0) && (ms < WD6_MIN_SPEED)) ms=0;
else if((ms < 0) && (-ms < WD6_MIN_SPEED)) ms=0;
if(ms < 0) dir=-1;
msd=ms-*ms_p;
msd=abs(msd);
// if(*ms_p == ms) {
if(msd <= 1) {
if(*ms_p == 0) {
wd6md1->md->setSpeed(0);
wd6md2->md->setSpeed(0);
wd6md3->md->setSpeed(0);
*ms_p=ms;
return(0);
}
if((rpm=wd6md1->re->rpm) == 0) {
if((rpm=wd6md2->re->rpm) == 0) {
rpm=wd6md3->re->rpm;
}
if(rpm < WD6_MIN_RPM) rpm=WD6_MIN_RPM;
}
if(abs(ms) <= WD6_MIN_NZ_SPEED) {
rpm=WD6_MIN_RPM;
}
// Serial.print("RPM: ");
// Serial.println(rpm);
wd6md_setrpm(wd6md1,rpm,dir);
wd6md_setrpm(wd6md2,rpm,dir);
wd6md_setrpm(wd6md3,rpm,dir);
// *ms_p=ms;
return(0);
}
// if((ms > *ms_p) && (wd6md1->md->getSpeed() >= ms)) return(0);
// if((ms < *ms_p) && (wd6md1->md->getSpeed() <= ms)) return(0);
wd6md1->md->setSpeed(ms);
msd=wd6md2->md->getSpeed()-ms;
msd=abs(msd);
if(msd > 4) {
wd6md2->md->setSpeed(ms);
}
msd=wd6md3->md->getSpeed()-ms;
msd=abs(msd);
if(msd > 4) {
wd6md3->md->setSpeed(ms);
}
*ms_p=ms;
return(0);
}
int wd6md_am_go(unsigned long dist, int16_t msr, int16_t msl)
{
WD6MD *wd6md1;
long x;
uint8_t ic;
if(g_wd6md_am_go == 0) {
wd6md_setspeed(0,0);
return(0);
}
wd6md1=&g_wd6md_J2;
if(wd6md1->am.go == 0) {
wd6md1->am.go=1;
wd6md1->am.ics=1;
wd6md1->am.ic=wd6md1->re->ic;
} else {
ic=wd6md1->re->ic;
x=(long)ic-wd6md1->am.ic;
if(x < 0) x+=256;
wd6md1->am.ic=ic;
wd6md1->am.ics+=x;
}
wd6md_setspeed(msr,msl);
if(wd6md1->am.ics >= (abs(dist)/1.57)) {
wd6md_setspeed(0,0);
wd6md1->am.go=0;
g_wd6md_am_go=0;
return(1);
}
return(0);
}
int wd6md_am_turn(unsigned long turn, int16_t ms)
{
unsigned long dist;
dist=3;
if(ms >= 0) {
wd6md_am_go(dist,ms,-ms);
} else {
wd6md_am_go(dist,-ms,ms);
}
return(0);
}
int wd6md_am(void)
{
int ret;
WD6MDTRACE tr[3]={
{300.0,400,400},
{200.0,-400,-400},
{100.0,-150,-150}
// {30,-100,-100}
};
if(g_cb_b6pBE == 11) {
g_wd6md_am=1;
g_wd6md_am_go=1;
g_wd6md_am_goidx=0;
return(0);
}
if(g_cb_b6pBE == 41) {
g_wd6md_am=0;
g_wd6md_am_go=0;
g_wd6md_am_goidx=-1;
return(0);
}
if(g_wd6md_am == 0) return(0);
if((g_wd6md_am_goidx >= sizeof(tr)/sizeof(tr[0])) || (g_wd6md_am_goidx < 0)) {
g_wd6md_am=0;
g_wd6md_am_go=0;
g_wd6md_am_goidx=-1;
return(0);
}
ret=wd6md_am_go(tr[g_wd6md_am_goidx].dist,tr[g_wd6md_am_goidx].msr,tr[g_wd6md_am_goidx].msl);
if(ret == 1) {
g_wd6md_am_go=1;
g_wd6md_am_goidx++;
delay(100);
}
return(0);
}
int wd6md_setspeed(int16_t msr, int16_t msl)
{
static int16_t l_m1s=0;
static int16_t l_m2s=0;
wd6md_setspeed1(msr,&l_m1s,&g_wd6md_J1,&g_wd6md_J2,&g_wd6md_J3);
wd6md_setspeed1(msl,&l_m2s,&g_wd6md_B1,&g_wd6md_B2,&g_wd6md_B3);
return(0);
}
int wd6md_mm(void)
{
if((g_wd6md_am != 0) && ((g_cb_m1s != 0) || (g_cb_m2s != 0))) {
g_wd6md_am=0;
g_wd6md_am_go=0;
g_wd6md_am_goidx=-1;
wd6md_setspeed(0,0);
return(0);
}
if(g_wd6md_am == 1) return(0);
wd6md_setspeed(g_cb_m1s,g_cb_m2s);
return(0);
}
int wd6md_setspeedx(void)
{
static int16_t l_m1s=0;
static int16_t l_m2s=0;
static unsigned long l_millis=0;
static int ms=65;
if(g_millis <= l_millis+2000) return(0);
l_millis=g_millis;
wd6md_setspeed1(ms,&l_m1s,&g_wd6md_J1,&g_wd6md_J2,&g_wd6md_J3);
wd6md_setspeed1(ms,&l_m2s,&g_wd6md_B1,&g_wd6md_B2,&g_wd6md_B3);
g_cb_m1s=ms;
ms++;
return(0);
}
<file_sep>void setup() {
g_millis=millis();
// put your setup code here, to run once:
Serial.begin(115200);
Serial2.begin(500000);
delay(1000);
Serial.println("motor test");
g_md_J3.init();
g_md_B3.init();
vnh5019_initTimers();
wd6re_setup();
stmdmtr_setup();
}
void loop() {
g_millis=millis();
wd6re_loop();
// put your main code here, to run repeatedly:
if(Serial2.available() > 0) {
g_rb=Serial2.read();
g_rb+=100;
Serial2.write((byte*)&g_rb,1);
}
stmdmtr_setrpm(&g_mtrJ3,3);
stmdmtr_setrpm(&g_mtrB3,7);
/*
if((g_millis-g_chmst) > 4000) {
g_chmst=g_millis;
g_msn++;
g_msn%=3;
}
if((g_msn == 0) && (g_msn != g_mso)) {
Serial.println("60");
g_mtrB3.md->setSpeed(60);
g_mtrJ3.md->setSpeed(60);
g_mso=g_msn;
} else if((g_msn == 1) && (g_msn != g_mso)) {
Serial.println("0");
g_mtrB3.md->setSpeed(0);
g_mtrJ3.md->setSpeed(0);
g_mso=g_msn;
} else if((g_msn == 2) && (g_msn != g_mso)) {
Serial.println("100");
g_mtrB3.md->setSpeed(100);
g_mtrJ3.md->setSpeed(100);
g_mso=g_msn;
}
*/
// delay(2000);
}
<file_sep>//cbox
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);
unsigned char g_rb=0;
unsigned char g_wb=0;
void setup() {
// put your setup code here, to run once:
// Serial.begin(112500);
Serial2.begin(19200);
lcd.begin(20, 4);
lcd.setCursor(0,0);
lcd.print("wd6 test");
}
void loop() {
// put your main code here, to run repeatedly:
//Serial.println("aaaaaa\n");
if(Serial2.available() > 0) {
g_rb=Serial2.read();
// Serial.println(g_rb);
lcd.setCursor(0,1);
lcd.print(g_rb);
g_rb+=50;
// delay(250);
Serial2.write((byte*)&g_rb,1);
}
// g_wb++;
// Serial2.write((byte*)&g_wb,1);
// delay(500);
}
|
ecaf8730cb7fcdb51044fedb99b67cea43e376c6
|
[
"C",
"C++"
] | 29
|
C++
|
topanka/wd6
|
049880b7eb9ee173cb0b780976b099b377eba7a5
|
de8a7af6820c4b146f12a9de24b5e8bebb26a510
|
refs/heads/master
|
<repo_name>hkovvuru/node-mongo-app<file_sep>/src/index.js
import bodyparser from 'body-parser';
import express from 'express';
import router from '../src/router-connection/router-methods';
// calls the express function
const app = express();
app.use(bodyparser.json());
app.use('/api', router);
const students = [{}];
// get the student details
router.get('/', (req, res) => {
res.json(students);
});
// created server at port 5000
app.listen(5000, () => {
console.log('Sever listening at port number 5000');
});
<file_sep>/src/router-connection/router-methods.js
import express from 'express';
import bodyparser from 'body-parser';
import Student from '../database-model/db-connection';
const app = express();
// tells the system to use JSON fromat data
app.use(bodyparser.json());
// define the routing using the express method
const router = express.Router();
// Mount the router as middleware at path /Stud
app.use('/stud', router);
// get all student details list from database
router.get('/stud', (req, res) => {
if (!req.body) {
return res.status(400).send({ message: 'Student Cannot be empty!' });
}
Student.find({}).then((data) => {
res.send(data);
}).catch((error) => {
console.error(error.message);
res.send({ err: error.message });
});
return 'get the data successfully';
});
// Get the data with name parameter
router.get('/stud/:name', (req, res) => {
if (!req.body) {
return res.status(400).send({ message: 'Person Cannot be empty!' });
}
Student.find({ name: req.params.name }).then((data) => {
res.send(data);
}).catch((error) => {
console.error(error.message);
res.send({ err: error.message });
});
return 'get the data successfully';
});
// add a new member to database using Post method
router.post('/stud', (req, res) => {
if (!req.body) {
return res.status(400).send({ message: 'Student Cannot be empty!' });
}
Student.create(req.body).then((stud) => {
res.status(201).json(stud);
// console.log('Post the data successfully');
}).catch((error) => {
console.error(error.message);
res.send({ err: error.message });
});
return 'post the data successfully';
});
// update student data
router.put('/stud/:id', (req, res) => {
if (!req.body) {
return res.status(400).send({ message: 'Student Cannot be empty!' });
}
Student.findById(req.params.id, (err, data) => {
// data.name = req.body[0].name;
console.log('data => ', data);
data.save(() => {
if (err) { res.send(err); }
res.json(data);
});
res.send(data);
// console.log('update the data successfully');
});
return 'put/update the data successfully';
});
// delete a data from database with parameter id
router.delete('/stud/:id', (req, res) => {
if (!req.body) {
return res.status(400).send({ message: 'Student Cannot be empty!' });
}
Student.findByIdAndRemove({ _id: req.params.id }).then((data) => {
res.send(data);
// console.log('Delete the data successfully');
}).catch((error) => {
console.error(error.message);
res.send({ err: error.message });
});
return 'delete the data successfully';
});
// Removing all students data from the database
router.delete('/stud', (req, res) => {
if (!req.body) {
return res.status(400).send({ message: 'Student Cannot be empty!' });
}
Student.remove().then((data) => {
// Student.remove().exec();
res.send(`${data.n} - Entries Deleted Sucessfully!!`);
// console.log('Deleted total data successfully');
}).catch((error) => {
console.error(error.message);
res.send({ err: error.message });
});
return 'Deleted total data successfully';
});
// pagination methods
router.get('/stud-details/:page', (req, res) => {
const perPage = 5;
const page = req.params.page || 1;
Student
.find({})
.skip((perPage * page) - perPage)
.limit(perPage)
.then((docs) => {
if (docs.length === 0) { console.log('There are no results matching your query.'); }
else {
Student.count({})
.then((number) => {
res.status(200).json(docs);
// fetch no.of records in the db
console.log(JSON.stringify({ number }));
});
}
})
.catch((err) => {
console.log(err.message);
});
});
// create the data in the database
router.post('/stud-details', (req, res) => {
if (!req.body) { console.log(res.status(400).send({ message: 'Student Cannot be empty!' })); }
Student.create(req.body).then((stud) => {
res.status(201).json(stud);
// console.log('Post the data successfully');
}).catch((error) => {
console.error(error.message);
res.send({ err: error.message });
});
});
/* router.get('/stud-details/:pageNo', (req, res,next) => {
const recordsPerPage = 5;
const pageNumber = req.params.pageNo || 1;
Student
.find({})
.skip((recordsPerPage * pageNumber) - recordsPerPage)
.limit(recordsPerPage)
.then((docs) => {
if (docs.length === 0)
console.log('hello No data is there ');
else
Student
.count({})
.then((totalRecords) => {
res.status(200).json(docs);
console.log(JSON.stringify({ totalRecords }));
});
})
.catch((error) => {
console.log(error.message);
res.send(error.message);
})
}); */
// Export the router
export default router;
|
6bb2be500a676d0ca8b434ec90c84842a3ffbde9
|
[
"JavaScript"
] | 2
|
JavaScript
|
hkovvuru/node-mongo-app
|
22730c498b6b43c0c7ffdd691b2451ebcfc26e1a
|
d22ce86ae1c016c34004283a2e7feee08739909a
|
refs/heads/master
|
<file_sep>const { EventEmitter } = require("events");
const doc = require("./doc");
const keyboard = require("./input/keyboard");
const senders = require("../senders");
const { white, rgb_to_hex, hex_to_rbg, lospec_palette } = require("../libtextmode/palette");
class PaletteChooser extends EventEmitter {
select_attribute() {
senders.send_sync("select_attribute", { fg: this.fg, bg: this.bg, palette: doc.palette });
}
constructor() {
super();
this.fg_index = 7;
this.bg_index = 0;
doc.on("new_document", () => this.new_document());
doc.on("update_swatches", () => this.update_swatches());
doc.on("set_bg", (index) => this.bg = index);
doc.on("change_palette", (lospec_palette_name) => this.change_palette(lospec_palette_name));
keyboard.on("previous_foreground_color", () => this.previous_foreground_color());
keyboard.on("next_foreground_color", () => this.next_foreground_color());
keyboard.on("previous_background_color", () => this.previous_background_color());
keyboard.on("next_background_color", () => this.next_background_color());
keyboard.on("toggle_fg", (index) => this.toggle_fg(index));
keyboard.on("toggle_bg", (index) => this.toggle_bg(index));
senders.on("previous_foreground_color", () => this.previous_foreground_color());
senders.on("next_foreground_color", () => this.next_foreground_color());
senders.on("previous_background_color", () => this.previous_background_color());
senders.on("next_background_color", () => this.next_background_color());
senders.on("default_color", () => this.default_color());
senders.on("switch_foreground_background", () => this.switch_foreground_background());
senders.on("set_fg", (e, new_fg) => this.fg = new_fg);
senders.on("set_bg", (e, new_bg) => {
this.bg = new_bg;
if (doc.connection) doc.connection.set_bg(this.bg);
});
}
new_document() {
this.color_picker_el = document.getElementById("color_picker")
this.swatch_container_el = document.getElementById("swatches");
this.bind_events();
this.update_swatches();
this.default_color();
}
bind_events() {
this.swatch_container_el.addEventListener("mousedown", (e) => {
if (!e.target.dataset.id) return;
clearTimeout(this.click_timer);
this.click_timer = setTimeout(() => {
if (e.button === 2 || e.ctrlKey) {
this.bg_internal = e.target.dataset.id;
} else {
this.fg = e.target.dataset.id;
}
}, 175);
});
this.swatch_container_el.addEventListener("dblclick", (e) => {
clearTimeout(this.click_timer);
this.color_picker_spawner = e.target;
this.color_picker_el.value = rgb_to_hex(doc.palette[e.target.dataset.id]);
this.color_picker_el.click();
});
// this.color_picker_el.addEventListener("input", (e) => this.color_picked(e.target.value));
this.color_picker_el.addEventListener("change", (e) => this.color_picked(e.target.value));
}
color_picked(hex) {
if (!hex || this.color_picker_spawner.style.backgroundColor === hex) return;
clearTimeout(this.paint_timer);
this.paint_timer = setTimeout(() => {
this.color_picker_spawner.style.backgroundColor = hex;
const id = parseInt(this.color_picker_spawner.dataset.id, 10)
if (this.bg_index === id) document.getElementById('bg').style.backgroundColor = hex;
if (this.fg_index === id) document.getElementById('fg').style.backgroundColor = hex;
doc.update_palette(parseInt(this.color_picker_spawner.dataset.id, 10), hex_to_rbg(hex));
}, 150);
}
update_swatches() {
this.swatch_container_el.innerHTML = "";
let container = document.createElement("section");
container.classList.add("base")
this.swatch_container_el.appendChild(container)
doc.palette.map((rgb, i) => {
const div = document.createElement("div");
div.style.backgroundColor = rgb_to_hex(rgb);
div.dataset.id = i;
container.appendChild(div);
});
this.update_selected("bg")
this.update_selected("fg")
}
add_color(button, rgb) {
doc.update_palette(null, rgb);
const hex = rgb_to_hex(rgb)
const div = document.createElement("div");
div.style.backgroundColor = hex;
div.dataset.id = doc.palette.length - 1;
button.before(div);
this.color_picker_spawner = div;
this.color_picker_el.value = hex;
this.color_picker_el.click();
}
update_selected(level) {
const class_name = `selected_${level}`;
let selected_el = this.swatch_container_el.querySelector(`.selected_${level}`);
if (selected_el) selected_el.classList.remove(class_name);
selected_el = this.swatch_container_el.querySelector(`[data-id="${this[level]}"`);
if (selected_el) selected_el.classList.add(class_name);
else {
} // we don't know about this color!
document.getElementById(level).style.backgroundColor = rgb_to_hex(doc.palette[this[level]]);
}
set fg(value) {
this.emit("set_fg", this.fg_index = parseInt(value, 10));
this.update_selected("fg")
}
get fg() {
return this.fg_index;
}
set bg(value) {
this.emit("set_bg", this.bg_index = parseInt(value, 10));
this.update_selected("bg")
}
set bg_internal(value) {
this.bg = value
if (doc.connection) doc.connection.set_bg(this.bg);
}
get bg() {
return this.bg_index;
}
previous_foreground_color() {
this.fg = (this.fg === 0) ? 15 : this.fg - 1;
}
next_foreground_color() {
this.fg = (this.fg === 15) ? 0 : this.fg + 1;
}
previous_background_color() {
this.bg_internal = (this.bg === 0) ? 15 : this.bg - 1;
}
next_background_color() {
this.bg_internal = (this.bg === 15) ? 0 : this.bg + 1;
}
async change_palette(lospec_palette_name) {
senders.send("update_menu_checkboxes", { lospec_palette_name });
await this.load_lospec_palette(lospec_palette_name);
this.update_swatches();
}
async load_lospec_palette(palette_name) {
const loaded_palette = lospec_palette(palette_name)
for (let i = 0; i < 16; i++) {
doc.update_palette(i, hex_to_rbg(loaded_palette[i]));
}
this.update_swatches()
//stupid way of forcing redraw on ui elements
this.fg = this.fg;
}
default_color() {
this.fg = 7;
this.bg_internal = 0;
}
switch_foreground_background() {
const fg_index = this.fg;
this.fg = this.bg;
this.bg_internal = fg_index;
}
toggle_fg(index) {
// TODO: ??
if (this.fg === index || (this.fg >= 8 && this.fg !== index + 8)) index += 8
this.fg = index;
}
toggle_bg(index) {
// TODO: ??
if (this.bg === index || (this.bg >= 8 && this.bg !== index + 8)) index += 8
this.bg_internal = index;
}
}
module.exports = new PaletteChooser();
<file_sep>
# Moebius XBIN GJ Edition (fork)
Moebius XBIN is an XBIN Editor for MacOS, Linux and Windows. This is a forked version of [Moebius XBIN](https://github.com/hlotvonen/moebius) which itself is a fork of [Moebius](https://github.com/blocktronics/moebius).
- `Moebius` is the original program.
- `Moebius XBIN` extends the original and contains support for custom colors and character sets and saving and loading xbin files (hence the name)
- `Moebius XBIN GJ Edition` which originally was just me wanting to stop the function keys from re-mapping -- but now has become a bit more.
## Moebius XBIN GJ Edition:
- Stops the function keys from being remapped when clicking in the character list.
- Makes default font IBM VGA instead of TOPAZ 437 (preference)
- Lets you use the character list picker to load the custom paint brush block.
- Adds opacity adjustment for the reference image with `SHIFT+Mouse Wheel`
- Adds opacity adjustment for drawing grids and guides with `ALT+Mouse Wheel`
- Adds a 1x1 drawing grid
- Adds character code to status bar
- Smaller character list (actual size of font vs 2x zoom previously)
- ... more things to come perhaps!
## Download packages
- Original Moebius: https://github.com/blocktronics/moebius
- Moebius XBIN: https://github.com/hlotvonen/moebius/releases
- Moebius XBIN GJ Edition: https://github.com/grymmjack/moebius/releases
## Acknowledgements
* This fork is a fork of a fork so the original authors get all the credit
* Uses modified Google's Material Icons. https://material.io/icons/
* Contains XBIN by LMN (Impure)
* Included fonts:
* GJSCI-3, GJSCI-4 and GJSCI-X appears courtesy of [GrymmJack](https://www.youtube.com/channel/UCrp_r9aomBi4mryxSxLq24Q)
* [FROGBLOCK](https://polyducks.itch.io/frogblock) appears courtesy of [PolyDucks](http://polyducks.co.uk/)
* Topaz originally appeared in Amiga Workbench, courtesy of Commodore Int.
* P0t-NOoDLE appears courtesy of Leo 'Nudel' Davidson
* mO'sOul appears courtesy of Desoto/Mo'Soul
## License
Copyright 2021 <NAME>
Licensed under the [Apache License, version 2.0](https://github.com/blocktronics/moebius/blob/master/LICENSE.txt)
<file_sep>const { white, bright_white, palette_4bit, rgb_to_hex } = require("./palette");
const { create_canvas, clone_canvas } = require("./canvas");
const fs = require("fs");
const path = require("path");
const { lookup_url } = require("./font_lookup");
function generate_font_canvas(bitmask, height, length) {
const { canvas, ctx, image_data } = create_canvas(8 * length, height);
const rgba = new Uint8Array([255, 255, 255, 255]);
for (let i = 0, y = 0, char = 0; i < bitmask.length; i++) {
for (let x = 0, byte = bitmask[i]; x < 8; x++) {
if (byte >> x & 1) {
image_data.data.set(rgba, (y * canvas.width + (8 - 1 - x) + char * 8) * 4);
}
}
if ((i + 1) % height === 0) {
y = 0;
char++;
} else {
y++;
}
}
ctx.putImageData(image_data, 0, 0);
return canvas;
}
function add_ninth_bit_to_canvas(canvas, length) {
const { canvas: new_canvas, ctx } = create_canvas(9 * length, canvas.height);
for (let char = 0; char < length; char++) {
ctx.drawImage(
canvas,
char * 8,
0,
8,
canvas.height,
char * 9,
0,
8,
canvas.height
);
if (char >= 0xc0 && char <= 0xdf) {
ctx.drawImage(
canvas,
char * 8 + 8 - 1,
0,
1,
canvas.height,
char * 9 + 8,
0,
1,
canvas.height
);
}
}
return new_canvas;
}
function coloured_glyphs(source_canvas, rgb) {
const { canvas, ctx } = clone_canvas(source_canvas);
ctx.fillStyle = rgb_to_hex(rgb);
ctx.globalCompositeOperation = "source-in";
ctx.fillRect(0, 0, canvas.width, canvas.height);
return canvas;
}
cached_backgrounds = {}
function coloured_background(font_width, height, rgb) {
const hex = rgb_to_hex(rgb);
const key = hex;
if (cached_backgrounds[key]) return cached_backgrounds[key];
const { canvas, ctx } = create_canvas(font_width, height);
ctx.fillStyle = hex;
ctx.fillRect(0, 0, canvas.width, canvas.height);
return cached_backgrounds[key] = canvas;
}
cached_glyphs = {}
function create_coloured_glyph(source_canvas, code, rgb, font_width, height) {
const hex = rgb_to_hex(rgb);
const key = [hex, code].join('|')
if (cached_glyphs[key]) return cached_glyphs[key];
const { canvas, ctx } = create_canvas(font_width, height);
const image_data = source_canvas.getContext("2d").getImageData(code * font_width, 0, font_width, height);
ctx.putImageData(image_data, 0, 0);
ctx.globalCompositeOperation = "source-in";
ctx.fillStyle = hex;
ctx.fillRect(0, 0, canvas.width, canvas.height);
return cached_glyphs[key] = canvas;
}
class Font {
async load({ name = "IBM VGA", bytes, use_9px_font = false }) {
if (bytes) {
//If we load XBIN, we check the font from the XBIN file so we don't need to load a font
if (this.name) {
this.name = name
} else {
this.name = "XBIN font"
}
} else {
//In case of ans or other non-xbin file, we load the font by its name
this.name = name;
let req = new Request(lookup_url(name));
let resp = await fetch(req);
bytes = new Uint8Array(await resp.arrayBuffer());
}
const font_height = bytes.length / 256;
if (font_height % 1 !== 0) {
throw ("Error loading font.");
}
this.height = font_height;
this.bitmask = bytes;
this.width = 8;
this.length = 256;
this.use_9px_font = use_9px_font;
this.canvas = generate_font_canvas(this.bitmask, this.height, this.length);
if (this.use_9px_font) {
this.width += 1;
this.canvas = add_ninth_bit_to_canvas(this.canvas, this.length);
}
this.glyphs = this.palette.map(rgb => coloured_glyphs(this.canvas, rgb));
this.backgrounds = this.palette.map(rgb => coloured_background(this.width, this.height, rgb));
this.cursor = coloured_background(this.width, 2, bright_white);
}
replace_cache_at(index, rgb) {
this.backgrounds[index] = coloured_background(this.width, this.height, rgb);
this.glyphs[index] = coloured_glyphs(this.canvas, rgb);
}
draw(ctx, block, x, y) {
ctx.drawImage(this.get_background_for(block.bg), x, y, this.width, this.height);
ctx.drawImage(this.get_glyphs_for(block.fg), block.code * this.width, 0, this.width, this.height, x, y, this.width, this.height);
}
draw_raw(ctx, block, x, y) {
const canvas = create_coloured_glyph(this.canvas, block.code, white, this.width, this.height);
ctx.drawImage(canvas, x, y);
}
get_rgb(i) {
return this.palette[i];
}
draw_bg(ctx, bg, x, y) {
ctx.drawImage(this.backgrounds[bg], x, y);
}
draw_cursor(ctx, x, y) {
ctx.drawImage(this.cursor, x, y);
}
get_glyphs_for(index) {
return this.glyphs[index] = this.glyphs[index] || coloured_glyphs(this.canvas, this.get_rgb(index));
}
get_background_for(index) {
return this.backgrounds[index] = this.backgrounds[index] || coloured_background(this.width, this.height, this.get_rgb(index));
}
constructor(palette = [...palette_4bit]) {
this.palette = palette;
}
}
module.exports = { Font };<file_sep>const events = require("events");
const doc = require("../doc");
const buttons = { NONE: 0, LEFT: 1, RIGHT: 2 };
const { toolbar, zoom_in, zoom_out, actual_size } = require("../ui/ui");
const palette = require("../palette");
const { on } = require("../../senders");
class MouseListener extends events.EventEmitter {
set_dimensions(columns, rows, font) {
this.columns = columns;
this.rows = rows;
this.font = font;
}
get_xy(event) {
let canvas_width;
const canvas_container = document.getElementById("canvas_container");
const canvas_container_rect = canvas_container.getBoundingClientRect();
if (doc.use_9px_font) {
canvas_width = doc.columns * 9;
} else {
canvas_width = doc.columns * 8;
}
const canvas_height = doc.rows * doc.font_height;
let mouseX = event.clientX - canvas_container_rect.left;
let mouseY = event.clientY - canvas_container_rect.top;
let canvasX = mouseX * canvas_width / canvas_container.clientWidth;
let canvasY = mouseY * canvas_height / canvas_container.clientHeight;
const x = Math.floor(canvasX / (this.font.width * (this.canvas_zoom_toggled ? 2 : 1)));
const y = Math.floor(canvasY / (this.font.height * (this.canvas_zoom_toggled ? 2 : 1)));
const half_y = Math.floor(canvasY / (this.font.height / 2 * (this.canvas_zoom_toggled ? 2 : 1)));
return { x, y, half_y };
}
canvas_zoom_toggle() {
this.canvas_zoom_toggled = !this.canvas_zoom_toggled;
}
record_start() {
[this.start.x, this.start.y, this.start.half_y] = [this.x, this.y, this.half_y];
this.started = true;
}
start_drawing() {
this.drawing = true;
}
end() {
this.button = buttons.NONE;
this.started = false;
this.drawing = false;
}
store(x, y, half_y) {
[this.x, this.y, this.half_y] = [x, y, half_y];
}
mouse_down(event) {
if (!this.font || this.started || this.drawing) return;
if (event.button == 1) {
actual_size();
return;
}
const { x, y, half_y } = this.get_xy(event);
const is_legal = (x >= 0 && x < doc.columns && y >= 0 && y < doc.rows);
if (event.altKey) {
if (!is_legal) return;
const block = doc.get_half_block(x, half_y);
if (block.is_blocky) {
palette[(event.button == 0) ? "fg" : "bg"] = block.is_top ? block.upper_block_color : block.lower_block_color;
} else {
palette[(event.button == 0) ? "fg" : "bg"] = block.fg;
}
return;
}
this.store(x, y, half_y);
this.start = { x, y, half_y };
if (event.button == 2 || event.ctrlKey) {
this.button = buttons.RIGHT;
} else if (event.button == 0) {
this.button = buttons.LEFT;
}
this.emit("down", x, y, half_y, is_legal, this.button, event.shiftKey);
this.last = { x, y, half_y };
}
same_as_last(x, y, half_y) {
if (this.last.x == x && this.last.y == y && (toolbar.mode != toolbar.modes.HALF_BLOCK || this.last.half_y == half_y)) return true;
this.last = { x, y, half_y };
return false;
}
mouse_move(event) {
if (!this.font) return;
const { x, y, half_y } = this.get_xy(event);
const is_legal = (x >= 0 && x < doc.columns && y >= 0 && y < doc.rows);
if (this.x == x && this.y == y && this.half_y == half_y) return;
if (this.drawing) {
if (!this.same_as_last(x, y, half_y)) {
this.emit("draw", x, y, half_y, is_legal, this.button, event.shiftKey);
this.store(x, y, half_y);
}
} else if (this.started) {
if (!this.same_as_last(x, y, half_y)) this.emit("to", x, y, half_y, this.button);
} else {
this.emit("move", x, y, half_y, is_legal);
}
}
mouse_up(event) {
if (!this.font) return;
const { x, y, half_y } = this.get_xy(event);
if (this.drawing || this.started) {
this.emit("up", x, y, half_y, this.button, this.start.x == x && this.start.y == y && this.start.half_y == half_y, event.shiftKey);
this.end();
}
}
escape() {
if (this.drawing || this.started) {
this.end();
this.emit("out");
}
}
mouse_out(event) {
if (event.relatedTarget) return;
this.escape();
}
wheel(event) {
if (event.ctrlKey) { // zooming
event.preventDefault();
if (this.listening_to_wheel) {
if (event.deltaY > 5) {
zoom_out();
} else if (event.deltaY < 5) {
zoom_in();
}
this.listening_to_wheel = false;
setTimeout(() => {
this.listening_to_wheel = true;
}, 50);
}
} else if (event.shiftKey) { // reference image opacity
if (this.listening_to_wheel) {
let e = document.getElementById("reference_image");
let o = parseFloat(e.style.opacity);
let a = 0.2;
if (event.deltaY > 5) {
if (o >= a) o = o - a;
} else if (event.deltaY < 5) {
if (o <= (1.0 - a)) o = o + a;
}
if (o > 0) e.style.opacity = parseFloat(o);
this.listening_to_wheel = false;
setTimeout(() => {
this.listening_to_wheel = true;
}, 50);
}
} else if (event.altKey) { // grid opacity
if (this.listening_to_wheel) {
let e = document.getElementById("drawing_grid");
let o = parseFloat(e.style.opacity);
let a = 0.2;
if (event.deltaY > 5) {
if (o >= a) o = o - a;
} else if (event.deltaY < 5) {
if (o <= (1.0 - a)) o = o + a;
}
if (o > 0) e.style.opacity = parseFloat(o);
this.listening_to_wheel = false;
setTimeout(() => {
this.listening_to_wheel = true;
}, 50);
}
}
}
constructor() {
super();
this.buttons = buttons;
this.button = buttons.NONE;
this.start = { x: 0, y: 0, half_y: 0 };
this.started = false;
this.drawing = false;
this.listening_to_wheel = true;
this.canvas_zoom_toggled = false;
on("canvas_zoom_toggle", (event) => this.canvas_zoom_toggle());
doc.on("render", () => this.set_dimensions(doc.columns, doc.rows, doc.font));
document.addEventListener("DOMContentLoaded", (event) => {
document.getElementById("viewport").addEventListener("pointerdown", (event) => this.mouse_down(event), true);
document.body.addEventListener("pointermove", (event) => this.mouse_move(event), true);
document.body.addEventListener("pointerup", (event) => this.mouse_up(event), true);
document.body.addEventListener("pointerout", (event) => this.mouse_out(event), true);
document.body.addEventListener("wheel", (event) => this.wheel(event), { passive: false });
});
}
}
module.exports = new MouseListener();
|
7ff3b1032d49eb38b5e9267e618081fc4b8cc990
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
grymmjack/moebius
|
6caff43394bcbc98d54c59998f12eb7c2579af1a
|
6748f23602a78270e9b894b5264ad8a5ea051718
|
refs/heads/master
|
<repo_name>enml-dev/bazar<file_sep>/README.md
# Bazar
Welcome to Bazar, an online ads app similar to OLX.
<file_sep>/app/src/main/java/com/enml/bazar/ui/adapters/CategoryAdapter.java
package com.enml.bazar.ui.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.enml.bazar.R;
import com.enml.bazar.deleteafter.Book;
import de.hdodenhof.circleimageview.CircleImageView;
public class CategoryAdapter extends BaseAdapter {
private final Context mContext;
private final Book[] books;
public CategoryAdapter(Context context, Book[] books) {
this.mContext = context;
this.books = books;
}
@Override
public int getCount() {
return books.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1
final Book book = books[position];
// 2
if (convertView == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(R.layout.category_item, null);
}
// 3
final CircleImageView imageView = convertView.findViewById(R.id.category_cover_art);
final TextView nameTextView = (TextView)convertView.findViewById(R.id.category_name);
final TextView authorTextView = (TextView)convertView.findViewById(R.id.category_extra);
final ImageView imageViewFavorite = (ImageView)convertView.findViewById(R.id.imageview_favorite);
// 4
imageView.setImageResource(book.getImageResource());
nameTextView.setText(mContext.getString(book.getName()));
authorTextView.setText(mContext.getString(book.getAuthor()));
return convertView;
}
}
<file_sep>/data/src/main/java/com/enml/bazar/data/utils/ImageLoader.java
package com.enml.bazar.data.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.builder.AnimateGifMode;
import com.squareup.pollexor.Thumbor;
import com.squareup.pollexor.ThumborUrlBuilder;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.util.Date;
import androidx.annotation.NonNull;
public class ImageLoader {
private static Thumbor thumbor = Thumbor.create("http://69.89.12.148:8888/");
private static File getLocalImage(final String id, final String size, final int roundCorner) {
final File direct = new File(
Environment.getExternalStorageDirectory() + "/bazar/Images/");
boolean existDir = direct.exists();
if (!direct.exists()) {
existDir = direct.mkdirs();
}
if (existDir) {
File[] files = direct.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
if (file.getName().startsWith(id + roundCorner + size)) {
return true;
}
return false;
}
});
File file = null;
if (files != null && files.length > 0) {
file = files[0];
}
return file;
}
return null;
}
private static void saveImage(Bitmap image, @NonNull String id, final String size, final int roundCorner) {
final File direct = new File(
Environment.getExternalStorageDirectory() + "/bazar/Images/");
boolean existDir = direct.exists();
if (!direct.exists()) {
existDir = direct.mkdirs();
}
if (existDir) {
File file = new File(direct, id + roundCorner + size + new Date().getTime());
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
File[] files = direct.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].getName().startsWith(id + roundCorner + size)
&& !files[i].getName().equalsIgnoreCase(file.getName())) {
files[i].delete();
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
public static void loadImage(final Context context, final String imageId, String imageURL, final String size, final int roundCorner, final ImageBitmapResult imageBitmapResult) {
loadImage(context, imageId, imageURL, size, roundCorner, imageBitmapResult, null);
}
public static void loadImage(final Context context, final String imageId, String imageURL, final String size, final int roundCorner, final ImageView contactImg) {
loadImage(context, imageId, imageURL, size, roundCorner, null, contactImg);
}
public static void loadImage(final Context context, final String imageId, String imageURL, final ImageBitmapResult imageBitmapResult) {
loadImage(context, imageId, imageURL, "0x0", 0, imageBitmapResult, null);
}
public static void loadImage(final Context context, final String imageId, String imageURL, final ImageView contactImg) {
loadImage(context, imageId, imageURL, "0x0", 0, null, contactImg);
}
public static void loadImage(final Context context, final String imageId, String imageURL) {
loadImage(context, imageId, imageURL, "0x0", 0, null, null);
}
private static void loadImage(final Context context, final String imageId, String imageURL, final String size, final int roundCorner, final ImageBitmapResult imageBitmapResult, final ImageView contactImg) {
try {
final int defaultImage = android.R.drawable.btn_default;
if (imageURL != null) {
File file = getLocalImage(imageId, size, roundCorner);
if (file == null || !file.exists()) {
if (imageURL != null && imageURL.startsWith("http")) {
String image = imageURL;
if (Integer.parseInt(size.split("x")[0]) != 0) {
image = thumbor.buildImage(imageURL)
.resize(Integer.parseInt(size.split("x")[0]), Integer.parseInt(size.split("x")[1]))
.filter(thumbor.buildImage(imageURL).roundCorner(roundCorner),
thumbor.buildImage(imageURL).format(ThumborUrlBuilder.ImageFormat.JPEG))
.toUrl();
}
Ion.with(context)
.load(image)
.withBitmap()
.animateGif(AnimateGifMode.ANIMATE)
.placeholder(defaultImage)
.error(defaultImage)
.asBitmap()
.setCallback(new com.koushikdutta.async.future.FutureCallback<Bitmap>() {
@Override
public void onCompleted(Exception e, Bitmap result) {
if (e == null) {
// Success
if (imageBitmapResult != null) {
imageBitmapResult.bitmapResult(result);
}
if (contactImg != null) {
contactImg.setImageBitmap(result);
}
try {
saveImage(result, imageId, size, roundCorner);
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
// Error
if (contactImg != null) {
contactImg.setImageResource(defaultImage);
}
if (imageBitmapResult != null) {
imageBitmapResult.bitmapResult(BitmapFactory.decodeResource(context.getResources(), defaultImage));
}
}
}
});
} else {
Ion.with(context)
.load(imageURL)
.withBitmap()
.animateGif(AnimateGifMode.ANIMATE)
.placeholder(defaultImage)
.error(defaultImage)
.asBitmap()
.setCallback(new com.koushikdutta.async.future.FutureCallback<Bitmap>() {
@Override
public void onCompleted(Exception e, Bitmap result) {
if (e == null) {
// Success
if (contactImg != null) {
contactImg.setImageBitmap(result);
}
if (imageBitmapResult != null) {
imageBitmapResult.bitmapResult(result);
}
} else {
// Error
if (contactImg != null) {
contactImg.setImageResource(defaultImage);
}
if (imageBitmapResult != null) {
imageBitmapResult.bitmapResult(BitmapFactory.decodeResource(context.getResources(), defaultImage));
}
}
}
});
}
} else {
Ion.with(context)
.load(file)
.withBitmap()
.animateGif(AnimateGifMode.ANIMATE)
.placeholder(defaultImage)
.error(defaultImage)
.asBitmap()
.setCallback(new com.koushikdutta.async.future.FutureCallback<Bitmap>() {
@Override
public void onCompleted(Exception e, Bitmap result) {
if (e == null) {
// Success
if (contactImg != null) {
contactImg.setImageBitmap(result);
}
if (imageBitmapResult != null) {
imageBitmapResult.bitmapResult(result);
}
} else {
// Error
if (contactImg != null) {
contactImg.setImageResource(defaultImage);
}
if (imageBitmapResult != null) {
imageBitmapResult.bitmapResult(BitmapFactory.decodeResource(context.getResources(), defaultImage));
}
}
}
});
}
} else {
if (contactImg != null) {
contactImg.setImageResource(defaultImage);
}
if (imageBitmapResult != null) {
imageBitmapResult.bitmapResult(BitmapFactory.decodeResource(context.getResources(), defaultImage));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/data/src/main/java/com/enml/bazar/data/dao/parse/ItemDAO.java
package com.enml.bazar.data.dao.parse;
import com.enml.bazar.data.GetCallback;
import com.enml.bazar.data.dao.interfaces.IItemDAO;
import com.enml.bazar.data.model.interfaces.IItem;
import com.enml.bazar.data.model.parse.Item;
import com.parse.ParseException;
import com.parse.ParseQuery;
import java.util.List;
public class ItemDAO implements IItemDAO {
@Override
public void getItems(final GetCallback<List<IItem>> callback) {
ParseQuery<Item> query = ParseQuery.getQuery(Item.class);
query.findInBackground(new com.parse.FindCallback<Item>() {
@Override
public void done(List categoryList, ParseException e) {
if (e != null) {
if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
callback.done(categoryList, null);
} else {
callback.done(categoryList, e);
}
} else {
callback.done(categoryList, e);
}
}
});
}
}
<file_sep>/data/src/main/java/com/enml/bazar/data/repositories/CategoryRepository.java
package com.enml.bazar.data.repositories;
import com.enml.bazar.data.GetCallback;
import com.enml.bazar.data.dao.factory.DAOFactory;
import com.enml.bazar.data.model.interfaces.ICategory;
import java.util.List;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
public class CategoryRepository {
private static CategoryRepository instance;
public static CategoryRepository getInstance() {
if (instance == null){
instance = new CategoryRepository();
}
return instance;
}
public LiveData<Resource<List<ICategory>>> getCategories() {
final MutableLiveData mutableLiveData = new MutableLiveData<>();
mutableLiveData.setValue(Resource.loading(null));
DAOFactory.getDAOFactory().getCategoryDAO().getCategories(new GetCallback<List<ICategory>>() {
@Override
public void done(List<ICategory> categoryList, Exception e) {
mutableLiveData.setValue(Resource.success(categoryList));
}
});
return mutableLiveData;
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.enml.bazar"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project(':data')
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
implementation 'com.google.android.material:material:1.0.0-beta01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
// Parse dependencies
implementation "com.github.parse-community.Parse-SDK-Android:parse:$parse"
// for FCM Push support (optional)
implementation "com.github.parse-community.Parse-SDK-Android:fcm:$parse"
implementation "com.github.parse-community.Parse-SDK-Android:ktx:$parse"
// Navigation
implementation "androidx.navigation:navigation-fragment:$nav_version"
// For Kotlin use navigation-fragment-ktx
implementation "androidx.navigation:navigation-ui:$nav_version"
// For Kotlin use navigation-ui-ktx
implementation 'com.yarolegovich:mp:1.0.9'
implementation 'com.jaredrummler:material-spinner:1.3.1'
implementation 'com.yanzhenjie:album:2.1.3'
implementation 'com.yanzhenjie:permission:2.0.0-rc12'
implementation 'com.koushikdutta.ion:ion:2.1.8'
implementation 'de.hdodenhof:circleimageview:2.1.0'
}
<file_sep>/data/src/main/java/com/enml/bazar/data/model/parse/Category.kt
package com.enml.bazar.data.model.parse
import com.enml.bazar.data.model.interfaces.ICategory
import com.parse.ParseClassName
import com.parse.ParseObject
import com.parse.ktx.delegates.stringAttribute
@ParseClassName("Category")
class Category : ParseObject(), ICategory {
override var name : String by stringAttribute()
override var description : String by stringAttribute()
}<file_sep>/data/src/main/java/com/enml/bazar/data/dao/parse/MunicipalityDAO.java
package com.enml.bazar.data.dao.parse;
public class MunicipalityDAO {
}
<file_sep>/data/src/main/java/com/enml/bazar/data/dao/parse/ProvinceDAO.java
package com.enml.bazar.data.dao.parse;
public class ProvinceDAO {
}
<file_sep>/data/src/main/java/com/enml/bazar/data/model/interfaces/ISubCategory.kt
package com.enml.bazar.data.model.interfaces
interface ISubCategory {
}<file_sep>/data/src/main/java/com/enml/bazar/data/model/interfaces/IItem.kt
package com.enml.bazar.data.model.interfaces
interface IItem {
var title: String
var description: String
var price: Int
// New or Used
var status: String
var category : ICategory?
}<file_sep>/data/src/main/java/com/enml/bazar/data/model/interfaces/IItemType.kt
package com.enml.bazar.data.model.interfaces
interface IItemType {
}<file_sep>/data/src/main/java/com/enml/bazar/data/utils/ImageBitmapResult.java
package com.enml.bazar.data.utils;
import android.graphics.Bitmap;
/**
* Created by edel on 12/02/17.
*/
public interface ImageBitmapResult {
void bitmapResult(Bitmap bitmap);
}
<file_sep>/data/src/main/java/com/enml/bazar/data/model/interfaces/IProvince.kt
package com.enml.bazar.data.model.interfaces
interface IProvince {
}<file_sep>/data/src/main/java/com/enml/bazar/data/model/parse/Province.kt
package com.enml.bazar.data.model.parse
import com.enml.bazar.data.model.interfaces.IProvince
import com.parse.ParseClassName
import com.parse.ParseObject
@ParseClassName("Province")
class Province : ParseObject(), IProvince {
}<file_sep>/data/src/main/java/com/enml/bazar/data/viewmodel/CategoryViewModel.java
package com.enml.bazar.data.viewmodel;
import com.enml.bazar.data.model.interfaces.ICategory;
import com.enml.bazar.data.repositories.CategoryRepository;
import com.enml.bazar.data.repositories.Resource;
import java.util.List;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
public class CategoryViewModel extends ViewModel {
public CategoryViewModel(){
}
public LiveData<Resource<List<ICategory>>> getCategories() {
return CategoryRepository.getInstance().getCategories();
}
}
<file_sep>/data/src/main/java/com/enml/bazar/data/model/interfaces/IMunicipality.kt
package com.enml.bazar.data.model.interfaces
interface IMunicipality {
}<file_sep>/app/src/main/java/com/enml/bazar/ui/ViewItemActivity.java
package com.enml.bazar.ui;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.enml.bazar.R;
public class ViewItemActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme_Light);
setContentView(R.layout.activity_view_item);
}
}<file_sep>/data/src/main/java/com/enml/bazar/data/model/interfaces/ICategory.kt
package com.enml.bazar.data.model.interfaces
interface ICategory {
var name : String
var description : String
}<file_sep>/app/src/main/java/com/enml/bazar/app/App.kt
package com.enml.bazar.app
import android.app.Application
import android.content.Context
import com.enml.bazar.data.dao.factory.DAOFactory
import com.enml.bazar.data.dao.factory.DAOFactoryType
import com.enml.bazar.data.utils.DbHelper
import com.enml.bazar.utils.MediaLoader
import com.yanzhenjie.album.AlbumConfig
import com.yanzhenjie.album.Album
class App : Application() {
companion object {
var ctx: Context? = null
}
override fun onCreate() {
super.onCreate()
ctx = applicationContext
DbHelper.init(this);
DAOFactory.init(this, DAOFactoryType.PARSE)
Album.initialize(AlbumConfig.newBuilder(this)
.setAlbumLoader(MediaLoader())
.build())
}
}<file_sep>/data/src/main/java/com/enml/bazar/data/model/parse/SubCategory.kt
package com.enml.bazar.data.model.parse
import com.enml.bazar.data.model.interfaces.ISubCategory
import com.parse.ParseClassName
import com.parse.ParseObject
@ParseClassName("SubCategory")
class SubCategory : ParseObject(), ISubCategory {
}<file_sep>/data/src/main/java/com/enml/bazar/data/model/parse/ItemType.kt
package com.enml.bazar.data.model.parse
import com.enml.bazar.data.model.interfaces.IItemType
import com.parse.ParseClassName
import com.parse.ParseObject
@ParseClassName("ItemType")
class ItemType : ParseObject (), IItemType {
}<file_sep>/data/src/main/java/com/enml/bazar/data/GetCallback.java
package com.enml.bazar.data;
/**
* Created by edel on 06/03/17.
*/
public interface GetCallback<T> {
void done(T object, Exception e);
}
<file_sep>/data/src/main/java/com/enml/bazar/data/model/parse/Item.kt
package com.enml.bazar.data.model.parse
import com.enml.bazar.data.model.interfaces.ICategory
import com.enml.bazar.data.model.interfaces.IItem
import com.parse.ParseClassName
import com.parse.ParseObject
import com.parse.ktx.delegates.intAttribute
import com.parse.ktx.delegates.stringAttribute
@ParseClassName("Item")
class Item : ParseObject (), IItem {
override var title: String by stringAttribute()
override var description: String by stringAttribute()
override var price: Int by intAttribute()
// New or Used
override var status: String by stringAttribute()
override var category : ICategory?
get() = get("category") as ICategory?
set(value) {
put("category", value as ICategory)
}
}
<file_sep>/data/src/main/java/com/enml/bazar/data/model/parse/Municipality.kt
package com.enml.bazar.data.model.parse
import com.enml.bazar.data.model.interfaces.IMunicipality
import com.parse.ParseClassName
import com.parse.ParseObject
@ParseClassName("Municipality")
class Municipality : ParseObject (), IMunicipality {
}<file_sep>/data/src/main/java/com/enml/bazar/data/dao/parse/ItemTypeDAO.java
package com.enml.bazar.data.dao.parse;
public class ItemTypeDAO {
}
|
ff34027faa1f2187bf6d2b7193855867ccb06188
|
[
"Markdown",
"Java",
"Kotlin",
"Gradle"
] | 26
|
Markdown
|
enml-dev/bazar
|
795a026ac5cb032de4fe41e30081a37d7f5d9144
|
f62c06887be6357d0150543a4002203e4e8280ee
|
refs/heads/master
|
<file_sep># What is this Application?
This is my play project (called: **_iTunes Media Search_**) where i am planning to experiment and present my ideas on how we should do Angular development following some of the best practices i have learned in last 1yr. It will start easy and build\progress towards awesomeness. This iTunes Search implementation is inspired from @devgirl (<NAME>) at [github](https://github.com/hollyschinsky/MediaExplorer).

### This implementation demonstrate following things
1. Can be used as quick "**_template_** \ **_seed_**" project for any new Angular Project.
2. It uses [**iTunes Search API**](https://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html) as REST endpoint.
3. It uses [**Twitter Bootstrap 3.1.1**](http://getbootstrap.com/) as UI Responsive Theme.
4. It uses latest [**Angular 1.2.14**](http://code.angularjs.org/1.2.14/docs/api) as of today (_March-3rd, 2014_)
5. Demonstrates how to use **filter** and **orderBy** features of Angular
# Technology Stack
* Angular latest (As of today March-14th, 2014 it is **1.2.14**)
* Bootstrap **3.1.1**
* Grunt
* jshint
* watch
* connect
* karma
* Bower
## Installation
git clone <EMAIL>:skusunam/angular-itunes-search.git
cd angular-itunes-search
npm install
## Running
# Serve static files using your own web server or run
grunt
# Go to this URL in your favorite browser
http://localhost:9001/app/
# Things i am planning write code for:
1. Original sample project organized based on "Type" (controller, services etc) w/ Unit Tests
2. Project sample using RequireJS w/ Unit tests
3. Project sample using Yeoman workflow
4. Project sample using Lineman workflow
5. Replace 'ngRout' with 'ui-router' (https://github.com/angular-ui/ui-router) and compare differences
6. What are the adavantages in using 'restangular' (https://github.com/mgonto/restangular) instead of default '$resource'?
7. Implement Authentication i.e. 'Login' using Facebook \ Twitter \ Linked-in \ Google+ (all or few of them).
8. How do you protect an angular Route?
9. Write an interceptor (Request and Response) and show how to use them?
10. Display spinner when there is an http request in progress
11. Replace table display with 'ngGrid' (http://angular-ui.github.io/ng-grid/)
12. Replace table display with 'ngTable' (https://github.com/esvit/ng-table)
13. Implement i18n using 'angular-translate' (https://github.com/angular-translate/angular-translate)
14. Show an example of using 'bindonce' (https://github.com/Pasvaz/bindonce)
# Simple things which i want to Blog:
1) Why should \ shouldn't use '$resource' with respect to '$http'?
<file_sep>'use strict';
// For any iTunes Search API refer here:
// https://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html
iTunesApp.factory('MediaService', ['$resource',
function($resource) {
return $resource('https://itunes.apple.com/:action', {
action: "search",
callback: 'JSON_CALLBACK'
}, {
get: {
method: 'JSONP'
}
});
}
]);<file_sep>'use strict';
// From Angular 1.2.x some of the modules (ngRoute, ngResource) are optional and
// needs to be included manually
//
// BLOG: What does 'ngResource' do explain in blog post?
var iTunesApp = angular.module('iTunesApp', ['ngRoute', 'ngResource']);
iTunesApp.config(['$routeProvider',
function($routeProvider) {
// BLOG: How to protect a Route?
$routeProvider.when('/', {
templateUrl: 'partials/media-list.html',
controller: 'MediaListController'
});
}
]);
|
efd88ecc010e47f86a9465402dfcad7715cb18b0
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
skusunam/angular-itunes-search
|
3e2bd7ed47b74776db73773e0eb833c0f9e27154
|
080acaf2044ac7d4ea2b207125494d43e22a39da
|
refs/heads/master
|
<repo_name>zdwalter/iconv-js<file_sep>/Makefile
all:
python iconv-gen.py > iconv.js
<file_sep>/iconv-gen.py
# coding=utf-8
import sys
code = open('iconv-template-orig.js', 'rb').read()
tocp949_map = []
shift = 7
for i in xrange(0, 0x10000, 1<<shift):
row = []
for j in xrange(i, i + (1<<shift)):
ch = unichr(j).encode('cp949', 'ignore') or '?'
if len(ch) == 1: row.append(ord(ch))
else: row.append(ord(ch[0]) | ((ord(ch[1])&0x7f)<<8))
if row == [63] * (1<<shift): row = None
tocp949_map.append(row)
def toprintable(ch):
if ch == 92 or ch == 39: return '\\%c' % ch
if ch < 0x20 or ch == 0x7f: return '\\x%02x' % ch
return unichr(ch).encode('utf-8')
code = code.replace('__TOCP949_MAP_SHIFT__', str(shift))
code = code.replace('__TOCP949_MAP_MASK__', str((1<<shift) - 1))
code = code.replace('__TOCP949_MAP_DEFAULT__', "'" + '?' * (1<<shift) + "'")
code = code.replace('__TOCP949_MAP__',
'[' + ','.join('\'' + ''.join(map(toprintable, row)) + '\'' if row else '0'
for row in tocp949_map) + ']')
sys.stdout.write(code)
|
a758c8812a57c37811c0eb0721a93f0e147bfcfd
|
[
"Python",
"Makefile"
] | 2
|
Makefile
|
zdwalter/iconv-js
|
b19c13aca4997e9c2933f76ed7711eeee1d8b44e
|
056257370209640afb4903507847a6479fa2eec9
|
refs/heads/master
|
<repo_name>WunderlichZA/CodingAssignment2<file_sep>/app/src/main/java/com/cobi/codingassignment/DetailActivity.java
package com.cobi.codingassignment;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import model.AndroidVersion;
import rest.RetroClient;
import com.cobi.codingassignment.databinding.ActivityDetailBinding;
public class DetailActivity extends AppCompatActivity {
private final String TAG = this.getClass().getName();
ActivityDetailBinding detailBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
detailBinding = DataBindingUtil.setContentView(this, R.layout.activity_detail);
// Set Toolbar
//setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
if(getIntent() != null) {
// populate fields
setData();
}
}
/**
* Populates and display selected object data
*/
private void setData() {
// AndroidVersion androidVersion = (AndroidVersion) getIntent()
// .getSerializableExtra(MainActivity.KEY);
//
// // check if version has a thumbnail
// if (!(androidVersion.getImage() == null)) {
// Glide.with(this)
// .load(RetroClient.ROOT_URL + "/" + androidVersion.getImage())
// .placeholder(R.mipmap.placeholder)
// .error(R.mipmap.placeholder)
// .diskCacheStrategy(DiskCacheStrategy.SOURCE)
// .into(image);
// }
// // set version name
// name.setText("Name : " + androidVersion.getName());
// // set version number
// version.setText("Version : " + androidVersion.getVersion());
// // check if version has an api version
// if (!(androidVersion.getApi() == null)) {
// api.setText("Api : " + androidVersion.getApi());
// }
// // check if version has a release date
// if (!(androidVersion.getReleased() == null)) {
// released.setText("Released : " + androidVersion.getReleased());
// }
}
}
|
2fe014792e7a71834c0252c9a0254ff94f6cc494
|
[
"Java"
] | 1
|
Java
|
WunderlichZA/CodingAssignment2
|
c06797125776314da91f405070238ba30ebfc0de
|
c84e3f5eea1339a70db592ff9d499bbd9d39a4dd
|
refs/heads/main
|
<file_sep>while (true) { Growl.js}
new Promise(function(resolve, reject) {
ClassName.prototype.methodName = function () {
// COMBAK: function* (Growl.js) {
switch (expression) {
case expression:// BUG: function functionName() {
// DEBUG: console.dir(Growl.js);
} getElementsByClassName('Growl.js')
case expression:
break;console.warn(Growl.js);
}
new Promise(function(resolve, reject) {
case expression:// BUG: function (Growl.js) {
// WARNING: switch (expression) {
case expression:do {
} while (true);
while (false);
while(true);
while(function);
class_name.prototype.method_name = function(first_argument) {
//
};
break;Growl.js
return ();
<file_sep># OpenModelGL
OpenModelGL
OpenModelGL.cpp of your modelview matrix project
matModel.rotateZ(modelAngle[2]);
matModel.rotateY(modelAngle[1]);
matModel.rotateX(modelAngle[0]);
matModel.translate(modelPosition[0], modelPosition[1], modelPosition[2]);
matModelView = matView * matModel;
glLoadMatrixf(matModelView.get());
if i change it to
matModel.rotateZ(modelAngle[2]);
matModel.rotateY(modelAngle[1]);
matModel.rotateX(modelAngle[0]);
matModelView = matView * matModel;
matModelView.translate(modelPosition[0], modelPosition[1], modelPosition[2]);
glLoadMatrixf(matModelView.get());
nothing happens, but if i make opengl do the translation part like this
matModel.rotateZ(modelAngle[2]);
matModel.rotateY(modelAngle[1]);
matModel.rotateX(modelAngle[0]);
matModelView = matView * matModel;
glLoadMatrixf(matModelView.get());
glTranslatef(modelPosition[0], modelPosition[1], modelPosition[2])/* v' = Mt · Mr · v */
glTranslatef(...);
glRotatef(...);
glVertex3f(...);
matModelView ();
/ This creates a symmetric frustum.
// It converts to 6 params (l, r, b, t, n, f) for glFrustum()
// from given 4 params (fovy, aspect, near, far)
void makeFrustum(double fovY, double aspectRatio, double front, double back)
{
const double DEG2RAD = 3.14159265 / 180;
double tangent = tan(fovY/2 * DEG2RAD); // tangent of half fovY
double height = front * tangent; // half height of near plane
double width = height * aspectRatio; // half width of near plane
// params: left, right, bottom, top, near, far
glFrustum(-width, width, -height, height, front, back);
}// Note that the object will be translated first then rotated
glRotatef(angle, 1, 0, 0); // rotate object angle degree around X-axis
glTranslatef(x, y, z); // move object to (x, y, z)
drawObject();
gluLookAt()glTranslatef()
/ This creates a symmetric frustum.
// It converts to 6 params (l, r, b, t, n, f) for glFrustum()
// from given 4 params (fovy, aspect, near, far)
void makeFrustum(double fovY, double aspectRatio, double front, double back)
{
const double DEG2RAD = 3.14159265 / 180;
double tangent = tan(fovY/2 * DEG2RAD); // tangent of half fovY
double height = front * tangent; // half height of near plane
double width = height * aspectRatio; // half width of near plane
// params: left, right, bottom, top, near, far
glFrustum(-width, width, -height, height, front, back);
}
// rotate texture around X-axis
glMatrixMode(GL_TEXTURE);
glRotatef(angle, 1, 0, 0);
...glRotatef(), glTranslatef(), glScalef().
glPushMatrix();glRotatef(), glTranslatef(), glScalef().
// set view matrix for camera transform
glLoadMatrixf(matrixView.get());
// draw the grid at origin before model transform
drawGrid();
// set modelview matrix for both model and view transform
// It transforms from object space to eye space.
glLoadMatrixf(matrixModelView.get());
// draw a teapot after both view and model transforms
drawTeapot();
glPopMatrix();
... glPushMatrix
...height()
glPushMatrix();
// initialze ModelView matrix
glLoadIdentity();
// First, transform the camera (viewing matrix) from world space to eye space
// Notice translation and heading values are negated,
// because we move the whole scene with the inverse of camera transform
// ORDER: translation -> roll -> heading -> pitch
glRotatef(cameraAngle[2], 0, 0, 1); // roll
glRotatef(-cameraAngle[1], 0, 1, 0); // heading
glRotatef(cameraAngle[0], 1, 0, 0); // pitch
glTranslatef(-cameraPosition[0], -cameraPosition[1], -cameraPosition[2]);
// draw the grid at origin before model transform
drawGrid();
// transform the object (model matrix)
// The result of GL_MODELVIEW matrix will be:
// ModelView_M = View_M * Model_M
// ORDER: rotZ -> rotY -> rotX -> translation
glTranslatef(modelPosition[0], modelPosition[1], modelPosition[2]);
glRotatef(modelAngle[0], 1, 0, 0);
glRotatef(modelAngle[1], 0, 1, 0);
glRotatef(modelAngle[2], 0, 0, 1);
// draw a teapot with model and view transform together
drawTeapot();
glPopMatrix();
...
///////////////////////////////////////////////////////////////////////////////
// return a perspective frustum with 6 params similar to glFrustum()
// (left, right, bottom, top, near, far)
///////////////////////////////////////////////////////////////////////////////
Matrix4 ModelGL::setFrustum(float l, float r, float b, float t, float n, float f)
{
Matrix4 matrix;
matrix[0] = 2 * n / (r - l);
matrix[5] = 2 * n / (t - b);
matrix[8] = (r + l) / (r - l);
matrix[9] = (t + b) / (t - b);
matrix[10] = -(f + n) / (f - n);
matrix[11] = -1;
matrix[14] = -(2 * f * n) / (f - n);
matrix[15] = 0;
return matrix;
}
///////////////////////////////////////////////////////////////////////////////
// return a symmetric perspective frustum with 4 params similar to
// gluPerspective() (vertical field of view, aspect ratio, near, far)
///////////////////////////////////////////////////////////////////////////////
Matrix4 ModelGL::setFrustum(float fovY, float aspectRatio, float front, float back)
{
float tangent = tanf(fovY/2 * DEG2RAD); // tangent of half fovY
float height = front * tangent; // half height of near plane
float width = height * aspectRatio; // half width of near plane
// params: left, right, bottom, top, near, far
return setFrustum(-width, width, -height, height, front, back);
}glRotatef()
glTranslatef() glScalef()
///////////////////////////////////////////////////////////////////////////////
// set a orthographic frustum with 6 params similar to glOrtho()
// (left, right, bottom, top, near, far)
///////////////////////////////////////////////////////////////////////////////
Matrix4 ModelGL::setOrthoFrustum(float l, float r, float b, float t, float n, float f)
{ (m0, m1, m2), (m4, m5, m6) and (m8, m9, m10)(m12, m13, m14)
Matrix4 matrix;
matrix[0] = 2 / (r - l);
matrix[5] = 2 / (t - b);
matrix[10] = -2 / (f - n);
matrix[12] = -(r + l) / (r - l);
matrix[13] = -(t + b) / (t - b);
matrix[14] = -(f + n) / (f - n);
return matrix;
}
... P1=(3,4) à P2=(20,18)
Xmin = 5, Xmax = 10, Ymin = 7, Ymax = 13,
Xmin = 2, Xmax = 10, Ymin = 10, Ymax = 17,
Xmin = 2, Xmax = 10, Ymin = 10, YmaxP1=(3,4) à P2=(20,18) = 17,
P1=(3,4) à P2=(20,18) P1=(15,11) à P2=(1,3)
// how to pass projection matrx to OpenGL
Matrix4 projectionMatrix = setFrustum(l, r, b, t, n, f);
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(matrixProjection.get());
(m0, m1, m2) : +X axis, left vector, (1, 0, 0) by default
(m4, m5, m6) : +Y axis, up vector, (0, 1, 0) by default
(m8, m9, m10) : +Z axis, forward vector, (0, 0, 1) by default
...
<file_sep>
import numpy as np
from scipy import interpolate
from mpl_toolkits.mplot3d import Axes3D
from pylab import *
from skimage.filter import gabor_kernel
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# Função utilizada para reescalar o kernel
def resize_kernel(aKernelIn, iNewSize):
x = np.array([v for v in range(len(aKernelIn))])
y = np.array([v for v in range(len(aKernelIn))])
z = aKernelIn
xx = np.linspace(x.min(), x.max(), iNewSize)
yy = np.linspace(y.min(), y.max(), iNewSize)
aKernelOut = np.zeros((iNewSize, iNewSize), np.float)
oNewKernel = interpolate.RectBivariateSpline(x, y, z)
aKernelOut = oNewKernel(xx, yy)
return aKernelOut
if __name__ == "__main__":
fLambda = 3.0000000001 # comprimento de onda (em pixels)
fTheta = 0 # orientação (em radianos)
fSigma = 0.56 * fLambda # envelope gaussiano (com 1 oitava de largura de banda)
fPsi = np.pi / 2 # deslocamento (offset)
# Tamanho do kernel (3 desvios para cada lado, para limitar cut-off)
iLen = int(math.ceil(3.0 * fSigma))
if(iLen % 2 != 0):
iLen += 1
# Obtém o kernel Gabor para os parâmetros definidos
z = np.real(gabor_kernel(fLambda, theta=fTheta, sigma_x=fSigma, sigma_y=fSigma, offset=fPsi))
# Plotagem do kernel
fig = plt.figure(figsize=(16, 9))
fig.suptitle(r'Gabor kernel para $\lambda=3.0$, $\theta=0.0$, $\sigma=0.56\lambda$ e $\psi=\frac{\pi}{2}$', fontsize=25)
grid = gridspec.GridSpec(1, 2, width_ratios=[1, 2])
fLambda = 3.0000000001
# Gráfico 2D
plt.gray()
ax = fig.add_subplot(grid[0])
ax.set_title(u'Visualização 2D')
ax.imshow(z, interpolation='nearest')
ax.set_xticklabels([v for v in range((-iLen/2)-1, iLen/2+1)], fontsize=10)
ax.set_yticklabels([v for v in range((-iLen/2)-1, iLen/2+1)], fontsize=10)
# Gráfico em 3D
# Reescalona o kernel para uma exibição melhor
z = resize_kernel(z, 300)
# Eixos x e y no intervalo do tamanho do kernel
x = np.linspace(-iLen/2, iLen/2, 300)
y = x
x, y = meshgrid(x, y)
ax = fig.add_subplot(grid[1], projection='3d')
ax.set_title(u'Visualização 3D')
ax.plot_surface(x, y, z, cmap='hot')
fLambda = 3.0
# ou
fLambda = float(3)
print(iLen)
plt.show()
import numpy as np
from scipy import interpolate
from mpl_toolkits.mplot3d import Axes3D
from pylab import *
from skimage.filter import gabor_kernel
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# Função utilizada para reescalar o kernel
def resize_kernel(aKernelIn, iNewSize):
x = np.array([v for v in range(len(aKernelIn))])
y = np.array([v for v in range(len(aKernelIn))])
z = aKernelIn
xx = np.linspace(x.min(), x.max(), iNewSize)
yy = np.linspace(y.min(), y.max(), iNewSize)
aKernelOut = np.zeros((iNewSize, iNewSize), np.float)
oNewKernel = interpolate.RectBivariateSpline(x, y, z)
aKernelOut = oNewKernel(xx, yy)
return aKernelOut
if __name__ == "__main__":
fLambda = 3 # comprimento de onda (em pixels)
fTheta = 0 # orientação (em radianos)
fSigma = 0.56 * fLambda # envelope gaussiano (com 1 oitava de largura de banda)
fPsi = np.pi / 2 # deslocamento (offset)
# Tamanho do kernel (3 desvios para cada lado, para limitar cut-off)
iLen = int(math.ceil(3.0 * fSigma))
if(iLen % 2 != 0):
iLen += 1
# Obtém o kernel Gabor para os parâmetros definidos
z = np.real(gabor_kernel(1.0/fLambda, theta=fTheta, sigma_x=fSigma, sigma_y=fSigma, offset=fPsi))
# Plotagem do kernel
fig = plt.figure(figsize=(16, 9))
fig.suptitle(r'Gabor kernel para $\lambda=3.0$, $\theta=0.0$, $\sigma=0.56\lambda$ e $\psi=\frac{\pi}{2}$', fontsize=25)
grid = gridspec.GridSpec(1, 2, width_ratios=[1, 2])
# Gráfico 2D
plt.gray()
ax = fig.add_subplot(grid[0])
ax.set_title(u'Visualização 2D')
ax.imshow(z, interpolation='bicubic')
ax.set_xticklabels([v for v in range((-iLen/2)-1, iLen/2+1)], fontsize=10)
ax.set_yticklabels([v for v in range((-iLen/2)-1, iLen/2+1)], fontsize=10)
# Gráfico em 3D
# Reescalona o kernel para uma exibição melhor
z = resize_kernel(z, 300)
# Eixos x e y no intervalo do tamanho do kernel
x = np.linspace(-iLen/2, iLen/2, 300)
y = x
x, y = meshgrid(x, y)
ax = fig.add_subplot(grid[1], projection='3d')
ax.set_title(u'Visualização 3D')
ax.plot_surface(x, y, z, cmap='hot')
print(iLen)
plt.show()
g = np.zeros(y.shape, dtype=np.complex)
g[:] = np.exp(-0.5 * (rotx**2 / sigma_x**2 + roty**2 / sigma_y**2))
g /= 2 * np.pi * sigma_x * sigma_y # <- DÚVIDA 1
g *= np.exp(1j * (2 * np.pi * frequency * rotx + offset)) # <- DÚVIDA 2
g = np.zeros(y.shape, dtype=np.complex)
g[:] = np.exp(-0.5 * (rotx**2 / sigma_x**2 + roty**2 / sigma_y**2))
g *= np.exp(1j * (2 * np.pi * rotx / frequency + offset))
return g
return g
mport numpy as np
from scipy import interpolate
from mpl_toolkits.mplot3d import Axes3D
from pylab import *
from skimage.filter import gabor_kernel
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def my_gabor_kernel(frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None,
offset=0):
if sigma_x is None:
sigma_x = _sigma_prefactor(bandwidth) / frequency
if sigma_y is None:
sigma_y = _sigma_prefactor(bandwidth) / frequency
n_stds = 3
x0 = np.ceil(max(np.abs(n_stds * sigma_x * np.cos(theta)),
np.abs(n_stds * sigma_y * np.sin(theta)), 1))
y0 = np.ceil(max(np.abs(n_stds * sigma_y * np.cos(theta)),
np.abs(n_stds * sigma_x * np.sin(theta)), 1))
y, x = np.mgrid[-y0:y0+1, -x0:x0+1]
rotx = x * np.cos(theta) + y * np.sin(theta)
roty = -x * np.sin(theta) + y * np.cos(theta)
g = np.zeros(y.shape, dtype=np.complex)
g[:] = np.exp(-0.5 * (rotx**2 / sigma_x**2 + roty**2 / sigma_y**2))
#g /= 2 * np.pi * sigma_x * sigma_y
g *= np.exp(1j * (2 * np.pi * rotx / frequency + offset))
return g
# Função utilizada para reescalar o kernel
def resize_kernel(aKernelIn, iNewSize):
x = np.array([v for v in range(len(aKernelIn))])
y = np.array([v for v in range(len(aKernelIn))])
z = aKernelIn
xx = np.linspace(x.min(), x.max(), iNewSize)
yy = np.linspace(y.min(), y.max(), iNewSize)
aKernelOut = np.zeros((iNewSize, iNewSize), np.float)
oNewKernel = interpolate.RectBivariateSpline(x, y, z)
aKernelOut = oNewKernel(xx, yy)
return aKernelOut
if __name__ == "__main__":
fLambda = 3.0000001 # comprimento de onda (em pixels)
fTheta = 0 # orientação (em radianos)
fSigma = 0.56 * fLambda # envelope gaussiano (com 1 oitava de largura de banda)
fPsi = np.pi / 2 # deslocamento (offset)
# Tamanho do kernel (3 desvios para cada lado, para limitar cut-off)
iLen = int(math.ceil(3.0 * fSigma))
if(iLen % 2 != 0):
iLen += 1
# Obtém o kernel Gabor para os parâmetros definidos
z = np.real(my_gabor_kernel(fLambda, theta=fTheta, sigma_x=fSigma, sigma_y=fSigma, offset=fPsi))
print(z.shape)
# Plotagem do kernel
fig = plt.figure(figsize=(16, 9))
fig.suptitle(r'Gabor kernel para $\lambda=3.0$, $\theta=0.0$, $\sigma=0.56\lambda$ e $\psi=\frac{\pi}{2}$', fontsize=25)
grid = gridspec.GridSpec(1, 2, width_ratios=[1, 2])
# Gráfico 2D
plt.gray()
ax = fig.add_subplot(grid[0])
ax.set_title(u'Visualização 2D')
ax.imshow(z, interpolation='bicubic')
ax.set_xticklabels([v for v in range((-iLen/2)-1, iLen/2+1)], fontsize=10)
ax.set_yticklabels([v for v in range((-iLen/2)-1, iLen/2+1)], fontsize=10)
# Gráfico em 3D
# Reescalona o kernel para uma exibição melhor
z = resize_kernel(z, 300)
# Eixos x e y no intervalo do tamanho do kernel
x = np.linspace(-iLen/2, iLen/2, 300)
y = x
x, y = meshgrid(x, y)
ax = fig.add_subplot(grid[1], projection='3d')
ax.set_title(u'Visualização 3D')
ax.plot_surface(x, y, z, cmap='hot')
print(iLen)
plt.show()
import numpy as np
from scipy import interpolate
from mpl_toolkits.mplot3d import Axes3D
from pylab import *
from skimage.filter import gabor_kernel
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def my_gabor_kernel(frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None,
offset=0):
if sigma_x is None:
sigma_x = _sigma_prefactor(bandwidth) / frequency
if sigma_y is None:
sigma_y = _sigma_prefactor(bandwidth) / frequency
n_stds = 3
x0 = np.ceil(max(np.abs(n_stds * sigma_x * np.cos(theta)),
np.abs(n_stds * sigma_y * np.sin(theta)), 1))
y0 = np.ceil(max(np.abs(n_stds * sigma_y * np.cos(theta)),
np.abs(n_stds * sigma_x * np.sin(theta)), 1))
y, x = np.mgrid[-y0:y0+1, -x0:x0+1]
rotx = x * np.cos(theta) + y * np.sin(theta)
roty = -x * np.sin(theta) + y * np.cos(theta)
g = np.zeros(y.shape, dtype=np.complex)
g[:] = np.exp(-0.5 * (rotx**2 / sigma_x**2 + roty**2 / sigma_y**2))
#g /= 2 * np.pi * sigma_x * sigma_y
g *= np.exp(1j * (2 * np.pi * rotx / frequency + offset))
return g
# Função utilizada para reescalar o kernel
def resize_kernel(aKernelIn, iNewSize):
x = np.array([v for v in range(len(aKernelIn))])
y = np.array([v for v in range(len(aKernelIn))])
z = aKernelIn
xx = np.linspace(x.min(), x.max(), iNewSize)
yy = np.linspace(y.min(), y.max(), iNewSize)
aKernelOut = np.zeros((iNewSize, iNewSize), np.float)
oNewKernel = interpolate.RectBivariateSpline(x, y, z)
aKernelOut = oNewKernel(xx, yy)
return aKernelOut
if __name__ == "__main__":
fLambda = 3.0000001 # comprimento de onda (em pixels)
fTheta = 0 # orientação (em radianos)
fSigma = 0.56 * fLambda # envelope gaussiano (com 1 oitava de largura de banda)
fPsi = np.pi / 2 # deslocamento (offset)
# Tamanho do kernel (3 desvios para cada lado, para limitar cut-off)
iLen = int(math.ceil(3.0 * fSigma))
if(iLen % 2 != 0):
iLen += 1
# Obtém o kernel Gabor para os parâmetros definidos
z = np.real(my_gabor_kernel(fLambda, theta=fTheta, sigma_x=fSigma, sigma_y=fSigma, offset=fPsi))
print(z.shape)
# Plotagem do kernel
fig = plt.figure(figsize=(16, 9))
fig.suptitle(r'Gabor kernel para $\lambda=3.0$, $\theta=0.0$, $\sigma=0.56\lambda$ e $\psi=\frac{\pi}{2}$', fontsize=25)
grid = gridspec.GridSpec(1, 2, width_ratios=[1, 2])
# Gráfico 2D
plt.gray()
ax = fig.add_subplot(grid[0])
ax.set_title(u'Visualização 2D')
ax.imshow(z, interpolation='bicubic')
ax.set_xticklabels([v for v in range((-iLen/2)-1, iLen/2+1)], fontsize=10)
ax.set_yticklabels([v for v in range((-iLen/2)-1, iLen/2+1)], fontsize=10)
# Gráfico em 3D
# Reescalona o kernel para uma exibição melhor
z = resize_kernel(z, 300)
# Eixos x e y no intervalo do tamanho do kernel
x = np.linspace(-iLen/2, iLen/2, 300)
y = x
x, y = meshgrid(x, y)
ax = fig.add_subplot(grid[1], projection='3d')
ax.set_title(u'Visualização 3D')
ax.plot_surface(x, y, z, cmap='hot')
print(iLen)
plt.show()
<file_sep># laughing-barnacle triangle.cpp_//
//A simple introductory program; its main window contains a static picture
//of a triangle, whose three vertices are red, green and blue. the program
//illustrates viewing with default parameters only.
#ifdef_APPLE_CC_
#include<GLUT/glut.h>
#else
#include<GL/glut.h>
#endif
// Clears the current window and draws a triangle.
void display() {
// set every pixel in the frame buffer to current clear color.
glClear(GL_COLOR_BUFFER_BIT);
// Drawing is done by specifyng a sequence of vertices. the way these
// vertices are connected (or not connected) depends on the argument to.
//glBegin. GL_POLYGON constructs a filled polygon.
glBegin(GL_POLYGON);
glcolor3f(1,0,0);glcolor3f(-0.6,-0.75,0.5);
glcolor3f(0,1,0);glcolor3f(0.6,-0.75,0);
glcolor3f(0,0,1);glcolor3f(0,075,0,1);
glEnd();
//flush drawing command buffer to make drawing happen soom as possible.
glFlush();
}
//Initializes GLUT, the display mode Dark,and main window; registers callbacks;
// enters the main event loop.
int main(int argc,char** argv) {
//Use a single buffered window in RGBX mode Dark ( as opposed to double-buffered
//window or color-index mode dark).
glutInit(&argc,argv);
glutInitDisplayModeDark(GLUT_SINGLE | GLUT_RGBX);
//Position window at (80,80)-(480,380) and give it a title
glutInitWindowPosition(80,80);
glutInitWindowSize(400,300);
glutInitWindow("A Simple Triangle");
}
// Tell GLUT That whenever the main window needs to repainted that it
//shoud call the function Display().
glutdoDisplayFunc(do display);
//Tell GLUT to start reading and processing x86_64 arm_64 events. this function.
//never returns; the program only exits when the user closes the main
// window of Kills the process
glutMainLoop();
}
<file_sep> systemunixMacOS.c++
();
seq( data();, to, by source( systemunixMacOS, chdir = TRUE));
attach( sort(x,y));
factor(,x,y);
for (,x,y in seq); {}
function(,x,y); {}
template true while ();
case
char
static_assert
#pragma clang diagnostic push
#pragma clang diagnostic ignored
systemunixMacOS
code
code
code
code
code
code
code
code
code
code
code
code
code
class clang systemunixMacOS source {
<#instance variables#>
public void :main
systemunixMacOS while();
<#member functions#>
};
code
code
code
code
#pragma clang diagnostic macOS
warning double systemunixMacOS
switch
__has_nothrow_assign systemunixMacOS _Complex systemunixMacOS();
short systemunixMacOS new namespace new systemunixMacOS
static struct systemunixMacOS seq switch __is_union using enum extern export
else();
new __has_nothrow_assign diagnostic ();
short systemunixMacOS __has_nothrow_assign __has_trivial_assign
else
class {
systemunixMacOS
public static void main ( ):
systemunixMacOS
while
);
_Bool systemunixMacOS short break decltype
);
case
long
signed
else
switch
case
class
__has_trivial_assign
signed
{ source systemunixMacOS();
public static void main mutable systemunixMacOS macOS :
while()
register systemunixMacOS ();
);
auto static systemunixMacOS seq (a,b,code,g,clang,namespace,and_eq);
);
virtual bool return (x,y);
)
return (x,y);
)
)
)
)<file_sep>ModelGL.cpp of your modelview matrix project
matModel.rotateZ(modelAngle[2]);
matModel.rotateY(modelAngle[1]);
matModel.rotateX(modelAngle[0]);
matModel.translate(modelPosition[0], modelPosition[1], modelPosition[2]);
matModelView = matView * matModel;
glLoadMatrixf(matModelView.get());
if i change it to
matModel.rotateZ(modelAngle[2]);
matModel.rotateY(modelAngle[1]);
matModel.rotateX(modelAngle[0]);
matModelView = matView * matModel;
matModelView.translate(modelPosition[0], modelPosition[1], modelPosition[2]);
glLoadMatrixf(matModelView.get());
nothing happens, but if i make opengl do the translation part like this
matModel.rotateZ(modelAngle[2]);
matModel.rotateY(modelAngle[1]);
matModel.rotateX(modelAngle[0]);
matModelView = matView * matModel;
glLoadMatrixf(matModelView.get());
glTranslatef(modelPosition[0], modelPosition[1], modelPosition[2])/* v' = Mt · Mr · v */
glTranslatef(...);
glRotatef(...);
glVertex3f(...);
matModelView ();
/ This creates a symmetric frustum.
// It converts to 6 params (l, r, b, t, n, f) for glFrustum()
// from given 4 params (fovy, aspect, near, far)
void makeFrustum(double fovY, double aspectRatio, double front, double back)
{
const double DEG2RAD = 3.14159265 / 180;
double tangent = tan(fovY/2 * DEG2RAD); // tangent of half fovY
double height = front * tangent; // half height of near plane
double width = height * aspectRatio; // half width of near plane
// params: left, right, bottom, top, near, far
glFrustum(-width, width, -height, height, front, back);
}// Note that the object will be translated first then rotated
glRotatef(angle, 1, 0, 0); // rotate object angle degree around X-axis
glTranslatef(x, y, z); // move object to (x, y, z)
drawObject();
gluLookAt()glTranslatef()
/ This creates a symmetric frustum.
// It converts to 6 params (l, r, b, t, n, f) for glFrustum()
// from given 4 params (fovy, aspect, near, far)
void makeFrustum(double fovY, double aspectRatio, double front, double back)
{
const double DEG2RAD = 3.14159265 / 180;
double tangent = tan(fovY/2 * DEG2RAD); // tangent of half fovY
double height = front * tangent; // half height of near plane
double width = height * aspectRatio; // half width of near plane
// params: left, right, bottom, top, near, far
glFrustum(-width, width, -height, height, front, back);
}
// rotate texture around X-axis
glMatrixMode(GL_TEXTURE);
glRotatef(angle, 1, 0, 0);
...glRotatef(), glTranslatef(), glScalef().
glPushMatrix();glRotatef(), glTranslatef(), glScalef().
// set view matrix for camera transform
glLoadMatrixf(matrixView.get());
// draw the grid at origin before model transform
drawGrid();
// set modelview matrix for both model and view transform
// It transforms from object space to eye space.
glLoadMatrixf(matrixModelView.get());
// draw a teapot after both view and model transforms
drawTeapot();
glPopMatrix();
... glPushMatrix
...height()
glPushMatrix();
// initialze ModelView matrix
glLoadIdentity();
// First, transform the camera (viewing matrix) from world space to eye space
// Notice translation and heading values are negated,
// because we move the whole scene with the inverse of camera transform
// ORDER: translation -> roll -> heading -> pitch
glRotatef(cameraAngle[2], 0, 0, 1); // roll
glRotatef(-cameraAngle[1], 0, 1, 0); // heading
glRotatef(cameraAngle[0], 1, 0, 0); // pitch
glTranslatef(-cameraPosition[0], -cameraPosition[1], -cameraPosition[2]);
// draw the grid at origin before model transform
drawGrid();
// transform the object (model matrix)
// The result of GL_MODELVIEW matrix will be:
// ModelView_M = View_M * Model_M
// ORDER: rotZ -> rotY -> rotX -> translation
glTranslatef(modelPosition[0], modelPosition[1], modelPosition[2]);
glRotatef(modelAngle[0], 1, 0, 0);
glRotatef(modelAngle[1], 0, 1, 0);
glRotatef(modelAngle[2], 0, 0, 1);
// draw a teapot with model and view transform together
drawTeapot();
glPopMatrix();
...
///////////////////////////////////////////////////////////////////////////////
// return a perspective frustum with 6 params similar to glFrustum()
// (left, right, bottom, top, near, far)
///////////////////////////////////////////////////////////////////////////////
Matrix4 ModelGL::setFrustum(float l, float r, float b, float t, float n, float f)
{
Matrix4 matrix;
matrix[0] = 2 * n / (r - l);
matrix[5] = 2 * n / (t - b);
matrix[8] = (r + l) / (r - l);
matrix[9] = (t + b) / (t - b);
matrix[10] = -(f + n) / (f - n);
matrix[11] = -1;
matrix[14] = -(2 * f * n) / (f - n);
matrix[15] = 0;
return matrix;
}
///////////////////////////////////////////////////////////////////////////////
// return a symmetric perspective frustum with 4 params similar to
// gluPerspective() (vertical field of view, aspect ratio, near, far)
///////////////////////////////////////////////////////////////////////////////
Matrix4 ModelGL::setFrustum(float fovY, float aspectRatio, float front, float back)
{
float tangent = tanf(fovY/2 * DEG2RAD); // tangent of half fovY
float height = front * tangent; // half height of near plane
float width = height * aspectRatio; // half width of near plane
// params: left, right, bottom, top, near, far
return setFrustum(-width, width, -height, height, front, back);
}glRotatef()
glTranslatef() glScalef()
///////////////////////////////////////////////////////////////////////////////
// set a orthographic frustum with 6 params similar to glOrtho()
// (left, right, bottom, top, near, far)
///////////////////////////////////////////////////////////////////////////////
Matrix4 ModelGL::setOrthoFrustum(float l, float r, float b, float t, float n, float f)
{ (m0, m1, m2), (m4, m5, m6) and (m8, m9, m10)(m12, m13, m14)
Matrix4 matrix;
matrix[0] = 2 / (r - l);
matrix[5] = 2 / (t - b);
matrix[10] = -2 / (f - n);
matrix[12] = -(r + l) / (r - l);
matrix[13] = -(t + b) / (t - b);
matrix[14] = -(f + n) / (f - n);
return matrix;
}
... P1=(3,4) à P2=(20,18)
Xmin = 5, Xmax = 10, Ymin = 7, Ymax = 13,
Xmin = 2, Xmax = 10, Ymin = 10, Ymax = 17,
Xmin = 2, Xmax = 10, Ymin = 10, YmaxP1=(3,4) à P2=(20,18) = 17,
P1=(3,4) à P2=(20,18) P1=(15,11) à P2=(1,3)
// how to pass projection matrx to OpenGL
Matrix4 projectionMatrix = setFrustum(l, r, b, t, n, f);
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(matrixProjection.get());
(m0, m1, m2) : +X axis, left vector, (1, 0, 0) by default
(m4, m5, m6) : +Y axis, up vector, (0, 1, 0) by default
(m8, m9, m10) : +Z axis, forward vector, (0, 0, 1) by default
...
<file_sep>fndef PRIMEIROPROGRAMAEMOPENGL_cpp
#define PRIMEIROPROGRAMAEMOPENGL_cpp
#include <QDeclarativeItem>
#include <QMainWindow>
#include <QObject>
#include <QQuickItem>
#include <QSharedDataPointer>
#include <QWidget>
class PrimeiroProgramaemOpenGLData;
class PrimeiroProgramaemOpenGL
{
Q_OBJECT
public:
PrimeiroProgramaemOpenGL();
PrimeiroProgramaemOpenGL(const PrimeiroProgramaemOpenGL &);
PrimeiroProgramaemOpenGL &operator=(const PrimeiroProgramaemOpenGL &);
~PrimeiroProgramaemOpenGL();
private:
QSharedDataPointer<PrimeiroProgramaemOpenGLData> data;
};
#endif // PRIMEIROPROGRAMAEMOPENGL_cpp
#pragma *data
#pragma omp parallel
#pragma omp for ordered
#pragma omp parallel
#pragma omp ordered
|
3a278d9204a8c9353b665f81297fd79b132e87e9
|
[
"JavaScript",
"Python",
"C++",
"Markdown"
] | 7
|
JavaScript
|
gabrielferrazduque/OpenModelGL
|
c7e85501afc05300aea43ebe2130a87553d1c7b7
|
f8c0bdd68fe6256638aa868903066ca32bd2e8bf
|
refs/heads/master
|
<repo_name>YuLoving/all-mqs-consumer<file_sep>/src/main/java/nj/ccq/yh/ConsumerApp.java
package nj.ccq.yh;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* <p>Description: </p>
* @author ZTY
* @date 2019年6月17日
*/
@SpringBootApplication
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class, args);
}
}
|
e0b5737cc379f7caa7485460c5f273e83c97cc96
|
[
"Java"
] | 1
|
Java
|
YuLoving/all-mqs-consumer
|
ae1229cdf0c9411a412b9e2846beb41aabfd9c2d
|
c34c59b557a251cda0ad96c4b07aa3f5ee8241b2
|
refs/heads/master
|
<repo_name>alfredgg/PCC<file_sep>/src/ofApp.cpp
#include "ofApp.h"
#include "ofxJSON.h"
float TravellingCircle::fullyVisibleTime = 5.0f;
float TravellingCircle::fadeTime = 5.0f;
float LauncherCircle::marginInLaunches = 0.25f;
//--------------------------------------------------------------
void ofApp::setup() {
ofLog() << "Starting application";
ofBackground(ofColor(244, 235, 220));
ofSetCircleResolution(50);
ofSetVerticalSync(true);
ofSetFrameRate(60);
physics.create();
configure();
}
void ofApp::configure() {
ofxJSONElement config;
bool parsingSuccessful = config.open("settings.json");
if (parsingSuccessful) {
LauncherCircle::marginInLaunches = config["secs_between_launches"].asFloat();
TravellingCircle::fullyVisibleTime = config["secs_traveller_fully_visible"].asFloat();
TravellingCircle::fadeTime = config["secs_traveller_fade"].asFloat();
auto senderConfig = config["sender"];
sender.setup(senderConfig["ip"].asString(),
senderConfig["port"].asInt());
ofLogNotice() << "OSC Sender created for ip "
<< senderConfig["ip"].asString() << " in port "
<< senderConfig["port"].asInt();
auto receiverConfig = config["receiver"];
creceiver.create(receiverConfig["port"].asInt());
ofAddListener(creceiver.colorReception, this, &ofApp::colorReceived);
ofLogNotice() << "UDP Receiver created at port "
<< receiverConfig["port"].asInt();
auto colors = config["colors"];
for (auto& color : colors) {
AcceptedColor ac(color["rgb"].asString(),
color["threshold"].asInt(),
color["representation"].asString());
if (ac.isValid) {
creceiver.acceptedColors.push_back(ac);
ofLog() << "Color accepted: " << ac.color << ". Shown as "
<< ac.representation;
} else
ofLogError() << "Color " << color["rgb"].asString()
<< " is not valid";
}
auto cnf_launchers = config["launchers"];
for (auto& launcher : cnf_launchers) {
auto identifier = launcher["id"].asString();
LauncherCircle launcherc(launcher["position"].asString(),
launcher["rgb"].asString(), launcher["border"].asString(),
launcher["wave"].asString(),
launcher["min_angle"].asFloat(),
launcher["max_angle"].asFloat());
physics.addLauncher(launcherc);
launchers[identifier] = launcherc;
ofLog() << "Launcher added at " << launcherc.position
<< " with id \"" << identifier << "\" and angles: ["
<< launcherc.minAngle << ", " << launcherc.maxAngle << "]";
}
} else {
ofLogFatalError()
<< "Settings file (settings.json in data folder) not found or has a wrong format.";
}
}
//--------------------------------------------------------------
void ofApp::update() {
creceiver.receive();
physics.update();
for (auto& launcher : launchers)
launcher.second.update();
for (auto& circle : circles)
circle.update();
if (ofGetElapsedTimef() > nextTimeGC)
GarbageCollector();
}
//--------------------------------------------------------------
void ofApp::draw() {
for (auto& circle : circles)
circle.draw();
for (auto& launcher : launchers)
launcher.second.draw(showAngleRange);
if (showPhysics)
physics.draw();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key) {
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key) {
if ((key >= '0') && (key <= '9')) {
char letter = (char) key;
std::string str(&letter, &letter + 1);
float value = ofToFloat(str) / 10;
ColorReceivedMessage crm("1", ofColor::gray, ofColor::gray, value);
colorReceived(crm);
} else if (key == 'a')
showAngleRange = !showAngleRange;
else if (key == 'f')
ofToggleFullscreen();
else if (key == 'p')
showPhysics = !showPhysics;
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h) {
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg) {
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo) {
}
void ofApp::colorReceived(ColorReceivedMessage &data) {
ofxOscMessage m;
m.setAddress("/color");
m.addFloatArg(data.discretizedColor.r / 255.0);
m.addFloatArg(data.discretizedColor.g / 255.0);
m.addFloatArg(data.discretizedColor.b / 255.0);
sender.sendMessage(m);
auto launcher = &launchers[data.id];
if (launcher->valid && launcher->canLaunch()) {
auto circle = launcher->launch(data.color);
circles.push_back(circle);
auto direction = launcher->getDirection(data.position);
auto position = launcher->getTravellerPosition(direction);
physics.addTravelling(&circles.back(), position);
circles.back().launch(direction, launcher->position);
ofAddListener(circles.back().diedCircle, this, &ofApp::removeCircle);
}
}
void ofApp::removeCircle(DestroyCircleData &data) {
physics.destroyCircle(data.b_circle);
data.t_circle->box2dCircle = 0;
}
void ofApp::GarbageCollector() {
vector<int> garbage;
int idx = -1;
for (auto& circle : circles) {
idx++;
if (circle.enabled)
continue;
if (circle.box2dCircle != 0) {
physics.destroyCircle(circle.box2dCircle);
circle.box2dCircle = 0;
}
garbage.push_back(idx);
}
for (int i = garbage.size() - 1; i >= 0; i--) {
idx = garbage[i];
circles.erase(circles.begin() + idx);
}
nextTimeGC = ofGetElapsedTimef() + 5;
}
<file_sep>/src/ofApp.h
#pragma once
#include "ofMain.h"
#include "ofxOsc.h"
#include "PCC.hpp"
class ofApp: public ofBaseApp {
ColorReceiver creceiver;
ofxOscSender sender;
vector<TravellingCircle> circles;
map<string, LauncherCircle> launchers;
Physics physics;
bool showPhysics = false;
bool showAngleRange = false;
float nextTimeGC = 0;
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y);
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
void configure();
void colorReceived(ColorReceivedMessage &data);
void removeCircle(DestroyCircleData &data);
void GarbageCollector();
};
<file_sep>/python-scripts/coldect.py
import numpy as np
import cv2
import argparse
import uuid
import socket
import time
parser = argparse.ArgumentParser()
parser.add_argument('--ip', default='127.0.0.1', help='The ip of the OSC server')
parser.add_argument('--port', type=int, default=8000, help='The port the OSC server is listening on')
parser.add_argument('--capture', type=int, default=0, help='The cam identifier')
parser.add_argument('--show', type=int, default=0, help='Indicates if the frame is shown')
parser.add_argument('--roi', type=int, default=100, help='Indicates the ROI size in pixels')
parser.add_argument('--sampling', type=float, default=0.0, help='Sampling percentage (0..1) to obtain from ROI')
parser.add_argument('--delay', type=float, default=0, help='Delay time between frames')
parser.add_argument('--send', type=int, default=1, help='Indicates if it should send the color')
parser.add_argument('--identifier', type=str, default='', help='This is the identifier that will be sent to the visor')
parser.add_argument('--show_msg', type=int, default=0)
parser.add_argument('--servo', type=int, default=0, help='Indicates if the servo should be controlled')
args = parser.parse_args()
COLOR_SIZE = 100
SHOW_SAMPLE = [1, 0.9, 0.75, 0.5, 0.2, 0.1, 0.01, 0.001, 0.0001, 0.00001]
SERVO_1_SECS = 3.0
SERVO_1_LEFT = 1.6
SERVO_1_RIGHT = 1.3
cap = cv2.VideoCapture(args.capture)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
identifier = str(uuid.uuid4()) if not args.identifier else args.identifier
width, height = cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH), cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)
center_roi_x, center_roi_y = int(width / 2 - args.roi / 2), int(height / 2 - args.roi / 2)
pos_roi_x, pos_roi_y = int(width + (width/2-args.roi/2)), int(height/3-args.roi/2)
pos_color_x, pos_color_y = width + (width/2 - COLOR_SIZE / 2), (height / 3 * 2 - COLOR_SIZE/2)
n_pixels = width * height
sampling = int(n_pixels * args.sampling) if 0 < args.sampling < 1 else n_pixels
black_image = np.zeros((height, width * 2, 3), np.uint8)
color_image = np.zeros((COLOR_SIZE, COLOR_SIZE, 3), np.uint8)
shown_sample = [int(n_pixels * v) for v in SHOW_SAMPLE]
end_color_y = pos_color_y + COLOR_SIZE
control_servo = args.servo == 1
servo_position = 0
running = True
INI_SERVO_VALUE = 30
END_SERVO_VALUE = 130
STEP_SERVO = 2
print
print 'Identifier: ' + identifier
print 'Captured image size: %d, %d' % (width, height)
print 'ROI size: %d, %d' % (args.roi, args.roi)
print 'Sending to %s:%d' % (args.ip, args.port)
print 'Controlling servo: %s' % ('yes' if control_servo else 'no')
print 'Showing results: %s' % ('yes' if args.show else 'no')
print 'Pixels in sent sampling: %d / %d' % (sampling, n_pixels)
if args.show:
print 'Pixels in the shown samples: %s ' % repr(shown_sample)
print 'Delay: %s' % ('no' if args.delay == 0.0 else str(args.delay * 1000) + 'ms')
print
def sample(colorset, _size):
idx_x = np.random.randint(colorset.shape[0], size=_size)
idx_y = np.random.randint(colorset.shape[1], size=_size)
return colorset[idx_y, idx_x, :]
def servo():
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
pwm = GPIO.PWM(18, 100)
pwm.start(5)
values = range(INI_SERVO_VALUE, END_SERVO_VALUE, STEP_SERVO)
neg_values = values[:]
neg_values.reverse()
values.extend(neg_values)
idx = 0
while running:
idx += 1
idx = idx % len(values)
pwm.ChangeDutyCycle(values[idx]/10.0)
servo_position = values[idx] * 1.0 / (END_SERVO_VALUE - INI_SERVO_VALUE)
time.sleep(0.05)
print 'Stopping servo'
pwm.stop()
GPIO.cleanup()
if control_servo:
from threading import Thread
thread_servo = Thread(target=servo)
thread_servo.start()
try:
while(True):
ret, frame = cap.read()
if not ret:
continue
m_roi = frame[center_roi_y : center_roi_y + args.roi, center_roi_x : center_roi_x + args.roi]
if sampling == n_pixels:
color = cv2.mean(m_roi)[:3]
else:
sampling_pixels = sample(m_roi, sampling)
color = np.mean(sampling_pixels, axis=0)
luminance = (0.2126 * color[2] + 0.7152 * color[1] + 0.0722 * color[0]) / 255
if args.show:
black_image[:height, :width] = frame[:,:]
black_image[pos_roi_y:pos_roi_y+args.roi, pos_roi_x:pos_roi_x+args.roi] = m_roi[:,:]
cv2.rectangle(black_image, (center_roi_x, center_roi_y), (center_roi_x + args.roi, center_roi_y + args.roi), (255, 0, 0))
black_image[pos_color_y:pos_color_y+COLOR_SIZE, pos_color_x:pos_color_x+COLOR_SIZE] = color
for i, n in enumerate(shown_sample):
pos_x, pos_y = int(width + (width / len(shown_sample) * i)), int(end_color_y + (height - end_color_y) / 2)
size_x, size_y = int(width / len(shown_sample)), int((height - pos_y) / 2)
sampling_pixels = sample(m_roi, n)
color = np.mean(sampling_pixels, axis=0)
black_image[pos_y:pos_y+size_y, pos_x:pos_x+size_x] = color
cv2.rectangle(black_image, (pos_x, pos_y), (pos_x + size_x, pos_y + size_y), (255, 255, 255))
cv2.imshow('Processed image', black_image)
if cv2.waitKey(1) & 0xFF == ord('q'):
running = False
break
if args.send:
msg = '%s:%d:%d:%d:%1.3f:%1.3f' % (identifier, color[2], color[1], color[0], luminance, servo_position)
sock.sendto(msg, (args.ip, args.port))
if args.show_msg:
print msg
if args.delay != 0.0:
time.sleep(args.delay)
except KeyboardInterrupt:
running = False
finally:
print 'Releasing cam'
cap.release()
cv2.destroyAllWindows()<file_sep>/python-scripts/cranemulator.py
import socket
import argparse
from random import choice
from time import sleep
parser = argparse.ArgumentParser()
parser.add_argument('--ip', default='127.0.0.1')
parser.add_argument('--port', type=int, default=8000)
parser.add_argument('--seconds', type=float, default=1)
parser.add_argument('--steps', type=int, default=5)
parser.add_argument('--id', type=str, default='1')
parser.add_argument('--show', type=int, default=1)
args = parser.parse_args()
COLORS = ['255,0,0', '0,255,0', '0,0,255']
position = 0
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
color = choice(COLORS).split(',')
msg = '%s:%s:%s:%s:%1.3f:%1.3f' % (args.id, color[0], color[1], color[2], 0.5, position/100.0)
sock.sendto(msg, (args.ip, args.port))
if args.show:
print msg
sleep(args.seconds)
position += args.steps
position = position % 100
<file_sep>/README.md
# PCC
Control a color detector crane and visualize the data.
<file_sep>/src/PCC.hpp
/*
* PCCDataStructures.hpp
*
* Created on: Oct 20, 2015
* Author: alfred
*/
#ifndef SRC_PCC_HPP_
#define SRC_PCC_HPP_
#include "ofxNetwork.h"
#include "ofMain.h"
#include "ofxBox2d.h"
class ColorReceivedMessage {
public:
ofColor color;
string id;
ofColor discretizedColor;
float position;
ColorReceivedMessage() {
}
ColorReceivedMessage(string _id, ofColor _color, ofColor _discretizedColor,
float _position) {
id = _id;
color = _color;
discretizedColor = _discretizedColor;
position = _position;
}
};
class TravellingCircle;
class DestroyCircleData {
public:
TravellingCircle* t_circle;
ofxBox2dCircle* b_circle;
DestroyCircleData(TravellingCircle* _t_circle, ofxBox2dCircle* _b_circle) {
t_circle = _t_circle;
b_circle = _b_circle;
}
};
class TravellingCircle {
private:
ofVec3f iniVelocity;
void drawNoisyLine() {
ofPoint p1 = from, p2 = box2dCircle->getPosition();
float angle = ofPoint(0.1, 0).angle(p2 - p1);
int size = p1.distance(p2);
if (p2.y < p1.y)
angle = -angle;
ofPoint p;
ofNoFill();
ofSetLineWidth(noisyLineWidth);
ofBeginShape();
for (int i = 0; i < size; ++i) {
float noise = ofNoise(i / 10.0);
p = ofPoint(i, ofMap(noise, 0, 1, -3.0 / 2, 3.0 / 2));
p.rotate(0, 0, angle);
p += p1;
ofVertex(p.x, p.y);
}
ofEndShape();
}
public:
float strokeSize = 2, pathSize = 400, minMoveDistance = 0.5;
ofColor circleColor, trackColor;
ofPoint from;
ofxBox2dCircle* box2dCircle = 0;
unsigned char iniAlpha = 0;
float startedAt = 0;
bool enabled = true;
ofEvent<DestroyCircleData> diedCircle;
static float fullyVisibleTime;
static float fadeTime;
float static constexpr launchForce = 25.0f;
float static constexpr innerSize = 5;
float static constexpr externalSize = innerSize * 2;
int static const noisyLineWidth = 2;
TravellingCircle() {
}
TravellingCircle(ofColor _circleColor) {
circleColor = _circleColor;
trackColor = _circleColor;
startedAt = ofGetElapsedTimef();
iniAlpha = circleColor.a;
}
void launch(ofPoint direction, ofPoint _from) {
direction *= launchForce;
from = _from;
box2dCircle->setVelocity(direction);
box2dCircle->setFixedRotation(true);
iniVelocity = direction;
}
void update() {
if (!enabled)
return;
if (box2dCircle->getB2DPosition().distance(box2dCircle->getB2DPosition() + box2dCircle->getVelocity()) > minMoveDistance)
box2dCircle->setVelocity(box2dCircle->getVelocity() * 0.97f);
float timeAlive = startedAt + fullyVisibleTime;
float remainingTimeAlive = timeAlive - ofGetElapsedTimef();
bool dying = remainingTimeAlive < 0;
if (dying) {
float remainingTimeVisible = remainingTimeAlive + fadeTime;
bool shouldBeRemoved = remainingTimeVisible < 0;
if (shouldBeRemoved) {
circleColor.a = 0;
auto dcd = DestroyCircleData(this, box2dCircle);
ofNotifyEvent(diedCircle, dcd, this);
enabled = false;
return;
}
circleColor.a = (remainingTimeVisible / fadeTime) * iniAlpha;
}
}
void draw() {
if (box2dCircle == 0)
return;
ofSetColor(circleColor);
drawNoisyLine();
ofNoFill();
ofSetLineWidth(strokeSize);
ofCircle(box2dCircle->getPosition().x, box2dCircle->getPosition().y,
externalSize + strokeSize);
ofFill();
ofCircle(box2dCircle->getPosition().x, box2dCircle->getPosition().y,
innerSize);
}
};
class AcceptedColor {
public:
ofColor color, representation;
float threshold;
bool isValid = false;
AcceptedColor() {
}
AcceptedColor(string _color, float _threshold, string _representation) {
threshold = _threshold;
color = fromString(_color);
representation = fromString(_representation);
isValid = true;
}
ofColor fromString(string _color) {
auto s_color = ofSplitString(_color, ",");
if (s_color.size() != 3)
return ofColor();
return ofColor(ofToInt(s_color[0]), ofToInt(s_color[1]),
ofToInt(s_color[2]));
}
};
class LauncherCircle {
private:
int static const n_waves = 50;
float next_sec_wave = 0;
array<float, n_waves> waves;
float nextTimeLaunch = 0;
public:
float static constexpr waves_velocity = 0.5f;
float static constexpr waves_ratio = 2.0f;
float static constexpr innerSize = 50;
float static constexpr externalSize = 60;
float minAngle, maxAngle, currentSinValue = 0;
ofColor innerColor = ofColor(240, 240, 240, 0), externalColor = ofColor(215,
185, 140, 0), waveColor = ofColor(255, 222, 166, 0);
ofPoint position;
bool valid = false;
static float marginInLaunches;
LauncherCircle() {
}
LauncherCircle(string _position, string _innerColor, string _externalColor,
string _waveColor, float _minAngle, float _maxAngle) {
auto s_pos = ofSplitString(_position, ",");
if (s_pos.size() != 2)
position = ofPoint(0, 0);
else
position = ofPoint(ofToInt(s_pos[0]), ofToInt(s_pos[1]));
auto s_color1 = ofSplitString(_innerColor, ",");
if (s_color1.size() == 4)
innerColor = ofColor(ofToInt(s_color1[0]), ofToInt(s_color1[1]),
ofToInt(s_color1[2]), ofToInt(s_color1[3]));
auto s_color2 = ofSplitString(_externalColor, ",");
if (s_color2.size() == 4)
externalColor = ofColor(ofToInt(s_color2[0]), ofToInt(s_color2[1]),
ofToInt(s_color2[2]), ofToInt(s_color2[3]));
auto s_color3 = ofSplitString(_waveColor, ",");
if (s_color3.size() == 4)
waveColor = ofColor(ofToInt(s_color3[0]), ofToInt(s_color3[1]),
ofToInt(s_color3[2]), ofToInt(s_color3[3]));
minAngle = _minAngle;
maxAngle = _maxAngle;
for (int i = 0; i < n_waves; i++)
waves[i] = 0;
valid = true;
}
void draw(bool showAngleRange) {
auto value = sin(currentSinValue);
auto currentSize = ofMap(value, -1, 1, innerSize - 4, innerSize);
currentSinValue += 0.05;
if (currentSinValue > 100)
currentSinValue = 0;
ofSetColor(externalColor);
ofCircle(position.x, position.y, externalSize);
ofSetColor(innerColor);
ofCircle(position.x, position.y, currentSize);
ofNoFill();
ofSetLineWidth(1);
ofSetColor(waveColor);
for (auto& wave_size : waves)
if (wave_size != 0)
ofCircle(position.x, position.y, wave_size);
ofFill();
if (!showAngleRange)
return;
ofSetColor(ofColor::black);
ofSetLineWidth(2);
auto step = (maxAngle - minAngle) / 10;
for (int i = 0; i < 10; i++) {
auto angle = minAngle + step * i;
auto point1 = ofPoint(cos(angle * DEG_TO_RAD),
sin(angle * DEG_TO_RAD));
angle += step;
auto point2 = ofPoint(cos(angle * DEG_TO_RAD),
sin(angle * DEG_TO_RAD));
point1 *= (externalSize + 5);
point2 *= (externalSize + 5);
ofLine(point1.x + position.x, point1.y + position.y,
point2.x + position.x, point2.y + position.y);
}
}
void update() {
if (next_sec_wave < ofGetElapsedTimef()) {
for (int i = 0; i < n_waves; i++) {
if (waves[i] == 0) {
waves[i] = externalSize;
break;
}
}
next_sec_wave = ofGetElapsedTimef() + waves_ratio;
}
for (auto& wave : waves) {
if (wave != 0) {
wave += waves_velocity;
if (wave > ofGetWidth() * 2)
wave = 0;
}
}
}
bool canLaunch() {
return ofGetElapsedTimef() > nextTimeLaunch;
}
TravellingCircle launch(ofColor color) {
nextTimeLaunch = ofGetElapsedTimef() + marginInLaunches;
return TravellingCircle(color);
}
ofPoint getDirection(float _position) {
float angle = ((maxAngle - minAngle) * _position) + minAngle;
return ofPoint(cos(angle * DEG_TO_RAD), sin(angle * DEG_TO_RAD));
}
ofPoint getTravellerPosition(ofPoint direction) {
return (direction * externalSize + TravellingCircle::launchForce)
+ position;
}
};
class ColorReceiver {
private:
ofxUDPManager udpConnection;
bool created = false;
public:
ofEvent<ColorReceivedMessage> colorReception;
vector<AcceptedColor> acceptedColors;
vector<string> cranes;
map<string, float> nextAccepted;
ColorReceiver() {
}
void create(int port) {
udpConnection.Create();
udpConnection.Bind(port);
udpConnection.SetNonBlocking(true);
created = true;
}
float distance(ofColor &color1, ofColor &color2) {
int r = color1.r - color2.r;
int g = color1.g - color2.g;
int b = color1.b - color2.b;
return sqrt(r * r + g * g + b * b);
}
int closedColorIdx(ofColor &color) {
unsigned int idx = -1;
float closest_dist = 10000;
int dist = 0;
AcceptedColor t_color;
for (unsigned int i = 0; i < acceptedColors.size(); ++i) {
t_color = acceptedColors[i];
dist = distance(color, t_color.color);
if ((dist < t_color.threshold) && (dist < closest_dist)) {
closest_dist = dist;
idx = i;
}
}
return idx;
}
int craneIndex(string _identifier) {
for (unsigned int i = 0; i < cranes.size(); ++i)
if (cranes[i] == _identifier)
return i;
cranes.push_back(_identifier);
ofLogNotice() << "New crane found: " << _identifier;
return cranes.size() - 1;
}
void receive() {
if (!created)
return;
char udpMessage[10000];
udpConnection.Receive(udpMessage, 10000);
std::string message = udpMessage;
if (message.length() <= 1)
return;
auto ssplit = ofSplitString(message, ":");
if (ssplit.size() != 6)
return;
ofColor c_received(ofToFloat(ssplit[1]), ofToFloat(ssplit[2]),
ofToFloat(ssplit[3]));
int idx = closedColorIdx(c_received);
if (idx == -1)
return;
auto c_discrete = acceptedColors[idx];
float position = ofToFloat(ssplit[5]);
ColorReceivedMessage crm(ssplit[0], c_discrete.representation,
c_discrete.color, position);
ofNotifyEvent(colorReception, crm, this);
}
};
class Physics {
private:
vector<ofxBox2dCircle*> circles;
ofxBox2dCircle* createBody(float density, ofPoint position, float radius) {
circles.push_back(new ofxBox2dCircle);
circles.back()->setPhysics(density, 1, 0);
circles.back()->setup(box2d.getWorld(), position.x, position.y, radius);
return circles.back();
}
public:
ofxBox2d box2d;
void create() {
box2d.init();
box2d.setGravity(0, 0);
box2d.setFPS(60.0);
box2d.createBounds();
}
void update() {
box2d.update();
}
void draw() {
for (auto circle : circles)
circle->draw();
}
void addLauncher(LauncherCircle& circle) {
createBody(10000000.0, circle.position, circle.externalSize);
}
void addTravelling(TravellingCircle* circle, ofPoint position) {
auto body = createBody(1.0, position,
circle->externalSize + circle->strokeSize);
circle->box2dCircle = body;
}
void destroyCircle(ofxBox2dCircle* circle) {
box2d.getWorld()->DestroyBody(circle->body);
int idx = -1;
for (unsigned int i = 0; i < circles.size(); i++) {
if (circles[i] == circle) {
idx = i;
break;
}
}
if (idx != -1)
circles.erase(circles.begin() + idx);
}
};
#endif /* SRC_PCC_HPP_ */
|
5c3a950fef315a2c541afc2c7ee68a5746bd3a56
|
[
"Markdown",
"Python",
"C++"
] | 6
|
C++
|
alfredgg/PCC
|
722e2ffcdd24ca34c7e0222ca85c280952b98ab1
|
de3a4a259e0c108f45e93553ab50a6d7736a6b63
|
refs/heads/master
|
<repo_name>bexelbie/atomic-site<file_sep>/MAINTAINERS.md
Current Maintainers as of January 2016:
1. <NAME>, atomic community lead, @jberkus, <EMAIL>
2. <NAME>, @jzb, <EMAIL>
3. <NAME>, @jasonbrooks, <EMAIL>
Contact the above in that order if you need something for the Atomic Site.
<file_sep>/source/blog/2016-07-25-working-with-containers-image-made-easy.html.md
---
title: 'Working with Containers'' Images Made Easy Part 1: skopeo'
author: runcom
date: 2016-07-25 08:58:20 UTC
tags: docker, containers, skopeo, OCI, kubernetes
published: true
comments: true
---
This is the first part of a series of posts about containers' images. In this first part we're going to focus on `skopeo`.
Back in March, I published a [post](http://www.projectatomic.io/blog/2016/03/skopeo-inspect-remote-images/) about [skopeo](https://github.com/projectatomic/skopeo), a new tiny binary to help people interact with Docker registries. Its job has been limited to _inspect_ (_skopeo_ is greek for _looking for_, _observe_) images on remote registries as opposed to `docker inspect`, which is working for locally pulled images.
READMORE
## The Tool
Since then, we've been adding more features to `skopeo`, such as downloading image layers (via `skopeo layers`), and eventually we came up with a nice abstraction to the problem of _downloading_, _inspecting_, and _uploading_ images (without even the need to have Docker installed on the system). We called this new abstraction `copy` and here is a straightforward example about how to use it:
```sh
# skopeo copy <source> <destination>
$ id -u
1000
# let's say we want to download the Fedora 24 docker image from the Docker Hub and store it on a local directory
$ mkdir fedora-24
$ skopeo copy docker://fedora:24 dir:fedora-24
$ tree fedora-24
fedora-24
├── 7c91a140e7a1025c3bc3aace4c80c0d9933ac4ee24b8630a6b0b5d8b9ce6b9d4.tar
├── f9873d530588316311ac1d3d15e95487b947f5d8b560e72bdd6eb73a7831b2c4.tar
└── manifest.json
0 directories, 3 files
```
You can see from the output above that `skopeo copy` successfully downloaded the Fedora 24 image—as in, it downloaded all its layers plus the image manifest.
You can also notice the whole operation has been done with an unprivileged user—while Docker needs you to be `root` to even do a `docker pull`.
What can you do with that `fedora-24` directory now? There comes the fun. A nice new addition to the [atomic](https://github.com/projectatomic/atomic) tool has been the so-called _system containers_—they are containers meant to be working before the Docker daemon comes up and they're powered by the community project [runc](https://github.com/opencontainers/runc) which is part of the [Open Container Initiative](https://www.opencontainers.org/). Basically, those containers are set up with these steps:
1. Download the image layers and manifest with `skopeo`
2. Setup a new [ostree](https://wiki.gnome.org/action/show/Projects/OSTree?action=show&redirect=OSTree) repository which will be the root filesystem of our system container
3. Import downloaded layers in the order they come in the image manifest
4. Create a systemd unit file to run `runc` with said filesystem
5. Spawn the service
6. Enjoy
If the above sounds rather complex, the `atomic` tool already provides a `--system` flag which can be used to create a system container:
```sh
$ sudo atomic install --system --name system-container gscrivano/spc-helloworld
Missing layer b037963d9b4419ffe09694c450bd33a06d24945416109aeb2937c7a8595252d9
Missing layer a1b129b466881845cdf628321bf7ed597b3d0cad0b8dd01564f78a4417c750fe
Missing layer a8a1c0600345270e055477e8f282d1318f0cef0debaed032cd1ba1e20eb2a35e
Missing layer 236608c7b546e2f4e7223526c74fc71470ba06d46ec82aeb402e704bfdee02a2
Extracting to /var/lib/containers/atomic/spc.0
systemctl enable spc
Created symlink from /etc/systemd/system/multi-user.target.wants/spc.service to /etc/systemd/system/spc.service.
systemctl start spc
# verify the service is running smoothly
$ sudo systemctl status spc
● spc.service - Hello World System Container
Loaded: loaded (/etc/systemd/system/spc.service; enabled; vendor preset: disabled)
Active: active (running) since Fri 2016-07-22 09:27:47 CEST; 5s ago
Main PID: 10405 (runc)
Tasks: 10 (limit: 512)
CGroup: /system.slice/spc.service
├─10405 /bin/runc start spc
└─spc
├─10416 /bin/sh /usr/bin/run.sh
└─10435 nc -k -l 8081 --sh-exec /usr/bin/greet.sh
Jul 22 09:27:47 localhost.localdomain systemd[1]: Started Hello World System Container.
# we know our system container is listening on port 8081 so let's test it out!
$ nc localhost 8081
HTTP/1.1 200 OK
Connection: Close
Hi World
```
The new `skopeo copy` command isn't just limited to download to local directories. Instead, it can do almost all sort of download/upload between:
- docker registries -> local diretories
- docker registries -> docker registries (`skopeo copy docker://myimage docker://anotherrepo/myimage`)
- docker registries -> [Atomic registry](http://www.projectatomic.io/registry/) (`atomic:` prefix)
- docker registries -> [OCI image-layout](https://github.com/opencontainers/image-spec/blob/master/image-layout.md) directories (`oci:` prefix)
- and viceversa in any combination!
Possibilities seems endless, being able to pull as an unprivileged user also open the doors to work with unprivileged _sanboxes_ like [Flatpak](http://flatpak.org/), [bubblewrap](https://github.com/projectatomic/bubblewrap).
As part of this unprileged capability, we're working on [a new feature in the Atomic tool](https://github.com/projectatomic/atomic/pull/483), which will be able to pull images to the calling user home directory and later run any containers from those images (by also remapping files ownership to the one of the calling user).
Supporting the [Open Container Initiative](https://www.opencontainers.org/) by early implementing the [image specification](https://github.com/opencontainers/image-spec) had also great advantages as we eventually helped the specification itself where things weren't totally clear and defined. We're continuosly adding wider support as the specification moves along also in areas like images signing and layers federation.
The next post will take care of explaining how we extracted some core components from `skopeo` and moved them to a set of reusable libraries.
<file_sep>/source/blog/2015-09-28-creating-custom-ostree-composes-for-atomic-testing.html.md
---
title: Creating Custom ostree Composes for Atomic Testing
author: miabbott
date: 2015-09-28 09:00:28 UTC
tags: ostree, rpm-ostree, testing, Fedora
published: true
comments: true
---
I recently was tasked with testing a change in the upstream `ostree` code on an Atomic Host.
Well, since Atomic hosts use `ostree` as their distribution model, that means I couldn't just get an RPM and install it that way. (I could have just copied over the compiled binary, but where is the fun in that?)
My task list was as follows:
1. build `ostree` from source
2. package `ostree` into an RPM
3. create an custom `ostree` compose
4. rebase an existing Atomic host to the custom compose
As someone who hadn't really accomplished any of these tasks before, I had to reach out for some help on multiple occasions, but I got through it all and hopefully this guide will help you along the way.
READMORE
## Practice ostree compose (the verbose version)
Before I get into the some of the details of doing a custom `ostree` compose, I found it was helpful to do a vanilla `ostree` compose to learn some of the mechanics.
I used <NAME>'s [post on the Red Hat Developer Blog](http://developerblog.redhat.com/2015/01/08/creating-custom-atomic-trees-images-and-installers-part-1/) as a guide for doing my first compose. It was critical to my success in this task! I would recommend reviewing that post for more details about how this works.
For this example, I booted up the latest [Fedora 22 Cloud image](https://getfedora.org/en/cloud/download/) in a VM on my workstation. (Additionally, Fedora 22 Server or Workstation should work.)
The first step was to install the necessary tools, which are `git` and `rpm-ostree-toolbox`
# dnf install git rpm-ostree-toolbox
With the tools installed, we are going to do a `git clone` of the [fedora-atomic git repo](https://git.fedorahosted.org/cgit/fedora-atomic.git) which contains the necessary input files for creating a Fedora Atomic `ostree` compose. (Additionally, I first made a 'working' directory to perform the compose in.)
# mkdir /home/working
# cd /home/working
# git clone https://git.fedorahosted.org/cgit/fedora-atomic.git
This cloned repo includes a number of branches, including **f22**, which contains the files necessary for doing a Fedora 22 Atomic compose. Since I had the best luck with this branch, we're going to use this for the example.
# cd fedora-atomic
# git checkout f22
With the right branch selected we can do a compose right away with the `rpm-ostree-toolbox` command. I'll dig into some of the options right after this.
# cd /home/working
# rpm-ostree-toolbox treecompose -c fedora-atomic/config.ini --ostreerepo /srv/rpm-ostree/fedora-atomic/22/
This command is going to generate a lot of output, so you can sit back and watch all the magic happens while we discuss the various options passed to the `rpm-ostree-toolbox` command.
The `treecompose` sub-command is pretty self-explanatory; it tells `rpm-ostree-toolbox` that we want to do a new `ostree` compose.
The `-c fedora-atomic/config.ini` option tells `rpm-ostree-toolbox` to use the config file specified in the fedora-atomic repo (also kind of self-explanatory). I'm not going to get into the details of the config file at the moment; the blog post linked above has some additional details about the config file.
The `--ostreerepo /srv/rpm-ostree/fedora-atomic/22/` option instructs `rpm-ostree-toolbox` where the resulting `ostree` compose will land on the disk. You don't have to create the directory structure beforehand; the toolbox will create it as part of its job.
If everything was successful, the last few lines of output that `rpm-ostree-toolbox` will produce, looks like this:
<pre><code>...
Moving /boot
Using boot location: both
Copying toplevel compat symlinks
Adding tmpfiles-ostree-integration.conf
Ignored user missing from new passwd file: root
Ignored user missing from new passwd file: root
Committing '/var/tmp/rpm-ostree.HI9E5X/rootfs.tmp' ...
Labeling with SELinux policy 'targeted'
fedora-atomic/f22/x86_64/docker-host => edbe79d713059e4ce5c73346112ef5a33beb54683ddf41b8a6afc81c1dc28083
Complete
fedora-atomic/f22/x86_64/docker-host => edbe79d713059e4ce5c73346112ef5a33beb54683ddf41b8a6afc81c1dc28083
</code></pre>
With our freshly composed `ostree`, let's see if we can actually use it with an Atomic host.
First, we'll make the new `ostree` compose available on the network with the built-in `trivial-httpd` server that comes with the `ostree` command. We just point it to the location of the `ostree` that was just composed (`/srv/rpm-ostree/fedora-atomic/22/`)
# ostree trivial-httpd -p - /srv/rpm-ostree/fedora-atomic/22/
43620
Note the number that is printed out; this is the port which the `ostree` compose is being served via HTTP. We'll need this number in the next step.
Next, I booted up a [Fedora 22 Atomic host](https://getfedora.org/cloud/download/atomic.html) in a VM and checked the existing `rpm-ostree status`.
<pre><code>f22-atomic-host# rpm-ostree status
TIMESTAMP (UTC) VERSION ID OSNAME REFSPEC
* 2015-05-21 19:01:46 22.17 06a63ecfcf fedora-atomic fedora-atomic:fedora-atomic/f22/x86_64/docker-host
</code></pre>
Then I added a new `ostree` remote that pointed to the trivial-httpd server and verified the remotes configured:
<pre><code>f22-atomic-host# ostree remote add f22-test http://192.168.122.219:43620 --no-gpg-verify
f22-atomic-host# ostree remote list -u
f22-test http://192.168.122.219:43620
fedora-atomic http://dl.fedoraproject.org/pub/fedora/linux/atomic/22/
</code></pre>
Then we can use `rpm-ostree rebase` to pull down the compose to the Atomic host
<pre><code>
f22-atomic-host# rpm-ostree rebase f22-test:fedora-atomic/f22/x86_64/docker-host
37 metadata, 38 content objects fetched; 86458 KiB transferred in 4 secondsCopying /etc changes: 25 modified, 0 removed, 42 added
Transaction complete; bootconfig swap: yes deployment count change: 1
Deleting ref 'fedora-atomic:fedora-atomic/f22/x86_64/docker-host'
Removed:
docker-storage-setup-0.0.4-2.fc22.noarch
Added:
iptables-services-1.4.21-14.fc22.x86_64
</code></pre>
Not a lot happened with this rebase, since only two packages had changed. But this was a successful rebase and we can try rebooting into it with `systemctl reboot`. But first, we can check `rpm-ostree status` to see how the new deployment has landed.
<pre><code>f22-atomic-host# rpm-ostree status
TIMESTAMP (UTC) VERSION ID OSNAME REFSPEC
2015-09-23 13:52:23 22 edbe79d713 fedora-atomic f22-test:fedora-atomic/f22/x86_64/docker-host
* 2015-05-21 19:01:46 22.17 06a63ecfcf fedora-atomic fedora-atomic:fedora-atomic/f22/x86_64/docker-host
</code></pre>
After the reboot, we can check `rpm-ostree status` again. But we should also see if that `docker-storage-setup` package was actually removed.
<pre><code>f22-atomic-host# rpm-ostree status
TIMESTAMP (UTC) VERSION ID OSNAME REFSPEC
* 2015-09-23 13:52:23 22 edbe79d713 fedora-atomic f22-test:fedora-atomic/f22/x86_64/docker-host
2015-05-21 19:01:46 22.17 06a63ecfcf fedora-atomic fedora-atomic:fedora-atomic/f22/x86_64/docker-host
f22-atomic-host# rpm -qi docker-storage-setup
package docker-storage-setup is not installed
</code></pre>
There! We did an `ostree` compose and had an Atomic host rebase to it successfully!
## Practice custom ostree compose
With the vanilla compose under out belt, let's try to add some packages to our compose. The mechanics are the same that is covered in the blog post mentioned earlier, so I'm going to keep these steps relatively short.
For the custom `ostree` compose, we are going to add `emacs` and `vim`. This is done by creating a custom JSON file in the fedora-atomic git checkout on the Fedora system where we did the original compose.
<pre><code># cat /home/working/fedora-atomic/fedora-atomic-editors.json
{
"include": "fedora-atomic-docker-host.json",
"packages": ["emacs", "vim"]
}
</code></pre>
Then we create a new profile in the `fedora-atomic/config.ini` file. The profile is indicated by the new **[editors]** section in the file:
<pre><code># tail /home/working/fedora-atomic/config.ini
ref = %(os_name)s/%(release)s/%(arch)s/%(tree_name)s
yum_baseurl = https://dl.fedoraproject.org/pub/fedora/linux/releases/22/Everything/%(arch)s/os/
# lorax_additional_repos = http://127.0.0.1/fedora-atomic/local-overrides
lorax_include_packages = fedora-productimg-atomic
docker_os_name = fedora
[editors]
tree_name = editors
ref = %(os_name)s/%(release)s/%(arch)s/%(tree_name)s
tree_file = %(os_name)s-editors.json
</code></pre>
Now we can do a new compose using nearly the same `rpm-ostree-toolbox` command as before. The only change is we supply the `-p editors` argument to the command, which instructs the toolbox to use the new **editors** profile we created.
# cd /home/working/
# rpm-ostree-toolbox treecompose -c fedora-atomic/config.ini --ostreerepo /srv/rpm-ostree/fedora-atomic/22/ -p editors
After that compose has completed, we can do the same steps to serve up the tree on the network and rebase to it on the Atomic host.
# ostree trivial-httpd -p - /srv/rpm-ostree/fedora-atomic/22/
52867
On the Atomic host, we'll add another remote pointing to the new port and then do a rebase. Note that when we do the rebase, we specify the **editors** ref.
<pre><code>f22-atomic-host# ostree remote add f22-editors http://192.168.122.219:52867 --no-gpg-verify
f22-atomic-host# ostree remote list -u
f22-editors http://192.168.122.219:52867
f22-test http://192.168.122.219:43620
fedora-atomic http://dl.fedoraproject.org/pub/fedora/linux/atomic/22/
f22-atomic-host# rpm-ostree rebase f22-editors:fedora-atomic/f22/x86_64/editors
668 metadata, 13543 content objects fetched; 192236 KiB transferred in 19 secondsCopying /etc changes: 25 modified, 0 removed, 43 added
Transaction complete; bootconfig swap: yes deployment count change: 0
Freed objects: 100.5 MB
Deleting ref 'f22-test:fedora-atomic/f22/x86_64/docker-host'
Added:
GConf2-3.2.6-11.fc22.x86_64
ImageMagick-libs-6.8.8.10-9.fc22.x86_64
OpenEXR-libs-2.2.0-1.fc22.x86_64
adwaita-cursor-theme-3.16.2.1-1.fc22.noarch
adwaita-icon-theme-3.16.2.1-1.fc22.noarch
...
vim-common-2:7.4.640-4.fc22.x86_64
vim-enhanced-2:7.4.640-4.fc22.x86_64
vim-filesystem-2:7.4.640-4.fc22.x86_64
xorg-x11-font-utils-1:7.5-28.fc22.x86_64
# rpm-ostree status
TIMESTAMP (UTC) VERSION ID OSNAME REFSPEC
2015-09-23 14:55:56 22 bed6673466 fedora-atomic f22-editors:fedora-atomic/f22/x86_64/editors
* 2015-09-23 13:52:23 22 edbe79d713 fedora-atomic f22-test:fedora-atomic/f22/x86_64/docker-host
</code></pre>
You can see that a number of packages were added in support of `emacs` and `vim`. And when we reboot into the new deployment, we can confirm that `emacs` and `vim` are installed.
<pre><code>f22-atomic-host# rpm-ostree status
TIMESTAMP (UTC) VERSION ID OSNAME REFSPEC
* 2015-09-23 14:55:56 22 bed6673466 fedora-atomic f22-editors:fedora-atomic/f22/x86_64/editors
2015-09-23 13:52:23 22 edbe79d713 fedora-atomic f22-test:fedora-atomic/f22/x86_64/docker-host
f22-atomic-host# rpm -qa | grep emacs
emacs-common-24.5-2.fc22.x86_64
emacs-24.5-2.fc22.x86_64
emacs-filesystem-24.5-2.fc22.noarch
f22-atomic-host# rpm -qa | grep vim
vim-enhanced-7.4.640-4.fc22.x86_64
vim-filesystem-7.4.640-4.fc22.x86_64
vim-minimal-7.4.640-4.fc22.x86_64
vim-common-7.4.640-4.fc22.x86_64
f22-atomic-host# file /usr/bin/vim
/usr/bin/vim: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=ab955a8dd49fcab6dcbc0a08178fe498a33f384e, stripped
f22-atomic-host# file /usr/bin/emacs
/usr/bin/emacs: symbolic link to `/etc/alternatives/emacs'
</code></pre>
Another tree composed and rebased to! Onward to building `ostree` from source!
## Building ostree from source
To start, we are going to need all the tools and dependencies that building `ostree` requires. The easiest way to do this is to use `yum-builddep`. On the Fedora server where we have been doing the composes, install those dependencies.
# yum-builddep ostree
Once those dependencies have been installed, we can clone the [ostree repo](https://github.com/GNOME/ostree.git)
<pre><code># cd /home/working
# git clone https://github.com/GNOME/ostree.git
Cloning into 'ostree'...
remote: Counting objects: 15576, done.
remote: Compressing objects: 100% (29/29), done.
remote: Total 15576 (delta 14), reused 0 (delta 0), pack-reused 15547
Receiving objects: 100% (15576/15576), 7.61 MiB | 1.87 MiB/s, done.
Resolving deltas: 100% (10184/10184), done.
Checking connectivity... done.
</code></pre>
Then we can try building it. The [README.md](https://github.com/GNOME/ostree/blob/master/README.md) in the `ostree` repo has some straightforward instructions on how to do this. I picked up some additional options to be used from [<NAME>](https://github.com/cgwalters) along the way.
First, we use the `autogen.sh` script:
<pre><code># cd /home/working/ostree/
# env NOCONFIGURE=1 ./autogen.sh
Submodule 'bsdiff' (https://github.com/mendsley/bsdiff) registered for path 'bsdiff'
Submodule 'libglnx' (https://git.gnome.org/browse/libglnx) registered for path 'libglnx'
Cloning into 'bsdiff'...
remote: Counting objects: 224, done.
remote: Total 224 (delta 0), reused 0 (delta 0), pack-reused 224
Receiving objects: 100% (224/224), 52.41 KiB | 0 bytes/s, done.
Resolving deltas: 100% (86/86), done.
Checking connectivity... done.
Submodule path 'bsdiff': checked out '1edf9f656850c0c64dae260960fabd8249ea9c60'
Cloning into 'libglnx'...
remote: Counting objects: 204, done.
remote: Compressing objects: 100% (204/204), done.
remote: Total 204 (delta 128), reused 0 (delta 0)
Receiving objects: 100% (204/204), 63.31 KiB | 0 bytes/s, done.
Resolving deltas: 100% (128/128), done.
Checking connectivity... done.
Submodule path 'libglnx': checked out 'e684ef07f03dd563310788c90b3cdb00bac551eb'
autoreconf: Entering directory `.'
autoreconf: configure.ac: not using Gettext
autoreconf: running: aclocal --force -I m4 ${ACLOCAL_FLAGS}
autoreconf: configure.ac: tracing
autoreconf: running: libtoolize --copy --force
libtoolize: putting auxiliary files in AC_CONFIG_AUX_DIR, `build-aux'.
libtoolize: copying file `build-aux/ltmain.sh'
libtoolize: putting macros in AC_CONFIG_MACRO_DIR, `m4'.
libtoolize: copying file `m4/libtool.m4'
libtoolize: copying file `m4/ltoptions.m4'
libtoolize: copying file `m4/ltsugar.m4'
libtoolize: copying file `m4/ltversion.m4'
libtoolize: copying file `m4/lt~obsolete.m4'
autoreconf: running: /usr/bin/autoconf --force
autoreconf: running: /usr/bin/autoheader --force
autoreconf: running: automake --add-missing --copy --force-missing
configure.ac:11: installing 'build-aux/compile'
configure.ac:31: installing 'build-aux/config.guess'
configure.ac:31: installing 'build-aux/config.sub'
configure.ac:7: installing 'build-aux/install-sh'
configure.ac:7: installing 'build-aux/missing'
Makefile.am: installing 'build-aux/depcomp'
parallel-tests: installing 'build-aux/test-driver'
autoreconf: Leaving directory `.'
</code></pre>
Then we use `./configure` with some of those extra options
# ./configure --prefix=/usr --libdir=/usr/lib64 --sysconfdir=/etc
The end result should look something like this:
<pre><code>...
config.status: executing libtool commands
OSTree 2015.8
===============
introspection: yes
libsoup (retrieve remote HTTP repositories): yes
libsoup TLS client certs: yes
SELinux: yes
libarchive (parse tar files directly): yes
static deltas: yes
documentation: no
gjs-based tests: yes
dracut: no
mkinitcpio: no
</code></pre>
Now we can use `make` (I've removed a lot of the output generated by `make`...)
<pre><code># make
make all-recursive
make[1]: Entering directory '/home/working/ostree'
Making all in .
make[2]: Entering directory '/home/working/ostree'
...
GISCAN OSTree-1.0.gir
GICOMP OSTree-1.0.gir
make[2]: Leaving directory '/home/working/ostree'
make[1]: Leaving directory '/home/working/ostree'
</code></pre>
And you should have a functional `ostree` command in the current directory
<pre><code># pwd
/home/working/ostree
# ./ostree --version
ostree 2015.8
+libsoup +gpgme +libarchive +selinux
</code></pre>
Now that we've proved we can build `ostree` from source, let's package it in an RPM so that we can include it in a custom `ostree` compose. Thankfully, the folks working on `ostree` have made it very simple. We just need to make sure we have the `rpm-build` package (and dependencies) installed.
# dnf install rpm-build
To create the RPM, we go into the `ostree/packaging` directory and just run a simple `make` command specifying the **rpm** target. There will be a ton of output generated, probably some warnings too, but if it gets to `exit 0` at the end, it has more than likely been successful.
<pre><code># cd /home/working/ostree/packaging/
# ls
91-ostree.preset Makefile.dist-packaging ostree.spec.in rpmbuild-cwd
# make -f Makefile.dist-packaging rpm
rm -f *.tar.xz
set -x; \
echo "PACKAGE=ostree"; \
TARFILE_TMP=ostree-2015.8.16.g1181833.tar.tmp; \
...
Processing files: ostree-debuginfo-2015.8.16.g1181833-3.fc22.x86_64
Checking for unpackaged file(s): /usr/lib/rpm/check-files /home/working/ostree/packaging/tmp-packaging/.build/ostree-2015.8.16.g1181833-3.fc22.x86_64
Wrote: /home/working/ostree/packaging/tmp-packaging/x86_64/ostree-2015.8.16.g1181833-3.fc22.x86_64.rpm
Wrote: /home/working/ostree/packaging/tmp-packaging/x86_64/ostree-devel-2015.8.16.g1181833-3.fc22.x86_64.rpm
Wrote: /home/working/ostree/packaging/tmp-packaging/x86_64/ostree-grub2-2015.8.16.g1181833-3.fc22.x86_64.rpm
Wrote: /home/working/ostree/packaging/tmp-packaging/x86_64/ostree-debuginfo-2015.8.16.g1181833-3.fc22.x86_64.rpm
Executing(%clean): /bin/sh -e /var/tmp/rpm-tmp.JgCDTd
+ umask 022
+ cd /home/working/ostree/packaging/tmp-packaging
+ cd ostree-2015.8.16.g1181833
+ rm -rf /home/working/ostree/packaging/tmp-packaging/.build/ostree-2015.8.16.g1181833-3.fc22.x86_64
+ exit 0
</code></pre>
We can inspect the results and look for the newly created RPM files:
<pre><code># pwd
/home/working/ostree/packaging/
# ls -l *rpm
-rw-r--r--. 1 root root 319928 Sep 22 20:11 ostree-2015.8.14.ged86160-3.fc22.x86_64.rpm
-rw-r--r--. 1 root root 926916 Sep 22 20:11 ostree-debuginfo-2015.8.14.ged86160-3.fc22.x86_64.rpm
-rw-r--r--. 1 root root 115440 Sep 22 20:11 ostree-devel-2015.8.14.ged86160-3.fc22.x86_64.rpm
-rw-r--r--. 1 root root 7448 Sep 22 20:11 ostree-grub2-2015.8.14.ged86160-3.fc22.x86_64.rpm
</code></pre>
Sure enough, there are our new `ostree` RPM files! Now we can use them in another custom `ostree` compose.
## Creating custom ostree composes with local repos
To include these new `ostree` RPMs in a custom compose, we have to create a local `yum` repo first. This is easily accomplished with the `createrepo` command.
# dnf install createrepo
With the `createrepo` tool installed, we're going to copy over the RPMs into a directory (can be named anything you like) that will be used as our local `yum` repo. And then use `createrepo` to make it a local repo.
<pre><code># mkdir -p /srv/local-repo
# cp /home/working/ostree/packaging/*rpm /srv/local-repo/
# createrepo /srv/local-repo/
Spawning worker 0 with 4 pkgs
Workers Finished
Saving Primary metadata
Saving file lists metadata
Saving other metadata
Generating sqlite DBs
Sqlite DBs complete
</code></pre>
Now we are going create a custom repo file in the `fedora-atomic` directory we were using before.
<pre><code># cd /home/working/fedora-atomic/
# cat local-testing.repo
[local-testing]
name=ostree local-testing
baseurl=file:///srv/local-repo/
enabled=0
gpgcheck=0
metadata_expire=1d
</code></pre>
With the repo file in place, we can create another custom JSON file that includes our local repo and `ostree` package we want to include in the `ostree` compose
<pre><code># cat fedora-atomic-ostree-testing.json
{
"include": "fedora-atomic-docker-host.json",
"repos": ["local-testing"],
"packages" : ["ostree"]
}
</code></pre>
And include a profile in the `config.ini` file for our special `ostree` package
<pre><code># cat config.ini
...
[ostree-testing]
tree_name = ostree-testing
ref = %(os_name)s/%(release)s/%(arch)s/%(tree_name)s
tree_file = %(os_name)s-ostree-testing.json
</code></pre>
Finally, we use `rpm-ostree-toolbox` as before to create our compose, specifying the **ostree-testing** profile
# cd /home/working
# rpm-ostree-toolbox treecompose -c fedora-atomic/config.ini --ostreerepo /srv/rpm-ostree/fedora-atomic/22/ -p ostree-testing
It is useful during this step to inspect the file list that is generated during the compose to make sure the right version of the package is included in the compose:
---> Package ostree.x86_64 0:2015.8.16.g1181833-3.fc22 will be installed
When the compose is complete, serve it up with `ostree trivial-httpd` and point your Atomic host at the new remote.
<pre><code>...
Moving /boot
Using boot location: both
Copying toplevel compat symlinks
Adding tmpfiles-ostree-integration.conf
Ignored user missing from new passwd file: root
Ignored user missing from new passwd file: root
Committing '/var/tmp/rpm-ostree.SU5O5X/rootfs.tmp' ...
Labeling with SELinux policy 'targeted'
fedora-atomic/f22/x86_64/ostree-testing => d6b2df2246475378bb42399e52886acf145e8a5d6f85c5854cada650de727521
Complete
fedora-atomic/f22/x86_64/ostree-testing => d6b2df2246475378bb42399e52886acf145e8a5d6f85c5854cada650de727521
# ostree trivial-httpd -p - /srv/rpm-ostree/fedora-atomic/22/
38824
</code></pre>
On the Atomic host:
<pre><code>f22-atomic-host# ostree remote add f22-ostree-testing http://192.168.122.219:38824 --no-gpg-verify
f22-atomic-host# rpm-ostree rebase f22-ostree-testing:fedora-atomic/f22/x86_64/ostree-testing
21 metadata, 30 content objects fetched; 86750 KiB transferred in 2 secondsCopying /etc changes: 25 modified, 0 removed, 44 added
Transaction complete; bootconfig swap: yes deployment count change: 0
Freed objects: 100.6 MB
Deleting ref 'f22-editors:fedora-atomic/f22/x86_64/editors'
Changed:
ostree-2015.8.16.g1181833-3.fc22.x86_64
ostree-grub2-2015.8.16.g1181833-3.fc22.x86_64
Removed:
GConf2-3.2.6-11.fc22.x86_64
ImageMagick-libs-6.8.8.10-9.fc22.x86_64
...
rest-0.7.93-1.fc22.x86_64
urw-fonts-3:2.4-20.fc22.noarch
vim-common-2:7.4.640-4.fc22.x86_64
vim-enhanced-2:7.4.640-4.fc22.x86_64
vim-filesystem-2:7.4.640-4.fc22.x86_64
xorg-x11-font-utils-1:7.5-28.fc22.x86_64
f22-atomic-host# rpm-ostree status
TIMESTAMP (UTC) VERSION ID OSNAME REFSPEC
2015-09-23 16:59:39 22 d6b2df2246 fedora-atomic f22-ostree-testing:fedora-atomic/f22/x86_64/ostree-testing
* 2015-09-23 14:55:56 22 bed6673466 fedora-atomic f22-editors:fedora-atomic/f22/x86_64/editors
</code></pre>
When we reboot into the new deployment, we can verify that the custom built `ostree` package was included in the tree.
<pre><code>f22-atomic-host# rpm-ostree status
TIMESTAMP (UTC) VERSIONID OSNAME REFSPEC
* 2015-09-23 16:59:39 22 d6b2df2246 fedora-atomic f22-ostree-testing:fedora-atomic/f22/x86_64/ostree-testing
2015-09-23 14:55:56 22 bed6673466 fedora-atomic f22-editors:fedora-atomic/f22/x86_64/editors
f22-atomic-host# rpm -qa | grep ostree
ostree-2015.8.16.g1181833-3.fc22.x86_64
ostree-grub2-2015.8.16.g1181833-3.fc22.x86_64
rpm-ostree-2015.3-8.fc22.x86_64
f22-atomic-host# ostree --version
ostree 2015.8
+libsoup +gpgme +libarchive +selinux
</code></pre>
Success!
This likely just scratches the surface of what you can do with custom `ostree` composes. But it is the first step.
I want to give a shout out to all those people who helped along the way:
* [<NAME>](https://github.com/baude) - who did all the hard work by documenting the custom tree compose steps on the Red Hat Developer Blog
* [<NAME>](https://github.com/cgwalters) - who is the architect of `ostree` and taught me how to build it from source
* [<NAME>](https://github.com/mbarnes) - who fielded all my questions about packaging `ostree` into an RPM, creating a local repo with it, and doing a custom compose with that repo
Please let me know if you have any questions or feedback. Or drop in at #atomic on Freenode.
<file_sep>/Nulecule/Dockerfile
FROM projectatomic/atomicapp:0.4.2
MAINTAINER Red Hat, Inc. <<EMAIL>>
LABEL io.projectatomic.nulecule.providers="kubernetes,docker" \
io.projectatomic.nulecule.specversion="0.0.2"
ADD /Nulecule /Dockerfile README.md /application-entity/
ADD /artifacts /application-entity/artifacts
<file_sep>/Nulecule/README.md
# atomic-site atomic app
This directory contains the configuration files for running the atomic-site
as an atomic app. The guide to bringing it up is in BUILD.md in the main directory.
What's in this file is some additional information about the atomic app setup
for this application.
## providers
Currently only the Docker provider is defined for atomic-site. PRs for
other providers are more than welcome.
## answers.conf
Here are the current parameters in the answers.conf file, and what they mean:
* **image**: the usual, currently jberkus/atomic-site until projectatomic/atomic-site goes up
* **hostport**: the port to map to on the host, default 4567
* **sourcedir**: the full path to the directory of /source in your clone of
the atomic-site repository
* **datadir**: the full path to the directory of /data in your clone of the
atomic-site repository
## volumes
Both /source and /data are mounted as volumes. This allows you to branch and edit
contents of the atomic site and see the results in the displayed webpage.
## autoremove
Currently, under the Docker provider, atomic-site is set up to autoremove the container
when you exit.
<file_sep>/source/docs/introduction.md
# Introduction to Project Atomic
Project Atomic is an umbrella for many projects related to re-designing the
operating system around principles of "immutable infrastructure",
using the LDK (Linux, Docker, Kubernetes) stack.
Many of the components of Project Atomic are upstream components of
[OpenShift Origin v3]().
The primary building block of Project Atomic is the "Atomic Host", a lightweight
container OS which implements these ideas. Atomic Hosts are immutable, since
each is imaged from an upstream repository, supporting mass deployment.
Applications run in containers. Atomic Host versions based on
CentOS and Fedora are available, and there is also a downstream enterprise
version in Red Hat Enterprise Linux.
Currently, the host comes out of the box with
[Kubernetes](http://kubernetes.io/) installed. A goal however is to
move to a containerized Kubernetes installation, to more easily
support different versions on the same host, such as
[OpenShift v3](https://www.openshift.org/). The Atomic Host also
comes with several Kubernetes utilites such as
[etcd](https://github.com/coreos/etcd) and
[flannel](https://github.com/coreos/flannel). Kubernetes curently uses
[Docker](https://www.docker.io/), an open source
project for creating lightweight, portable, self-sufficient
application containers.
The host system is managed via
[rpm-ostree](http://www.projectatomic.io/docs/os-updates/), an open
source tool for managing bootable, immutable, versioned filesystem
trees from upstream RPM content. This and several other components are wrapped
in the [atomic](https://github.com/projectatomic/atomic) command which provides
a unified entrypoint.
The Project Atomic umbrella also encompasses many other tools which are essential
to immutable, container-based infrastructures, including:
* [Cockpit](http://cockpit-project.org/) gives visibility into your hosts
and your container cluster.
* Many patches and extensions to Docker for better SELinux and Systemd integration.
* [AtomicApp](https://github.com/projectatomic/atomicapp)
and [Nulecule](https://github.com/projectatomic/nulecule)
for composing mulit-container applications.
* [Atomic Registry](http://docs.projectatomic.io/registry/) for registering
your containers.
* [Commissaire](https://github.com/projectatomic/commissaire) to provide a
better API for Kubernetes hosts.
* The [Atomic Developer Bundle](https://github.com/projectatomic/adb-atomic-developer-bundle)
to make development of containerized applications easy.
There are many more tools and projects available within
[Project Atomic](https://github.com/projectatomic). We're building the
next-generation operating system, one component at a time.
## How Can Project Atomic Help Me?
* The traditional enterprise OS model with a single runtime environment controlled by the OS and shared by all applications does not meet the requirements of modern application-centric IT.
* The complexity of the software stack, the amount of different stacks, and the speed of change have overwhelmed the ability of a single monolithic stack to deliver in a consistent way.
* Developer/DevOps-led shops seek control over the runtime underneath their applications, without necessarily owning the entire stack.
* VMs provide a means for separation among applications, but this model adds significant resource and management overhead.
Slimming down the host with the Atomic distribution limits the surface area and patch frequency for administrators. Docker containers offer developers and admins a clear path to delivering consistent and fully tested stacks from development to production. Containers secured with Linux namespaces, cGroups, and SELinux give isolation close to that of a VM, with much greater flexibility and efficiency. And simple, easy-to-use tools like Cockpit provide cross-cluster capabilities to deploy and manage applications.
<file_sep>/source/docs/docker_patches.md
---
title: "Docker Patches"
---
# List of patches to Docker
Project Atomic includes the development and maintenance of a number of patches to the docker daemon and related tools.
All of the patches that we ship are described in the README.md file on the appropriate branch of [our docker repository](https://github.com/projectatomic/docker). If you want to look at the patches for docker-1.12 you would look at [the docker-1.12 branch](https://github.com/projectatomic/docker/tree/docker-1.12).
Each time docker creates a new version, we create a new branch in projectatomic with the version name to match. The current master is working on docker-1.13. You can see the current patchset on [the 1.13 branch](https://github.com/projectatomic/docker/tree/docker-1.13).
Patch types are:
* Red Hat: support compatibility with Red Hat Enterprise Linux and related tools.
* Upstream: Patches which were, or will be, submitted to mainstream docker. Some have been rejected and are being maintained by the Atomic team.
* Backports: Patches which backport fixes from later versions of docker to earlier ones.
## Table of Patches
| Name | Type | PRs | Status |
|--------------------|--------------------|---------------|-----------------------------|
| Add-RHEL-super-secrets-patch | Red Hat | [6075](https://github.com/docker/docker/pull/6075) | Maintaining |
| Add-add-registry-and-block-registry-options-to-docker | Upstream | [11991](https://github.com/docker/docker/pull/11991), [10411](https://github.com/docker/docker/pull/10411) | Rejected, Maintaining |
| Improved-searching-experience | Upstream | | Rejected, Maintaining |
| The-following-syscalls-should-not-be-blocked-by-seccomp | Upstream | [24221](https://github.com/docker/docker/pull/24221), [24510](https://github.com/docker/docker/pull/24510) | Rejected, Maintaining |
| Add-dockerhooks-exec-custom-hooks-for-prestart/poststop-containers | Upstream | [17021](https://github.com/docker/docker/pull/17021) | Pending |
| Return-rpm-version-of-packages-in-docker-version | Red Hat | [14591](https://github.com/docker/docker/pull/14591) | Maintaining |
| rebase-distribution-specific-build | Upstream | [15364](https://github.com/docker/docker/pull/15364) | Pending |
| System-logging-for-docker-daemon-API-calls | Upstream | [14446](https://github.com/docker/docker/pull/14446) | Blocked |
| Audit-logging-support-for-daemon-API-calls | Upstream | [109](https://github.com/rhatdan/docker/pull/109) | Blocked |
| Add-volume-support-to-docker-build | Upstream | See Below | See Below |
Patches which have been accepted by upstream docker are not represented in this chart.
A list of backport patches will be added to this page later.
## Longer Patch Descriptions
Project Atomic is carrying a series of patches that we feel are required for our users or for our support engineering.
### Add-RHEL-super-secrets-patch.patch
This patch allows us to provide subscription management information from the host into containers for both `docker run` and `docker build`. In order to get access to RHEL7 and RHEL6 content inside of a container via yum you need to use a subscription. This patch allows the subscriptions to work inside the container. The docker upstream thought this was too RHEL specific so told us to carry a patch.
* [6075](https://github.com/docker/docker/pull/6075)
Note: This is our oldest patch. Other distributions, like [SuSe](https://github.com/SUSE/docker.mirror/commit/76a4eb2f2e79d1abec07dfe33cd99c3d7a4568c3), are carrying similar patches to allow the hosts subscriptions to be used inside the container to update distribution specific content.
### Add-add-registry-and-block-registry-options-to-docker.patch
Users have been asking for us to provide a mechanism to allow additional registries to be specified in addition to docker.io. We also want to have Red Hat Content available from our Registry by default. This patch allows users to customize the default registries available. We believe this closely aligns with the way yum and apt currently work. This patch also allows users to block images from registries. Some users do not want software
to be accidentally pulled and run on a machine. Some users also have no access to the internet and want to setup private registries to handle their content.
* [11991](https://github.com/docker/docker/pull/11991)
* [10411](https://github.com/docker/docker/pull/10411)
**Status**: Upstream docker does not like this patch set, because they want the **docker** experience to be the same everywhere. If I do a `docker pull fedora`, I always get it from docker.io. We and our customers do not agree, so we continue to carry this patch. We prefer the yum/apt method for specifying registries.
### Improved-searching-experience.patch
Red Hat wants to allow users to search multiple registries as described above. This patch improves the search experience.
**Status**: This patch actually works with the Add-add-registry-and-block-registry-options-to-docke.patch so we need to carry it also.
### The-following-syscalls-should-not-be-blocked-by-seccomp.patch
Capabilities block these syscalls.
`mount`, `umount2`, `unshare`, `reboot` and `name\_to\_handle\_at` are all needed to run `systemd` as PID 1 in a container. These syscalls work fine without administrator privileges, sys_admin disabled. These syscalls also provide features that do not require administrative access. Blocking them by default breaks known work loads for little added security. There is no easy way to discover which syscalls are blocked, so we noticed that users that needed this functionality would simply run their containers without *any* security by using `--privileged`. We feel that adding the capability for `systemd` to run as PID 1 in the container, thereby allowing our users to run with security enabled, far outweighs the negatives for allowing these syscalls with seccomp.
With UserNamespace we want to allow users to potentially setup unshare additional namespaces.
From `man 2 reboot`:
...
Behavior inside PID namespaces
Since Linux 3.4, when reboot() is called from a PID namespace (see
pid_namespaces(7)) other than the initial PID namespace, the effect
of the call is to send a signal to the namespace "init" process.
LINUX_REBOOT_CMD_RESTART and LINUX_REBOOT_CMD_RESTART2 cause a SIGHUP
signal to be sent. LINUX_REBOOT_CMD_POWER_OFF and
LINUX_REBOOT_CMD_HALT cause a SIGINT signal to be sent.
* [21287](https://github.com/docker/docker/pull/21287)
**Status**: docker upstream says that systemd inside of a container is not something they want to support, so they do not want this patch merged. They also claim some of these syscalls open up security risks like allowing unshare(USERNS) to containers. They have pointed out that this syscall is not blocked by SYS_ADMIN capability, which means it could potentially lead to a privilege escalation. Since these syscalls are available to non privileged users on most distributions, it is not seen as a big security issue, and some just break functionality like reboot above. There are lots of other syscalls that are required by admin privs that could be blocked but are not because they would break common workloads. There is little difference between that approach and our patch if systemd is to be considered a common workload. Blocking the unshare syscall can actually weaken security since a container process could tighten its security using this syscall, which is not prevented.
We have a patch we are working with upstream docker to externalize the syscall whitelist file from the docker syscalls, this would allow distributions and admins to define their own list of syscalls to be used by default inside of containers. When this patch gets merged we can drop our patch and just ship distribution defaults.
* [24221](https://github.com/docker/docker/pull/24221)
* [24510](https://github.com/docker/docker/pull/24510)
### Add-dockerhooks-exec-custom-hooks-for-prestart/poststop-containers.patch
With the addition of runc/hooks support we want to add a feature to allow third parties to run helper programs before a docker container gets started and just after the container finishes.
For example we want to add a RegisterMachine hook.
For systems that support systemd/RegisterMachine, this hook would register a machine to the machinectl. machinectl could then list docker containers along with other virtualization environments like kvm, and systemd-nspawn containers. Over time we would want to implement other machinectl features to get docker containers better integrated into the system.
Another example of a hook is a log agent that records when a container starts and stops and then sends a message to a monitoring station.
Dockerhooks reads the `/usr/libexec/oci/hooks.d` directory to search for hooks, if the directory exists docker will execute the executables in this directory via runc/libcontainer is using PreStart and PostStop. It will also send the config.json file as the second parameter.
**Status**: We hope that the upstream docker will expose this feature just like it makes use of these hooks for setting up networking in containers. So far they haven’t given users the option to take advantage of these hooks.
* [17021](https://github.com/docker/docker/pull/17021)
### Return-rpm-version-of-packages-in-docker-version.patch
Red Hat Support wants to know the version of the rpm package that docker is running. This patch allows the distribution to show the rpm version of the client and server using the `docker version` command. The docker upstream was not interested in this patch. This patch only affects the `docker info` command.
* [14591](https://github.com/docker/docker/pull/14591)
**Status**: Since this is distribution specific, docker has rejected the patch. But it is required for our support people to easily identify the client and server RPM of the patches in use, so we plan on carrying it. This patch is also easy to maintain.
### rebase-distribution-specific-build.patch
Current upstream docker tests run totally on Debian. We want to be able to make sure all tests run on platforms and containers we support. This patch allows us to run distribution specific tests. This means that `make test` on RHEL7 will use RHEL7-based images for the test, and `make test` on Fedora will use Fedora-based images for the test. The docker upstream was not crazy about the substitutions done in this patch, and the changes never show up in the version of the docker client/daemon that we ship.
* [15364](https://github.com/docker/docker/pull/15364)
**Status**: Up til now upstream docker does not like the way this works, not sure if there is a good way forward. This patch set is really only for QA and does not change the way that docker works.
### System-logging-for-docker-daemon-API-calls.patch
Red Hat wants to log all access to the docker daemon. This patch records all access to the docker daemon in syslog/journald. Currently docker logs access in its event logs but these logs are not stored permanently and do not record critical information like loginuid to record which user created/started/stopped containers. We will continue to work with the docker upstream to get this patch merged. The docker upstream indicates that they want to wait until the authentication patches get merged.
* [14446](https://github.com/docker/docker/pull/14446)
**Status**: This patch is currently blocked because the docker CLI does not have anyway of authenticating the user doing the activity. All docker currently logs when an activity happens is something like **root** started a container. With this patch, we can actually log that **dwalsh** started a container, but this only works for local domain socket clients. We are working with upstream on an [authentication patch](https://github.com/docker/docker/pull/20883) that can identify the user on the client initiating the action. When/If that patch gets merged we will resubmit and attempt to get this patch merged.
### Audit-logging-support-for-daemon-API-calls.patch
This is a follow on patch to the previous syslog patch, to record all auditable events to the audit log. We want to get `docker daemon` to some level of common criteria. In order to do this administrator activity must be audited.
* [109](https://github.com/rhatdan/docker/pull/109)
**Status**: Similar to the System Logging patch, we need to wait for authentication patch gets merged before working this into docker upstream.
### Add-volume-support-to-docker-build.patch
This patch adds the ability to add bind mounts at build-time. This will be helpful in supporting builds with host files and secrets. The `--volume|-v flag` is added for this purpose. Trying to define a volume (ala docker run) errors out. Each bind mounts' mode will be read-only and it will preserve any SELinux label which was defined via the cli (`:[z,Z]`). Defining a read-write mode (`:rw`) will just print a warning in the build output and the actual mode will be
changed to read-only.
**Status**: Upstream docker has continuously blocked all efforts to support volumes in `docker build`.
These 2 below are open but no progress so far in years:
* [18603](https://github.com/docker/docker/issues/18603)
* [14080](https://github.com/docker/docker/issues/14080)
Closed proposals:
* [3949](https://github.com/docker/docker/issues/3949)
* [3156](https://github.com/docker/docker/issues/3156)
* [14251](https://github.com/docker/docker/issues/14251)
Up until now no satisfactory alternatives have arrived, but there are several projects working to build container images outside of docker, including [Ansible](http://docs.ansible.com/ansible/docker_image_module.html) and potentially [dockerramp](https://github.com/jlhawn/dockramp).
<file_sep>/test-pull.py
#!/usr/bin/env python
"""
This script automates creating a new branch, merging in a numbered pull
request, and starting up the atomic-site in a container so that you can
check the content. Needs to be run from the atomic-site repo homedir.
Expects Nulecule etc. to be already set up.
"""
import github3
import sys
from subprocess import check_call
if len(sys.argv) < 2:
print "usage: test-pull.py #PRNUM"
sys.exit(-1)
else:
prnum = sys.argv[1]
# connect anonymously
gh = github3.GitHub();
rep = gh.repository('projectatomic','atomic-site')
# pull the pull request using the user-supplied number
pr = rep.pull_request(prnum)
prsrc = pr.head
# if it's a local pull request, name is branch ...
if prsrc.repo[0] == u'projectatomic':
prname = prsrc.ref
else:
#otherwise it's user + branch
prname = '{}-{}'.format(prsrc.repo[0],prsrc.ref)
prfrom = 'git://github.com/{}/{}'.format(prsrc.repo[0], prsrc.repo[1], prsrc.ref)
# make sure we're up to date
check_call(["git", "checkout", "master"])
check_call(["git", "pull", "origin", "master"])
# create a branch for the new pr, and pull to it
check_call(["git", "checkout", "-b", prname, "master"])
check_call(["git", "pull", prfrom, prsrc.ref])
# launch the container using Nulecule
check_call(["sudo", "atomicapp", "run", "-a", "answers.conf", "Nulecule/"])
<file_sep>/source/blog/2016-06-20-atomic-registry-systemd.html.md
---
title: Atomic Registry Deployment Update
author: aweiteka
date: 2016-06-20 13:09:00 UTC
tags: atomic registry, systemd
published: true
comments: true
---
Since Atomic Registry was [announced](blog/2016/04/atomic-registry-intro/) as *the* enterprise, 100% open source private docker registry, we have been responding to feedback from the community to make it great. The [Cockpit](http://cockpit-project.org/) team has been working hard to improve the console interface and general user experience. The [OpenShift](https://www.openshift.org/) team has been tirelessly updating the backend to make the registry more stable, usable, and easier to deploy and maintain.
Some of the feedback we received suggested the deployment method was difficult to understand. As part of OpenShift it pulled in a lot of dependencies that were not essential for running the registry. The OpenShift features are terrific for running clustered container workloads but it can be a barrier to some administrators for just running a standalone registry.
READMORE
We've tried to strike a balance between ease of deployment, configuration and maintenance while retaining architectural flexibility to support scale, distributed configuration and container best practices. We're doing this using systemd.
## Why Systemd?
There are several benefits to managing containers with Systemd.
* Mature process management that supports dependencies, logical restart, etc.
* Ease of configuration that matches a traditional sysadmin experience.
* Native system logging to journald.
With this approach we leverage docker packaging to deliver applications that *just work*.
Check out the new [systemd deployment](https://github.com/openshift/origin/tree/master/examples/atomic-registry/systemd) for Atomic Registry. The unit files and setup script have been [packaged as an install container](https://hub.docker.com/r/projectatomic/atomic-registry-install/) so you can quickly pull it down and try it out.
## Open Source. Open Process.
As a Red Hat-sponsored project we see the benefits in practicing **open source** as well as **open process**. We committed to this and worked hard to share our public [Trello organization](https://trello.com/atomicopenshift). The [Atomic Registry roadmap card](https://trello.com/c/0hsX6B4G) aggregates all of the planned and in-progress development work. I've been excited about progress on these specific items:
* **Unauthenticated docker pull**. This is essential for the on-premise use case where users want to tightly control who can push images but allow *anyone* to freely pull images without docker login. [Trello card](https://trello.com/c/Ev8y3pC4)
* **Federated image remotes**. With the pending image layer federation support ISVs will be able to retain control of their layers without distributing base image layers from another vendor. [Trello card](https://trello.com/c/DLaMPAoh)
* **Image Signing**. We're well along in our development of a simple but robust cryptographic image validation prototype. [Trello aggregate card](https://trello.com/c/SApLBoLC)
<file_sep>/source/blog/2016-04-08-atomic-registry-intro.md
---
title: Introducing Atomic Registry
author: aweiteka
date: 2016-04-08 14:00:00 UTC
tags: atomic, registry, docker, openshift, cockpit
published: true
comments: true
categories:
- Blog
---
I am pleased to announce the initial release of [Atomic Registry](http://www.projectatomic.io/registry/).
This is an open source, collaborative effort between [OpenShift Origin](https://www.openshift.org/) and the [Cockpit Project](http://cockpit-project.org/). With these projects we build on a
foundation that has a deep understanding of container technology and a disciplined
approach to software development.
### Highlights
Here are a few features we've pulled into Atomic Registry that we believe any enterprise registry should have:
* Clean, user-focused web interface
* Single sign-on (SSO) user experience with enterprise and cloud identity providers
* Role-based access control (RBAC) to distribute images securely
* Flexible storage options
* Designed for clustering and high availability
Check out this video introducing the user interface console.
<iframe width="960" height="720" src="https://www.youtube.com/embed/YzkjJo7DNMU" frameborder="0" allowfullscreen></iframe>
### Try it out
Atomic Registry is available now. We put together a [quickstart install](http://docs.projectatomic.io/registry/latest/registry_quickstart/administrators/index.html)
to get it up and running quickly on a system. [Documentation](http://docs.projectatomic.io/registry/) covers the architecture,
installation and management of the registry.
### Contribute
This is a 100% open source project. Please give us your feedback, ideas and contributions and help us make it better.
* **IRC**: #atomic or #cockpit channels on Freenode
* **Email**: [<EMAIL>](mailto:<EMAIL>)
* [OpenShift Origin source](https://github.com/openshift/origin/)
* [Cockpit Project source](https://github.com/cockpit-project/cockpit)
* [Documentation source](https://github.com/openshift/openshift-docs)
<file_sep>/source/docs/nulecule.md
---
title: "Nulecule Specification"
---
# Nulecule: A Composite Container-based Application Specification
***/NOO-le-kyul/*** *(n.)* – a made-up word meaning "*[the mother of all atomic particles](http://simpsons.wikia.com/wiki/Made-up_words)*." Sounds like "molecule". But different.
**Package once. Run anywhere.** With pluggable orchestration providers you can package your application to run on OpenShift, Kubernetes, Docker Compose, Helios, Panamax, Docker Machine, etc. and allow the user to choose the target when deployed.
**Compose applications from a catalog.** No need to re-package common services. Create composite applications by referencing other Nulecule-compliant apps. Adding a well-designed, orchestrated database is simply a reference to another container image.
**MSI Installer for containers.** Replace your shell script and deployment instructions with some metadata.
**Change runtime parameters for different environments.** No need to edit files before deployment. Users can choose interactive or unattended deployment. Guide web interface users with parameter metadata to validate user input and provide descriptive help.
## Problem Statement
Currently there is no standard mechanism to define a composite multi-container application or composite service composed of aggregate pre-defined building blocks spanning multiple hosts and clustered deployments. In addition, the associated metadata and artifact management requires separate processes outside the context of the application itself.
## What is Nulecule?
Nulecule defines a pattern and model for packaging complex multi-container applications, referencing all their dependencies, including orchestration metadata in a container image for building, deploying, monitoring, and active management.
The Nulecule specification enables complex applications to be defined, packaged and distributed using standard container technologies. The resulting container includes dependencies while supporting multiple orchestration providers and ability to specify resource requirements. The Nulecule specification also supports aggregation of multiple composite applications. The Nulecule specification is container and orchestration agnostic, enabling the use of any container and orchestration engine.
## Nulecule Specification
The Nulecule Specification is developed as a community effort on github.
The Team uses a <a href="https://www.redhat.com/mailman/listinfo/container-tools">mailing lists</a> hosted by Red Hat.
If you want to contribute to the Nulecule Specification itself, we welcome you at <a href="https://github.com/projectatomic/nulecule/">the spec's repo</a>.
### Highlights
* Application description and context maintained within a single container through extensible metadata
* Composable definition of complex applications through inheritance and composition of containers into a single, standards-based, portable description.
* Simplified dependency management for the most complex applications through a directed graph to reflect relationships.
* Container and orchestration engine agnostic, enabling the use of any container technology and/or orchestration technology
### Releases
* latest, 0.0.2 <a href="/nulecule/spec/0.0.2/index.html">human readable version</a>, <a href="https://github.com/projectatomic/nulecule/tree/master/spec/schema.json">machine readable version</a>
* 0.0.1-alpha <a href="https://github.com/projectatomic/nulecule/releases/tag/v0.0.1-alpha">Archive</a>
## “The Big Picture”
<img src="/images/nulecule-diagram.png" width="100%" alt="Nulecule specification high-level story" />
## Deployment User Experience
Here's an example using [Atomic App](https://github.com/projectatomic/atomicapp), a reference implementation of Nulecule with a Kubernetes provider.
### Option 1: Interactive
Run the image. You will be prompted to provide required values that are missing from the default configuration:
```
$ [sudo] atomic run projectatomic/helloapache
```
### Option 2: Unattended
1. Fetch an Atomic App with a generated answers.conf file:
```
$ [sudo] atomic run projectatomic/helloapache --mode fetch --destination helloapache
...
Your application resides in helloapache
Please use this directory for managing your application
```
2. Mode and modify the answers.conf.sample to your liking:
```
$ mv answers.conf.sample answers.conf
$ vim answers.conf
[general]
provider = kubernetes
[helloapache-app]
image = centos/httpd # optional: choose a different image
hostport = 80 # optional: choose a different port to expose
```
3. Run the application from the current working directory
```
$ [sudo] atomic run projectatomic/helloapache .
...
helloapache
```
## Developer User Experience
See the [Getting Started with Nulecule guide](https://github.com/projectatomic/nulecule/blob/master/docs/getting-started.md).
## Implementations
This is only a specification. Implementations may be written in any language. See [implementation guide](https://github.com/projectatomic/nulecule/blob/master/docs/implementation_guide.md) for more details.
**Reference implementation:** https://github.com/projectatomic/atomicapp
### Developer tooling
Developer tooling is TBD. There is some work planned for [DevAssistant](http://devassistant.org/).
### Contributing
Please review the [contributing guidelines](https://github.com/projectatomic/nulecule/blob/master/CONTRIBUTING.md) before submitting pull requests.
###Communication channels
* IRC: #nulecule (On Freenode)
* Mailing List: [<EMAIL>](https://www.redhat.com/mailman/listinfo/container-tools)
<file_sep>/source/docs/atomicapp.md
---
title: "Atomic App"
---
# What is Atomic App?
[Atomic App](https://github.com/projectatomic/atomicapp) is a reference implementation of the [Nulecule Specification](https://github.com/projectatomic/nulecule). It can be used to bootstrap container applications and to install and run them. Atomic App is designed to be run in a container context.
Examples using this tool may be found in the [Nulecule examples library](https://github.com/projectatomic/nulecule-library).
## Getting Started
Atomic App itself is packaged as a container. End-users typically do not install the software from source. Instead using the `atomicapp` container as the `FROM` line in a Dockerfile and packaging your application on top. For example:
```
FROM projectatomic/atomicapp
MAINTAINER <NAME> <<EMAIL>>
ADD /nulecule /Dockerfile README.md /application-entity/
ADD /artifacts /application-entity /artifacts
```
For more information see the [extensive Atomic App getting started guide](https://github.com/projectatomic/atomicapp/blob/master/docs/start_guide.md) which goes over in detail on how to build your first Atomic App container.
## Running your first Nulecule
### Install Atomic App
Clone the github repository
```
git clone https://github.com/projectatomic/atomicapp
cd atomicapp
```
Install it:
```
sudo make install
```
### Running Atomic App
This will run a helloworld example using the `centos/apache` container image on Kubernetes:
```
sudo atomicapp run projectatomic/helloapache
```
Same with Docker:
```
sudo atomicapp run projectatomic/helloapache --provider=docker
```
### Fetching, modifying and running an Atomic App
Fetch a Nuleculized container, modify the answers file and launch it.
```
atomicapp fetch projectatomic/helloapache --destination helloapache
cd helloapache
cp answers.conf.sample answers.conf # Modify then copy
answers.conf.sample
atomicapp run .
```
### Commands
```
atomicapp {run,fetch,stop,genanswers,init} APP|PATH [--dry-run] [-a answers.conf] [-v] [--namespace foo] [--destination foo]
```
Pulls the application and it's dependencies. If the last argument is an existing path, it looks for `Nulecule` file there instead of pulling the container.
* `--destination DST_PATH` Unpack the application into given directory instead of current directory
* `APP` Name of the image containing the application (f.e. `vpavlin/wp-app`)
* `PATH` Path to a directory with installed (i.e. result of `atomicapp install ...`) app
* `--dry-run` Performs a faux command of Atomic App to simulate a deployment scenario
* `-a answers.conf` Provide an answers.conf file when deploying a container
* `--namespace foo` Use a particular namespace for a specific provider (specifically, k8s and openshift)
## Providers
Atomic App currently supports the following providers:
* Kubernetes
* OpenShift
* Marathon
* Docker
## Contribution
Interested in contributing? We have an awesome [development guide to get you started](https://github.com/projectatomic/atomicapp/blob/master/CONTRIBUTING.md)!
## Communication channels
Interested in **Atomic App**? We'd love to hear from you about your use of Atomic App and work together on improving it.
* IRC: __#nulecule__ on irc.freenode.net
* Mailing List: [<EMAIL>](https://www.redhat.com/mailman/listinfo/container-tools)
* Weekly IRC Nulecule meeting: Monday's @ 0930 EST / 0130 UTC
* Weekly SCRUM Container-Tools meeting: Wednesday's @ 0830 EST / 1230 UTC on [Bluejeans](https://bluejeans.com/381583203/)
<file_sep>/source/docs/docker-image-author-guidance.md
# Guidance for Docker Image Authors
Docker image authors have multiple concerns for their images:
* Is my image easy to use?
* Is my image easy to base another image on?
* Does my image behave in a performant manner?
There are many details which can affect the answers to these questions. We've created this
document to help image authors create images for which the answer is 'yes' across the board.
## Learn About Creating Images with Dockerfiles
There are two ways to create a docker image:
* Create a container and alter its state by running commands in it; create an image with
`docker commit`
* Create a `Dockerfile` and create an image with `docker build`
Most image authors will find that using a `Dockerfile` is a much easier way to repeatably create
an image. A `Dockerfile` is made up of <i>instructions</i>, several of which will be discussed in this guide.
You can find the complete `Dockerfile` instruction reference
[here](http://docs.docker.io/en/latest/reference/builder/#id5).
## Use `MAINTAINER`
The `MAINTAINER` instruction sets the <i>Author</i> field of the image. This is useful for
providing an email contact for your users if they have questions for you.
## Know the Differences Between CMD and ENTRYPOINT
There are many details of how the Dockerfile `CMD` and `ENTRYPOINT` instructions work, and
expressing exactly what you want is key to ensuring users of your image have the right
experience. These two instructions are similar in that they both specify commands that run in an
image, but there's an important difference: `CMD` simply sets a command to run in the image if no
arguments are passed to `docker run`, while `ENTRYPOINT` is meant to make your image behave like a
binary. The rules are essentially:
* If your `Dockerfile` uses only `CMD`, the provided command will be run if no arguments are
passed to `docker run`
* If your `Dockerfile` uses only `ENTRYPOINT`, the arguments passed to `docker run` will always
be passed to the entrypoint; the entrypoint will be run if no arguments are passed to `docker
run`
* If your `Dockerfile` declares both `ENTRYPOINT` and `CMD`, and no arguments are passed to
`docker run`, then the argument(s) to `CMD` will be passed to the declared entrypoint
Be careful with using `ENTRYPOINT`; it will make it more difficult to get a shell inside your
image. While it may not be an issue if your image is designed to be used as a single command,
it can frustrate or confuse users that expect to be able to use the idiom:
# docker run -i -t <your image> /bin/bash
Then entrypoint of an image can be changed by the `--entrypoint` option to `docker run`. If you
choose to set an entrypoint, consider educating your users on how to get a shell in your image
with:
# docker run -i --entrypoint /bin/bash -t <your image>
## Know the Difference Between Array and String Forms of CMD and ENTRYPOINT
There are also two different forms of both `CMD` and `ENTRYPOINT`: array and string forms:
* Passing an array will result in the exact command being run. Example: `CMD [ "ls", "/" ]`
* Passing a string will prefix the command with `/bin/sh -c`. Example: `CMD ls /`
The `-c` option affects how the shell interprets arguments. We recommend
[reading up](http://www.gnu.org/software/bash/manual/html_node/Invoking-Bash.html#Invoking-Bash)
on this option's behavior or using array syntax.
## Always `exec` in Wrapper Scripts
Many images use wrapper scripts to do some setup before starting a process for the software being
run. It is important that if your image uses such a script, that script should use `exec` so that
the script's process is replaced by your software. If you do not use `exec`, then signals sent by
docker will go to your wrapper script instead of your software's process. This is not what you
want - as illustrated by the following example:
Say that you have a wrapper script that starts a process for a server of some kind. You start
your container (using `docker run -i`), which runs the wrapper script, which in turn starts your
process. Now say that you want to kill your container with `CTRL+C`. If your wrapper script used
`exec` to start the server process, docker will send `SIGINT` to the server process, and everything
will work as you expect. If you didn't use `exec` in your wrapper script, docker will send
`SIGINT` to the process for the wrapper script - and your process will keep running like nothing
happened.
## Always EXPOSE Important Ports
The `EXPOSE` instruction makes a port in the container available to the host system and other
containers. While it is possible to specify that a port should be exposed with a `docker run`
invocation, using the `EXPOSE` instruction in a `Dockerfile` makes it easier for both humans and
software to use your image by explicitly declaring the ports your software needs to run:
* Exposed ports will show up under `docker ps` associated with containers created from your image
* Exposed ports will also be present in the metadata for your image returned by `docker inspect`
* Exposed ports will be linked when you link one container to another
For more information about ports and docker, please check out the
[docker documentation](http://docs.docker.io/en/latest/use/port_redirection/).
## Use Volumes Appropriately
The `VOLUME` instruction and the `-v` option to `docker run` tell docker to store files in a directory on the host
instead of in the container's file system. Volumes give you a couple of key benefits:
* Volumes can be shared between containers using `--volumes-from`
* Changes to large files are faster
Volumes obey different rules from normal files in containers:
* Changes made to volumes are not included in the next `docker commit`
* Volumes are a reference counted resource - they persist as long as there are containers using
them
### Sharing Volumes Between Containers
It is possible to share the volumes created by one container with another by using the
`--volumes-from` parameter to docker run. For example, say we make a container named 'ContainerA'
that has a volume:
# docker run -i -v /var/volume1 -name 'ContainerA' -t fedora /bin/bash
We can share the volumes from this container with another container:
# docker run -i --volumes-from ContainerA -t fedora /bin/bash
In `ContainerB`, we will see `/var/volume1` from `ContainerA`. For more information about sharing
volumes, please check out the
[docker documentation](http://docs.docker.io/en/latest/use/working_with_volumes/)
### When to Use Volumes
We recommend that you use volumes in the following use-cases:
1. You want to be able to share a directory between containers
2. You intend on writing large amounts of data to a directory, for example, for a database
## Use USER
By default docker containers run as `root`. A docker container running as root has <b>full control</b>
of the host system. As docker matures, more secure default options may become available. For now,
requiring `root` is dangerous for others and may not be available in all environments. Your image
should use the `USER` instruction to specify a non-root user for containers to run as. If your
software does not create its own user, you can create a user and group in the `Dockerfile` as follows:
RUN groupadd -r swuser -g 433 && \
useradd -u 431 -r -g swuser -d <homedir> -s /sbin/nologin -c "Docker image user" swuser && \
chown -R swuser:swuser <homedir>
### Reusing an Image with a Non-root User
The default user in a `Dockerfile` is the user of the parent image. For example, if your image is
derived from an image that uses a non-root user `swuser`, then `RUN` commands in your
`Dockerfile` will run as `swuser`.
If you need to run as root, you should change the user to root at the beginning of your
`Dockerfile` then change back to the correct user with another `USER` instruction:
USER root
RUN yum install -y <some package>
USER swuser
<file_sep>/source/blog/2015-10-05-setting-up-skydns.html.md
---
title: 'Setting up SkyDNS '
author: dmabe
date: 2015-10-05 08:17:14 UTC
tags: skydns, dns, fedora, centos, etcd, kubernetes
comments: true
published: true
---
Kubernetes exposes DNS for service discovery, but the DNS server itself must be configured after you install Kubernetes. In the future it will be integrated into `kubernetes` as part of the platform (see [PR11599](https://github.com/kubernetes/kubernetes/pull/11599)) but for now you have to setup and run the [SkyDNS](https://github.com/skynetservices/skydns) container yourself.
I have seen some tutorials on how to get `skydns` working, but almost all of them are rather involved. However, if you just want a simple setup on a single node for testing then it is actually rather easy to get `skydns` set up.
READMORE
Setting it up
=============
**NOTE:** This tutorial assumes that you already have a machine with `docker` and `kubernetes` set up and working. This has been tested on Fedora 22 and CentOS 7. It should work on other platforms but YMMV.
So the way `kubernetes`/`skydns` work together is by having two parts:
- kube2sky - listens on the kubernetes api for new services and adds information into etcd.
- skydns - listens for dns requests and responds based on information in etcd.
The easiest way to get `kube2sky` and `skydns` up and running is to just kick off a few `docker` containers. We'll start with `kube2sky` like so:
[root@f22 ~]$ docker run -d --net=host --restart=always \
gcr.io/google_containers/kube2sky:1.11 \
-v=10 -logtostderr=true -domain=kubernetes.local \
-etcd-server="http://127.0.0.1:2379"
**NOTE:** We are re-using the same `etcd` that `kubernetes` is using.
The next step is to start `skydns` to respond to dns queries:
[root@f22 ~]$ docker run -d --net=host --restart=always \
-e ETCD_MACHINES="http://127.0.0.1:2379" \
-e SKYDNS_DOMAIN="kubernetes.local" \
-e SKYDNS_ADDR="0.0.0.0:53" \
-e SKYDNS_NAMESERVERS="8.8.8.8:53,8.8.4.4:53" \
gcr.io/google_containers/skydns:2015-03-11-001
The final step is to modify your `kubelet` configuration to let it know where the dns for the cluster is. You can do this by adding `--cluster_dns` and `--cluster_domain` to `KUBELET_ARGS` in `/etc/kubernetes/kubelet`:
[root@f22 ~]$ grep KUBELET_ARGS /etc/kubernetes/kubelet
KUBELET_ARGS="--cluster_dns=192.168.121.174 --cluster_domain=kubernetes.local"
[root@f22 ~]$ systemctl restart kubelet.service
**NOTE:** I used the ip address of the machine that we are using for this single node cluster.
And finally we can see our two containers running:
[root@f22 ~]$ docker ps --format "table {{.ID}}\t{{.Status}}\t{{.Image}}"
CONTAINER ID STATUS IMAGE
d229442f533c Up About a minute gcr.io/google_containers/skydns:2015-03-11-001
76d51770b240 Up About a minute gcr.io/google_containers/kube2sky:1.11
Testing it out
==============
Now lets see if it works! Taking a page out of the [kubernetes github](https://github.com/kubernetes/kubernetes/tree/master/cluster/addons/dns#1-create-a-simple-pod-to-use-as-a-test-environment) we'll start a busybox container and then do an `nslookup` on the *"kubernetes service"*:
[root@f22 ~]$ cat > /tmp/busybox.yaml <<EOF
apiVersion: v1
kind: Pod
metadata:
name: busybox
namespace: default
spec:
containers:
- image: busybox
command:
- sleep
- "3600"
imagePullPolicy: IfNotPresent
name: busybox
restartPolicy: Always
EOF
[root@f22 ~]$ kubectl create -f /tmp/busybox.yaml
pod "busybox" created
[root@f22 ~]$ kubectl get pods
NAME READY STATUS RESTARTS AGE
busybox 1/1 Running 0 16s
[root@f22 ~]$ kubectl exec busybox -- nslookup kubernetes
Server: 192.168.121.174
Address 1: 192.168.121.174
Name: kubernetes
Address 1: 10.254.0.1
**NOTE:** The *"kubernetes service"* is the one that is shown from the `kubectl get services kubernetes` command.
Now you have a single node `k8s` setup with dns. In the future [PR11599](https://github.com/kubernetes/kubernetes/pull/11599) should satisfy this need but this works for now.
<file_sep>/source/docs/compose-your-own-tree.md
# Compose Your Own Atomic Updates
Project Atomic hosts are built from standard RPM packages which have been composed into filesystem trees using rpm-ostree. This guide provides a method for customizing existing filesystem trees or creating new trees.
## Requirements
* a machine running CentOS or Fedora for composing filesystem trees
* a web server for hosting these tree repositories
## Process
* The `rpm-ostree` program takes as input a manifest file that describes the target system, and commits the result to an OSTree repository.
* This tree is made available via web server, for Atomic hosts to consume.
## Example Dockerfile
The tree compose and hosting functions can both be performed in a container, if you choose. The simple Dockerfile below will suffice, or you may use a similarly-configured Fedora or CentOS machine:
````
FROM fedora:21
# install needed packages
RUN yum install -y rpm-ostree git polipo; \
yum clean all
# create working dir, clone fedora and centos atomic definitions
RUN mkdir -p /home/working; \
cd /home/working; \
git clone https://github.com/CentOS/sig-atomic-buildscripts; \
git clone https://git.fedorahosted.org/git/fedora-atomic.git; \
# create and initialize repo directory
mkdir -p /srv/rpm-ostree/repo && \
cd /srv/rpm-ostree/ && \
ostree --repo=repo init --mode=archive-z2
# expose default SimpleHTTPServer port, set working dir
EXPOSE 8000
WORKDIR /home/working
# start web proxy and SimpleHTTPServer
CMD polipo; pushd /srv/rpm-ostree/repo; python -m SimpleHTTPServer; popd
````
## Build, Run and Enter the Container
````
docker build --rm -t $USER/atomicrepo .
docker run --privileged -d -p 8000:8000 --name atomicrepo $USER/atomicrepo
docker exec -it atomicrepo bash
````
## Compose Your Custom Tree
The Dockerfile above pulls in the definition files for Atomic CentOS and Atomic Fedora, which may be modified to produce a custom tree. The tree manifest syntax is documented [here](https://github.com/projectatomic/rpm-ostree/blob/master/docs/manual/treefile.md).
For example, here's how to produce a version of the Atomic Fedora 21 tree that adds the `fortune` command:
````
cd fedora-atomic
git checkout f21
vi fedora-atomic-docker-host.json
````
Now, in the `"packages":` section of `fedora-atomic-docker-host.json`, and insert a line like this: `"fortune-mod",`.
Currently, the fedora-atomic git repo is missing the yum repository file for Fedora's updates, so we'll want to add this as well. Change the line `"repos": ["fedora-21"],` to `"repos": ["fedora-21", "updates"],` and then save and close the file.
Finally, we need to download that Fedora updates repository file into the `fedora-atomic` directory, and replace occurrences of `$releasever` in the file with `21` (important for when the release version of your composer does not match the release version of the tree you're composing).
````
curl -o fedora-21-updates.repo https://git.fedorahosted.org/cgit/fedora-repos.git/plain/fedora-updates.repo?h=f21
sed -i 's/\$releasever/21/g' fedora-21-updates.repo
````
Next, compose the new tree with the command:
````
rpm-ostree compose tree --proxy=http://127.0.0.1:8123 --repo=/srv/rpm-ostree/repo fedora-atomic-docker-host.json
````
The `--proxy` argument is optional but strongly recommended -- with this option you can avoid continually redownloading the packages every compose. The Dockerfile above provides for [Polipo](http://www.pps.univ-paris-diderot.fr/~jch/software/polipo/) as a proxy.
## Configure Your Atomic Host with the New Repository
To configure an Atomic host to receive updates from your build machine, run a pair of commands like the following to add a new "withfortune" repo definition to your host, and then rebase to that tree:
````
sudo ostree remote add withfortune http://$YOUR_IP:8000/repo --no-gpg-verify
sudo rpm-ostree rebase withfortune:fedora-atomic/f21/x86_64/docker-host
````
Once the rebase operation is complete, run `sudo systemctl reboot` to reboot into your updated tree.
<file_sep>/docker.sh
#!/bin/bash
# install everything in a docker container based on Fedora 22
# permit to have the same env on any system without any issue
# set SElinux context to allow docker to read the source directory
chcon -Rt svirt_sandbox_file_t source/
chcon -Rt svirt_sandbox_file_t data/
# requires docker and being in the right group
docker build -t middleman .
docker run --rm -p 4567:4567 -v "$(pwd)"/source:/tmp/source:ro -v "$(pwd)"/data:/tmp/data middleman
<file_sep>/BUILD.md
# Building the Website
This website is built on [Middleman, a static site generator](https://middlemanapp.com). See instructions below for building it.
## Atomic.app
The recommended way to test the site is with [atomic.app](https://github.com/projectatomic/atomicapp). Currently, version 0.4.2 or later is required.
### First time setup
The first time you run it with Atomic App, you'll need to generate an answers.conf
file with information it needs to launch the container. You shouldn't have to
do this on successive runs unless you delete the answers.conf file for some
reason.
1. Generate answer.conf file:
```
cd /path/to/atomic-site/Nulecule/
atomicapp genanswers .
```
2. Edit answers.conf to match your setup.
For answers.conf, the two things you are required to set is the full path
to the two directories, /source and /data. These should point to the absolute path to `atomic-site/source`
and `atomic-site/data` directories on your computer. For example: `/home/josh/git/atomic-site/source`.
The other fields should not require modification for most people.
### Running the atomic.app
Once you are done with the setup, you should be able to do this to run the container
each time and test the atomic site by running from the repository's root:
```
cd /path/to/atomic-site/
sudo atomicapp run Nulecule/
```
The first time you do this, it will pull the atomic-site image, which may take
a while depending on your internet connection. After that it should be very fast.
Once it's running, you can view the site on [127.0.0.1:4567](http://127.0.0.1:4567).
## Docker build
The second way to build the site is using Docker without atomic.app. From the repo's
root directory, run the docker build:
```
./docker.sh
```
If your local machine has Docker secured, then you'll need to sudo the above command.
Once the container is up and running, the site will be available on [127.0.0.1:4567](http://127.0.0.1:4567).
Note that `docker.sh` builds the site's image every time it runs due to cache issues. This may take a significant amount of time on slower machines.
## Manual Build
If you don't want to use the Atomic App or Docker containers for some reason,
you can follow below instructions to build the site manually.
To get started, you need to have Ruby and Ruby Gems installed, as well
as "bundler".
### Initial setup
On a rpm based distribution:
```
git clone http://github.com/projectatomic/atomic-site.git
cd atomic-site
./setup.sh # This script assumes your user account has sudo rights
```
### Running a local server
1. Start a local Middleman server:
`./run-server.sh`
This will update your locally installed gems and start a Middleman
development server.
2. Next, browse to <http://0.0.0.0:4567>
3. Edit!
Note, when you edit files (pages, layouts, CSS, etc.), the site will
dynamically update in development mode. (There's no need to refresh
the page, unless you get a Ruby error.)
### Updating
When there are new gems in `Gemfile`, just run `bundle` again.
### Customizing your site
The site can be customized by editing `data/site.yml`.
### Adding a Post
To add a post to the community blog (or any blog managed by Middleman) use:
```
bundle exec middleman article TITLE
```
### Build your static site
You can build the static site by running:
`bundle exec middleman build`
## Deploying
### Setting up deployment
FIXME: Right now, please reference [data/site.yml](data/site.yml)
### Actual deployment
After copying your public key to the remote server and configuring your
site in [data/site.yml](data/site.yml), deployment is one command:
```
bundle exec middleman deploy
```
### Add new features (parsers, etc.)
Simply add a new `gem 'some-gem-here'` line in the `Gemfile` and run
`bundle install`
## More info
For more information, please check the excellent
[Middleman documentation](https://middlemanapp.com/basics/install/).
<file_sep>/source/blog/2016-08-18-docker-patches.html.md
---
title: "Project Atomic Docker Patches"
author: dwalsh
date: 2016-08-18 12:00:00 UTC
tags: docker, patches, development
published: true
comments: true
---
Project Atomic's version of the Docker-based container runtime has been carrying a series of patches on the upstream Docker project for a while now. Each time we carry a patch, it adds significant effort as we continue to track upstream, therefore we would prefer to never carry any patches. We always strive to get our patches upstream and do it in the open.
This post, and the accompanying document, will attempt to describe the patches we are currently carrying:
* Explanation on types of patches.
* Description of patches.
* Links to GitHub discussions, and pull requests for upstreaming the patches to docker.
Some people have asserted that [our docker repo](https://github.com/projectatomic/docker) is a fork of the upstream docker project.
## What Does It Mean To Be a Fork?
I have been in open source for a long time, and my definition of a "fork" might be dated. I think of a "fork" as a hostile action taken by one group to get others to use and contribute to their version of an upstream project and ignore the "original" version. For example, LibreOffice forking off of OpenOffice or going way back Xorg forking off of Xfree86.
Nowadays, GitHub has changed the meaning. When a software repository exists on GitHub or a similar platform, everyone who wants to contribute has to hit the "fork" button, and start building their patches. As of this writing, Docker on GitHub has 9,860 forks, including ours. By this definition, however, all packages that distributions ship that include patches are forks. Red Hat ships the Linux Kernel, and I have not heard this referred to as a fork. But it would be considered a "fork" if you're considering any upstream project shipped with patches a fork.
*The Docker upstream even relies on Ubuntu carrying patches for AUFS that were never merged into the upstream kernel.* Since Red Hat-based distributions don’t carry the AUFS patches, we contributed the support for Devicemapper, OverlayFS, and Btrfs backends, which are fully supported in the upstream kernel. This is what enterprise distributions should do: attempt to ship packages configured in a way that they can be supported for a long time.
At the end of the day, we continue to track the changes made to the upstream Docker Project and re-apply our patches to that project. We believe this is an important distinction to allow freedom in software to thrive while continually building stronger communities. It’s very different than a hostile fork that divides communities—we are still working very hard to maintain continuity around unified upstreams.
## How Can I Find Out About Patches for a Particular Version of Docker?
All of the patches we ship are described in the README.md file on the appropriate branch of [our docker repository](https://github.com/projectatomic/docker). If you want to look at the patches for docker-1.12 you would look at [the docker-1.12 branch](https://github.com/projectatomic/docker/tree/docker-1.12).
You can then look on the [docker patches list page](/docs/docker_patches) for information about these patches.
## What Kind of Patches does Project Atomic Include?
Here is a quick overview of the kinds of patches we carry, and then guidance on finding information on specific patches.
### Upstream Fixes
The Docker Project upstream tends to fix issues in the **next** version of Docker. This means if a user finds an issue in docker-1.11 and we provide a fix for this to upstream, the patch gets merged in to the master branch, and it will probably not get back ported to docker-1.11.
Since Docker is releasing at such a rapid rate, they tell users to just install docker-1.12 when it is available. This is fine for people who want to be on the bleeding edge, but in a lot of cases the newer version of Docker comes with new issues along with the fixes.
For example, docker-1.11 split the docker daemon into three parts: docker daemon, containerd, and runc. We did not feel this was stable enough to ship to enterprise customers right when it came out, yet it had multiple fixes for the docker-1.10 version. Many users want to only get new fixes to their existing software and not have to re-certify their apps every two months.
Another issue with supporting stable software with rapidly changing dependencies is that developers on the stable projects must spend time ensuring that their product remains stable every time one of their dependencies is updated. This is an expensive process, dependencies end up being updated only infrequently. This causes us to "cherry-pick" fixes from upstream Docker and to ship these fixes on older versions so that we can get the benefits from the bug fixes without the cost of updating the entire dependency. This is the same approach we take in order to add capabilities to the Linux kernel, a practice that has proven to be very valuable to our users.
### Proposed Patches for Upstream
We carry patches that we know our users require right now, but have not yet been merged into the upstream project. Every patch that we add to the Project Atomic repository also gets proposed to the upstream docker repository.
These sorts of patches remain on the Project Atomic repository briefly while they’re being considered upstream, or forever if the upstream community rejects them. If we don't agree with upstream Docker and feel our users need these patches, we continue to carry them. In some cases we have worked out alternative solutions like building authorization plugins.
For example, users of RHEL images are not supposed to push these image onto public web sites. We wanted a way to prevent users from accidentally pushing RHEL based images to Docker Hub, so we originally created a patch to block the pushing. When authorization plugins were added we then created a plugin to protect users from pushing RHEL content to a public registry like Docker Hub, and no longer had to carry the custom patch.
## Detailed List of Patches
Want to know more about specific patches? You can find the current table and list of patches on our new [docker patches list page](/docs/docker_patches).
<file_sep>/source/blog/2016-06-16-micro-cluster-part-2.html.md
---
title: Building a Sub-Atomic Cluster, Part 2
author: jberkus
date: 2016-06-16 12:43:00 UTC
tags: docker, atomic host, kubernetes, events
published: true
comments: true
---
I'm continuing to kit out the Sub-Atomic Cluster, in the process it's received some upgrades. Thanks to <NAME> of the Minnowboard Project at Intel, I now have a nice power supply instead of the tangle of power strips, and in a couple days I'll also have more SSD storage. You can see here that one node is in a nice blue metal case: that's Muon, which we'll be raffling off at [DockerCon](http://2016.dockercon.com/). Come by booth G14 to see the cluster and for a chance to win the Muon!

While I'm waiting for those, though, I might as well get this set up as a proper Kubernetes cluster. Ansible is my tool for doing this.
READMORE
One way to set up Kubernetes clusters—and the only way which has been specifically configured for Atomic—is [Kubernetes Ansible](https://github.com/kubernetes/contrib/tree/master/ansible). I actually use [Jason Brooks' fork](https://github.com/jasonbrooks/contrib/tree/atomic/ansible), though, because there's a few Atomic-specific fixes in it.
So, next I plugged my laptop into the Sub-Atomic Cluster router. I logged into each host and did three things:
1. Added an SSH key for keyless auth as the "atomic" user
2. Started timesyncd
3. Started Cockpit
Step 2 is one of those things I learned the hard way. Timesyncd isn't started by default on Fedora Atomic Host, and etcd and Kubernetes behave fairly badly if the hosts in the cluster show very different times. In fact, Ansible config will fail. [I have an issue open](https://fedorahosted.org/cloud/ticket/161) and this should get fixed in the future. For now, the way you enable it is:
```
timedatectl set-ntp true
```
[Cockpit](http://cockpit-project.org/) is a terrific GUI for managing your Linux hosts and more. In future posts, we'll talk about using Cockpit to manage Kubernetes; for now, it's useful to launch a cockpit instance to manage each host. For example, I can use it to check which containers are running on one node:

The way to launch these is to call them using the `atomic` command:
```
atomic run cockpit/ws
/usr/bin/docker run -d --privileged --pid=host -v /:/host cockpit/ws /container/atomic-run --local-ssh
0ad2d2b10a1fdd7d1220920e9b0c594901885db85dda706a5404433da6f44e70
```
Now I'm ready to do Ansible. Since there are a bunch of dependencies, I set up a container running Fedora 23. I installed the Ansible 1.9 package because Kubernetes-ansible isn't up to current releases. If you're using a Fedora 24 container, use [this COPR](https://copr.fedorainfracloud.org/coprs/jasonbrooks/ansible1.9.4/).
After installing the other dependencies, I cloned Jason's repository in the container. Next I had to configure it. The first part of that was to create an inventory file:
```
emacs inventory
[masters]
192.168.1.100
[etcd]
192.168.1.100
[nodes]
192.168.1.101
192.168.1.102
192.168.1.103
192.168.1.104
```
As you can see, we've got a master and four kubelets, which are the four nodes. We're setting up single-node etcd, which is not a production setup. That's mostly because I'm waiting on my msata SSDs; I don't want to run etcd on a board which has only a microSD as storage, given the number of writes etcd does. Once I have the new hardware, I'll be able to do an HA setup for Kubernetes.
I also had to make some changes to `group_vars/all.yml`:
```
ansible_ssh_user: atomic
...
# If a password is needed to sudo to root that password must be set here
ansible_sudo_pass: <PASSWORD>
```
That is, since Ansible is going to be logging into hosts using a user with sudo, I need to give it that user and its password. The rest of the defaults work pretty well for a demo cluster, so I'm going to accept them. The main reason one would change anything would be to change the various networks in order to avoid conflicting with your local network, but I've already avoided that with a private router.
Now, I can run Ansible:
```
./setup.sh
PLAY [all] ********************************************************************
TASK: [pre-ansible | Get os_version from /etc/os-release] *********************
ok: [192.168.1.100]
...
PLAY RECAP ********************************************************************
192.168.1.100 : ok=280 changed=11 unreachable=0 failed=0
192.168.1.101 : ok=170 changed=32 unreachable=0 failed=0
192.168.1.102 : ok=170 changed=32 unreachable=0 failed=0
192.168.1.103 : ok=170 changed=32 unreachable=0 failed=0
192.168.1.104 : ok=170 changed=32 unreachable=0 failed=0
```
If your output ends in the above, setup was successful. If not, you'll need to scroll back through the output to see what failed. My first time around, I got a bunch of "expired certificate" failures, which was caused by the timesyncd issue.
What Ansible just set up for me included the following:
* Kubernetes with SSL support
* Docker with Flannel network overlay
* Single-node etcd
Things it did not set up for me include:
* Docker or Atomic registry
* Cockpit Kubernetes
* applications
* high availability
We'll get to those later. For now, let's see how Kubernetes is doing:
```
-bash-4.3# kubectl get nodes
NAME STATUS AGE
electron Ready 57s
muon Ready 23s
neutron Ready 1m
photon Ready 2m
```
Looks good for now. More later, or stop by the booth at [DockerCon](http://2016.dockercon.com/).
<file_sep>/source/docs/atomic-host-networking.md
# Single-host networking: Docker
Docker hosts, by default, give each container an IP address on an unused private range, enabling containers on the same host to communicate with each other, given knowledge of the containers’ assigned IP addresses and on their exposed ports.
Docker’s linked containers feature simplifies communication between containers running on the same host by enabling containers to reference one another through their names, rather than through network values that can change as containers stop and restart.
Docker containers can also communicate with external containers and applications through port forwarding that connects specific container ports to statically or dynamically assigned ports on the host machine.
However, container linking does not span multiple docker hosts, and it is difficult for applications running inside containers to advertise their external IP and port, as that information is not available to them.
While you may run containers on one or more Atomic hosts using only the networking facilities provided by docker itself, multi-host docker deployments will benefit from using the additional stack components that ship with Atomic.
Consult the upstream docker documentation for more information about docker [networking concepts](https://docs.docker.com/articles/networking), and to learn more about [docker links](https://docs.docker.com/userguide/dockerlinks).
# Multi-host networking: Kubernetes & Flannel
Kubernetes addresses these multi-host container communication issues with the concepts of pods and services.
A kubernetes [pod](https://github.com/GoogleCloudPlatform/kubernetes/blob/master/docs/pods.md) corresponds to a colocated group of applications running with a shared context. It may contain one or more applications which are relatively tightly coupled -- in a pre-container world, they would have executed on the same physical or virtual host.
Kubernetes gives every pod its own IP address allocated from an internal network, but since pods can fail and be scheduled to different nodes, these addresses will likely change over time. [Services](https://github.com/GoogleCloudPlatform/kubernetes/blob/master/docs/services.md) provide a single, stable name and address for applications spanning kubernetes pods.
In Kubernetes, every machine in the cluster is assigned a full subnet, a model intended to reduce the complexity of doing port mapping, but which can prove challenging to implement in many network environments. Atomic hosts include [flannel](https://github.com/coreos/flannel/blob/master/README.md), which provides an overlay network that gives a subnet to each machine in a kubernetes cluster.
To learn how to configure flannel and kubernetes in an Atomic host cluster, check out the Project Atomic [Getting Started Guide](http://www.projectatomic.io/docs/gettingstarted/).
<file_sep>/CONTRIBUTING.md
# Contributing
We want your contributions! Our goal is for projectatomic.io to have everything you need in order to run, administer, build applications, or contribute to Atomic projects.
What follows is a guide to contributing content to the Project Atomic website.
## Content We Want
We're looking for anything which relates to the various open source sub-projects of Atomic, or running Linux containers on Fedora, CentOS or RHEL. In general, all content should relate to open source technologies. This includes:
* Fedora, Centos, and RHEL Atomic Host
* Atomic Developer Bundle
* Cockpit
* OStree and RPM-OStree
* Atomic.app and Nulecule
* Fedora Atomic Workstation
* Running Docker and/or RunC on Fedora/CentOS/RHEL
* Linux container technology and news
For all of the above, we are looking for blog posts, documentation, and technical guides. Please see below on how to write and contribute these. The approval process is also outlined below.
## Project Atomic Site Style Guide and Authoring Details
If you are contributing to the Project Atomic site, please look at the following tips and guidelines.
### Style
* Use Markdown* (which flavors are supported by our Middleman install?)
* Use correct indentation levels for code blocks to support correct copy/paste w/o leading spaces (examples)
### Blog posts
* Fork this repo
* Create a git branch for the blog post for clean merges
* Blogs reside in the source/blog directory
* Naming convention is date-title *yyyy-mm-dd-this-is-a-blog*
* Create a pull request to submit for editorial review
#### Template
The header for the post should contain the following information, tags are a free form list. Your post will start immediately following the header. Add a 'READMORE' tag on a separate line to define at a good place to continue reading the full post.
---
title: Getting started with cloud-init
author: mmicene
date: 2014-10-21
layout: post
comments: true
categories:
- Blog
tags:
- cloud-init
- Kubernetes
---
#### Images:
Place in correct directory, use relative links (?)
#### Administrivia:
Add yourself to data/authors.yml
jzb:
name: <NAME>
twitter: jzb
gravatar: 39606c0c942bb877967b5b54b29a9d66
description: Works on Red Hat's Open Source and Standards team. Music junkie, and artist-in-training. Vim lover. Fan of polar bears and cats. Enjoys beer.
### Technical guides
* Fork this repo
* Create a git branch per document for clean merges
* Pull and merge often
* Create a pull request to submit for editorial review
#### Objective:
* Provide overview of the guides objectives
* What will a successful outcome look like
* What will the reader learn from following the guide
* How long should it take (rough order of magnitude, 15 mins, 30 mins, 2 hrs, etc)
#### Prerequisites:
Complete environment description and skills / understanding required before starting, include versions of packages as tested
* Environment: Local host with virt provider, OpenStack, AWS, etc
* Host OS: Version and variant if applicable (Fedora 21 Workstation, CentOS 7, etc)
* Virtualization platform: QEMU, QEMU w/ VMM, VirtualBox, etc
* Packages: any additional packages not explicitly installed during the guide
#### Guide:
The meat of the instruction set, lay out in some logical order, provide expected outputs where needed. Only provide enough detail as needed for the objectives, if more detail can be helpful to learn but not needed, link to an outside resource.
* Provide copy/paste sections, make sure Markdown is correct for leading / trailing whitespace
## Approval and Publishing Process
All content going to projectatomic.io must be vetted and approved by the Maintainers. Please see MAINTAINERS.md for a list of names.
### Blog Post / Technical Guide Approval
1. Author submits PR or article text in MD format.
* if MD file, maintainer adds to his fork and creates PR.
* if a post by maintainer, he submits his own PR.
2. maintainer does a build of the site with the blog post locally.
3. maintainer checks post for formatting, technical accuracy, spelling and grammar.
* if revisions required, Maintainer works with author
* if revisions required but blog post is timely,
Maintainer produces corrected version and submits a new PR.
4. Maintainer marks PR as "Reviewed and ready" and tags @bkproffitt
5. PR Reviewer re-checks grammar and spelling, and checks against PR policy.
6. PR Reviewer merges PR to master, updates date/published, and pushes to
production.
### Minor site updates, Doc updates:
1. Author submits changes as a PR or MD file. MD files are changed
to PRs by Maintainer on his fork.
2. Maintainer does a build of the site with the updates locally.
3. Maintainer checks changes for formatting, technical accuracy, spelling and grammar.
* if revisions required, Maintainer works with author
* if revisions required but changes are timely,
Maintainer produces corrected version and submits a new PR.
4. Maintainer merges to master and pushes new site version to production.
### Minor site updates, Doc updates by Maintainer:
1. Maintainer writes updates
2. Maintainer does a build of the site locally and checks himself for
links and appearance.
3. Maintainer submits a PR to the attention of appropriate parties:
* @bkproffitt for substantial content changes;
* @dwalsh and/or @jbrooks for technical review
4. Once cleared by the above, Maintainer merges to master and pushes
new site version to production.
|
c2d6e03dff1cc4ad1f258069956703178c93ffb7
|
[
"Markdown",
"Python",
"Dockerfile",
"Shell"
] | 21
|
Markdown
|
bexelbie/atomic-site
|
5c90b77c67aa560be944125809512a7e64d1ddbd
|
43cfe82b04cf8ecec383213b171285396a04958c
|
refs/heads/master
|
<repo_name>AJAYK-01/telegram-bot<file_sep>/README.md
## A fun telegram bot
Send images from duckduckgo search to your telegram group anonymously from group members
duckduckgo api credits - https://github.com/deepanprabhu/duckduckgo-images-api
<file_sep>/requirements.txt
requests==2.24.0
beautifulsoup4==4.9.1
pyTelegramBotAPI==3.7.2
<file_sep>/script.py
import telebot,urllib.request,urllib.parse,re,requests
from telebot import apihelper
from duck_api import search
import os
chat_id = os.environ.get('chat_id')
TG_PROXY = os.environ.get('TG_PROXY')
TG_BOT_TOKEN = os.environ.get('TG_BOT_TOKEN')
apihelper.proxy = {'http': TG_PROXY}
bot = telebot.TeleBot(TG_BOT_TOKEN)
@bot.message_handler(func=lambda m: True)
def image(message, index=0):
""" receives message from bot and sends back first image result from duckduckgo """
message = message.text
try:
result_no = message.split(' ')[-1]
index = int(result_no)
message = message[:(-1*len(result_no))]
print(str(index))
except Exception as e:
index = 0
print(str(e))
try:
print("Query : ",message)
bot.send_photo(chat_id, search(message, index=index))
except Exception as err:
print(str(err))
bot.polling(none_stop=True,timeout=123)
<file_sep>/duck_api.py
import requests
import re
import json
def search(keywords, max_results=None, index=0):
""" Searches through duckduckgo and returns image result at index """
url = 'https://duckduckgo.com/';
params = {
'q': keywords
};
""" First make a request to above URL, and parse out the 'vqd'
This is a special token, which should be used in the subsequent request """
res = requests.post(url, data=params)
searchObj = re.search(r'vqd=([\d-]+)\&', res.text, re.M|re.I);
if not searchObj:
# logger.error("Token Parsing Failed !");
return -1;
headers = {
'authority': 'duckduckgo.com',
'accept': 'application/json, text/javascript, */*; q=0.01',
'sec-fetch-dest': 'empty',
'x-requested-with': 'XMLHttpRequest',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'referer': 'https://duckduckgo.com/',
'accept-language': 'en-US,en;q=0.9',
}
params = (
('l', 'us-en'),
('o', 'json'),
('q', keywords),
('vqd', searchObj.group(1)),
('kp', '-2'),
('f', ',,,'),
('p', '-1'),
('v7exp', 'a'),
)
request_url = url + "i.js";
data = ""
while True:
try:
res = requests.get(request_url, headers=headers, params=params);
data = json.loads(res.text);
break;
except ValueError as e:
print(str(e))
# logger.debug("Hitting Url Failure - Sleep and Retry: %s", requestUrl);
continue;
return(data["results"][index]["image"])
|
0d96bdc82bc1db83673337a049893c8c0a3f5c43
|
[
"Markdown",
"Python",
"Text"
] | 4
|
Markdown
|
AJAYK-01/telegram-bot
|
586697d9dd4e2ab34c4e9fac6d7ceee1a84f6282
|
c751a6bae66da08cf473a153d7c6185e38fe8eeb
|
refs/heads/master
|
<repo_name>cancerberoSgx/typedoc-plugin-markdown<file_sep>/src/theme/helpers/ifDisplayIndex.ts
import { ReflectionKind } from 'typedoc/dist/lib/models/reflections/index';
import { getMarkdownEngine } from '../utils';
/**
* Return true if index item should be displayed
* @param item
* @param opts
*/
export function ifDisplayIndex(member: any, opts: any) {
const isGitBook = getMarkdownEngine() === 'gitbook';
const classModule =
member.children && member.children.length
? member.children[0].kind === ReflectionKind.Class
: false;
const enumModule =
member.children && member.children.length
? member.children[0].kind === ReflectionKind.Enum
: false;
const interfaceModule =
member.children && member.children.length
? member.children[0].kind === ReflectionKind.Interface
: false;
if (
(member.displayReadme && isGitBook) ||
(isGitBook && member.kind === ReflectionKind.Class) ||
(isGitBook && member.kind === ReflectionKind.Interface) ||
(isGitBook &&
member.kind === ReflectionKind.ExternalModule &&
!classModule &&
(isGitBook &&
member.kind === ReflectionKind.ExternalModule &&
!enumModule) &&
(isGitBook &&
member.kind === ReflectionKind.ExternalModule &&
!interfaceModule))
) {
return opts.inverse(this);
} else {
return opts.fn(this);
}
}
<file_sep>/test/src/destructuring.ts
/* tslint:disable */
/**
* Destructuring objects.
*/
let { destructObjectA, destructObjectB, destructObjectC } = { destructObjectA: 0, destructObjectB: 'string', destructObjectC: 0 };
/**
* Destructuring arrays.
*/
let [destructArrayA, destructArrayB, destructArrayC = 10] = [0, 'string', 0];
/**
* Array Destructuring with rest
*/
let [destructArrayWithRestA, destructArrayWithRestB, ...destructArrayWithRest] = [1, 2, 3, 4];
/**
* Array Destructuring with ignores
*/
let [destructArrayWithIgnoresA, , ...destructArrayWithIgnoresRest] = [1, 2, 3, 4];
/**
* Destructuring function parameters.
*
* @param a This is a normal param
* @param text This is the text
* @param location This is the location
* @param bold Should it be bold?
*/
function drawText(a, { n = true }, { text = '', location: [x, y] = [0, 0], bold = false }, b) {
return 0;
}
export function dest({ a: b, b: c }: { a: string, b: number }): string {
return 'x';
}
/* tslint:enable */
<file_sep>/test/spec.ts
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
const compiledDirRoot = 'test/out';
const expectedDirRoot = 'test/fixtures';
describe(`Compile 'github' flavoured markdown`, () => {
spawnSync(
'typedoc',
[
'./test/src',
'--out',
'./test/out/github',
'--theme',
'markdown',
'--gitRevision',
'master',
'--media',
'test/src/media/',
'--includes',
'test/src/inc/',
],
{
stdio: 'inherit',
},
);
compareOutputToMocks('github');
});
describe(`Compile 'bitbucket' flavoured markdown`, () => {
spawnSync(
'typedoc',
[
'./test/src',
'--out',
'./test/out/bitbucket',
'--theme',
'markdown',
'--gitRevision',
'master',
'--mdEngine',
'bitbucket',
'--media',
'test/src/media/',
'--includes',
'test/src/inc/',
'--excludePrivate',
'--readme',
'none',
'--mode',
'file',
'--mdSourceRepo',
'https://bitbucket.org/owner/repository_name',
],
{
stdio: 'inherit',
},
);
compareOutputToMocks('bitbucket');
});
describe(`Compile 'gitbook' flavoured markdown`, () => {
spawnSync(
'typedoc',
[
'./test/src',
'--out',
'./test/out/gitbook',
'--theme',
'markdown',
'--gitRevision',
'master',
'--mdEngine',
'gitbook',
'--media',
'test/src/media/',
'--includes',
'test/src/inc/',
],
{
stdio: 'inherit',
},
);
compareOutputToMocks('gitbook');
test('should compile summary', () => {
expectFileToEqualMock('SUMMARY.md', 'gitbook');
});
});
function compareOutputToMocks(flavour) {
test('should compile home', (done) => {
expectFileToEqualMock('README.md', flavour);
done();
});
test('should compile modules', () => {
expectOutputFilesToEqualMocks('modules', flavour);
});
test('should compile classes', () => {
expectOutputFilesToEqualMocks('classes', flavour);
});
test('should compile interfaces', () => {
expectOutputFilesToEqualMocks('interfaces', flavour);
});
test('should compile enums', () => {
expectOutputFilesToEqualMocks('enums', flavour);
});
}
function expectFileToEqualMock(fileName, testNum) {
const md1 = fs.readFileSync(
`${compiledDirRoot}/${testNum}/${fileName}`,
'utf-8',
);
const md2 = fs.readFileSync(
path.join(__dirname, '..', `${expectedDirRoot}/${testNum}/${fileName}`),
'utf-8',
);
// console.log('md1', md1);
// console.log('md2', md2);
expect(md1).toEqual(md2);
}
function expectOutputFilesToEqualMocks(ref, testNum) {
const files = fs.readdirSync(
path.join(__dirname, '..', `${expectedDirRoot}/${testNum}/${ref}`),
);
files.forEach((filename) => {
if (!/^\..*/.test(filename)) {
expectFileToEqualMock(`${ref}/${filename}`, testNum);
}
});
}
<file_sep>/src/theme/helpers/ifDisplayBreadcrumbs.ts
import { getMarkdownEngine } from '../utils';
/**
* Return true if breadcrumbs should be displayed
* @param opts
*/
export function ifDisplayBreadcrumbs(opts: any) {
return getMarkdownEngine() === 'gitbook' ? opts.inverse(this) : opts.fn(this);
}
<file_sep>/src/theme/helpers/compileSources.ts
import { getOptions } from '../props';
import { compilePartial } from '../utils';
/**
* Compiles sources
* @param sources
*/
export function compileSources(sources: any) {
const options = getOptions();
let md = '';
if (!options.mdHideSources) {
md = compilePartial('member.sources.hbs', sources);
}
return md;
}
<file_sep>/src/theme/helpers/getMemberGroupHeadingLevel.ts
import { getMarkdownEngine } from '../utils';
export function getMemberGroupHeadingLevel() {
return getMarkdownEngine() === 'gitbook' ? '#' : '##';
}
<file_sep>/src/theme/helpers/ifHasTypeDeclarations.ts
export function ifHasTypeDeclarations(parameters: any, opts: any) {
const hasTypeDeclaration = parameters.find((param: any) => {
return param.type.declaration && param.type.declaration.children;
});
if (hasTypeDeclaration) {
return opts.fn(this);
} else {
return opts.inverse(this);
}
}
<file_sep>/src/theme/helpers/ifDisplayMainTitle.ts
import { getMarkdownEngine } from '../utils';
/**
* Return true if index item should be displayed
* @param item
* @param opts
*/
export function ifDisplayMainTitle(item: any, opts: any) {
if (getMarkdownEngine() === 'gitbook' || item.model.displayReadme) {
return opts.inverse(this);
} else {
return opts.fn(this);
}
}
<file_sep>/src/theme/helpers/getHeadingLevel.ts
import { getMarkdownEngine } from '../utils';
export function getHeadingLevel(baseLevel: string) {
return getMarkdownEngine() === 'gitbook'
? baseLevel.substring(0, baseLevel.length - 1)
: baseLevel;
}
<file_sep>/src/theme/helpers/getStrippedComment.ts
import { getMarkdownEngine } from '../utils';
/**
* Returns comments block with new lines stripped
* @param comment
*/
export function getStrippedComment(comment: any) {
const lineBreak = getMarkdownEngine() === 'bitbucket' ? ' ' : '<br><br>';
let newComment: string = '';
if (comment) {
if (comment.text) {
newComment += comment.text.replace(/\n\n/g, lineBreak);
}
if (comment.shortText) {
newComment += comment.shortText.replace(/\n\n/g, lineBreak);
}
}
return newComment === '' ? '-' : newComment;
}
<file_sep>/src/theme/helpers/ifGroupContainesVisibleItems.ts
import { ReflectionGroup } from 'typedoc/dist/lib/models/ReflectionGroup';
import { getOptions } from '../props';
/**
* Returns true if group contains visible items
* @param group
* @param opts
*/
export function ifGroupContainesVisibleItems(
group: ReflectionGroup,
opts: any,
) {
const options = getOptions();
if (!options.excludePrivate || !group.allChildrenArePrivate) {
return opts.fn(this);
} else {
return opts.inverse(this);
}
}
<file_sep>/src/theme/helpers/compileGroup.ts
import { ReflectionGroup } from 'typedoc/dist/lib/models/ReflectionGroup';
import { ReflectionKind } from 'typedoc/dist/lib/models/reflections/index';
import { getOptions } from '../props';
import { compilePartial } from '../utils';
/**
* Sets relevant context for member.groups and compiles partial
* @param group
* @param parent
*/
export function compileGroup(
group: ReflectionGroup,
parentKind: ReflectionKind,
) {
const options = getOptions();
let md = '';
if (!options.excludePrivate || !group.allChildrenArePrivate) {
md = compilePartial('members.group.hbs', { ...group });
}
return md;
}
<file_sep>/src/theme/helpers/getAnchor.ts
import { getMarkdownEngine } from '../utils';
/**
* Returns the anchor element
* @param anchor
*/
export function getAnchor(anchor: string) {
return getMarkdownEngine() === 'bitbucket' ? '' : `<a id="${anchor}"></a>`;
}
<file_sep>/src/theme/props.ts
const props = new Map();
export function setProps(options: any, resources: any) {
props.set('options', options);
props.set('resources', resources);
}
export function getOptions() {
return props.get('options');
}
export function getResources() {
return props.get('resources');
}
|
d40e4309d962cc81e4795ce061b3a7387a7c7571
|
[
"TypeScript"
] | 14
|
TypeScript
|
cancerberoSgx/typedoc-plugin-markdown
|
8eff28c3c86ce7d6136286ddc5b00b670c972702
|
657537b79cb815fcf4dc175c1cebcbe841a5f4a9
|
refs/heads/master
|
<repo_name>BugsyFTW/globallib-extensions<file_sep>/ValidationsPT.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GlobalLib.Extensions
{
public static class ValidationsPT
{
/// <summary>
/// Verifica se o NIB de uma conta bancária é válido
/// </summary>
/// <param name="nib">NIB em formato string sem espaços ou traços</param>
/// <returns>Devolve True caso o NIB seja válido</returns>
public static bool IsValidNIB(this string nib)
{
if (nib == null)
return false;
//remove os espaços vazios
nib = nib.Replace(" ", string.Empty);
// remove qq traço
nib = nib.Replace("-", string.Empty);
if (nib.Length != 21)
return false;
//guarda o check digit
string digito = nib.Substring(nib.Length - 2, 2);
//substitui o checkdigit por '00'
nib = nib.Substring(0, 19);
nib += "00";
int peso = 0, res, a;
bool resultado = false;
for (int i = 1; i < nib.Length; i++)
{
a = int.Parse(nib.Substring(i - 1, 1));
a = peso + a;
peso = (a * 10) % 97;
}
res = 98 - peso;
if (digito == string.Format("{0:00}", res))
{
resultado = true;
}
return resultado;
}
/// <summary>
/// Verifica se o IBAN é válido
/// </summary>
/// <param name="iban">IBAN em formato string sem espaços</param>
/// <returns>Devolve True caso o IBAN seja válido</returns>
public static bool IsValidIBAN(this string iban)
{
if (iban == null)
return false;
if (iban.Length < 6)
return false;
//remove os espaços vazios
iban = iban.Replace(" ", string.Empty);
//troca para o fim o código do país e o check digit
iban = iban.Substring(4) + iban.Substring(0, 4);
char[] ibanArray = iban.ToCharArray();
string aux = string.Empty;
decimal finalIban;
foreach (char c in ibanArray)
{
int res = 0;
if (char.IsLetter(c))
{
res = Convert.ToInt32(c) - 55;
}
else if (char.IsNumber(c))
{
res = Convert.ToInt32(c.ToString());
}
aux += res;
}
finalIban = decimal.Parse(aux);
if ((finalIban % 97) == 1)
return true;
else
return false;
}
/// <summary>
/// Verifica se o NIF é válido de acordo com as regras portuguesas
/// </summary>
/// <param name="nif">NIF em formato string sem espaços</param>
/// <param name="isInVATIN">true se contém a indicação ISO2 de portugal</param>
/// <returns>Devolve True caso o NIF seja válido</returns>
public static bool IsValidNIF_PT(this string nif, Boolean isInVATIN = false)
{
if ( (nif == null) || (nif.Trim().Length == 0))
return false;
if(isInVATIN)
{
string iso2 = nif.Substring(0, 2).ToUpperInvariant();
if (iso2 != "PT")
return false;
nif = nif.Replace(iso2, "");
}
int checkDigit;
char firstNumber;
//Verifica se é numerico e tem 9 digitos
if (nif.isNumber() && nif.Length == 9)
{
//primeiro némero do NIF
firstNumber = nif[0];
//Verifica se o nif comeca por (1, 2, 5, 6, 8, 9) que séo os valores posséveis para os NIF's em PT
if (firstNumber.Equals('1') || firstNumber.Equals('2') || firstNumber.Equals('5') || firstNumber.Equals('6') || firstNumber.Equals('8') || firstNumber.Equals('9'))
{
//Calcula o CheckDigit
checkDigit = (Convert.ToInt16(firstNumber.ToString()) * 9);
for (int i = 2; i <= 8; i++)
{
checkDigit += Convert.ToInt16(nif[i - 1].ToString()) * (10 - i);
}
checkDigit = 11 - (checkDigit % 11);
//Se checkDigit for superior a 10 passa a 0
if (checkDigit >= 10)
checkDigit = 0;
//Compara o digito de controle com o éltimo numero do NIF
//Se igual, o NIF é vélido.
if (checkDigit.ToString() == nif[8].ToString())
return true;
}
}
return false;
}
}
}
<file_sep>/VATINValidations.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace GlobalLib.Extensions
{
public static class VATINValidations
{
public static bool IsValidVATIN(this string value, string pais)
{
if (value.IsNullOrEmpty()) return true;
string[] paises = { "AT", "BE", "BG", "CY", "CZ", "DE", "DK", "EE", "EL", "GR", "ES", "FI", "FR"
, "GB", "HU", "IE", "IT", "LT", "LU", "LV", "MT", "NL", "PL", "RO", "SE", "SI", "SK" };
var valueISO2 = value.Substring(0, 2);
if (paises.Contains(valueISO2) && pais == valueISO2)
{
try
{
Regex regex = new Regex(@"^((AT)?U[0-9]{8}|(BE)?0[0-9]{9}|(BG)?[0-9]{9,10}|(CY)?[0-9]{8}L|
(CZ)?[0-9]{8,10}|(DE)?[0-9]{9}|(DK)?[0-9]{8}|(EE)?[0-9]{9}|
(EL|GR)?[0-9]{9}|(ES)?[0-9A-Z][0-9]{7}[0-9A-Z]|(FI)?[0-9]{8}|
(FR)?[0-9A-Z]{2}[0-9]{9}|(GB)?([0-9]{9}([0-9]{3})?|[A-Z]{2}[0-9]{3})|
(HU)?[0-9]{8}|(IE)?[0-9]S[0-9]{5}L|(IT)?[0-9]{11}|
(LT)?([0-9]{9}|[0-9]{12})|(LU)?[0-9]{8}|(LV)?[0-9]{11}|(MT)?[0-9]{8}|
(NL)?[0-9]{9}B[0-9]{2}|(PL)?[0-9]{10}|(PT)?[0-9]{9}|(RO)?[0-9]{2,10}|
(SE)?[0-9]{12}|(SI)?[0-9]{8}|(SK)?[0-9]{10})$");
if (regex.Match(value).Success)
{
return true;
}
return false;
}
catch (ArgumentException)
{
return false;
}
}
return false;
}
}
}
<file_sep>/NullOrEmptyExtensions.cs
using System.Collections;
using System.Collections.Generic;
namespace GlobalLib.Extensions
{
public static class NullOrEmptyExtensions
{
#region isNullOrEmpty
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsNullOrEmpty(this IEnumerable source)
{
if (source != null)
{
foreach (object obj in source)
{
return false;
}
}
return true;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
if (source != null)
{
foreach (T obj in source)
{
return false;
}
}
return true;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsNullOrEmpty<T>(this object[] source)
{
if (source != null)
{
foreach (T obj in source)
{
return false;
}
}
return true;
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="Obj"></param>
/// <param name="ValNull"></param>
/// <returns></returns>
public static object NullOrValue(this object Obj, object ValNull)
{
if (Obj == null)
{
return ValNull;
}
else
{
return Obj;
}
}
/// <summary>
///
/// </summary>
/// <param name="Obj"></param>
/// <param name="ValNull"></param>
/// <returns></returns>
public static string NullOrValue(this string Obj, string ValNull)
{
if (Obj == null)
{
return ValNull;
}
else
{
return Obj;
}
}
}
}
<file_sep>/ExpandoObjectHelpers.cs
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GlobalLib.Extensions
{
public static class ExpandoObjectHelpers
{
/// <summary>
/// https://www.oreilly.com/learning/building-c-objects-dynamically
/// </summary>
/// <param name="expando"></param>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
public static void AddProperty(this ExpandoObject expando, string propertyName, object propertyValue)
{
// ExpandoObject supports IDictionary so we can extend it like this
var expandoDict = expando as IDictionary<string, object>;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
}
}
<file_sep>/DateExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GlobalLib.Extensions
{
public static class DateExtensions
{
public static DateTime GetByTimeZone(this DateTime dateTime, string timeZone = "GMT Standard Time")
{
TimeZoneInfo gmtTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, gmtTimeZone);
}
}
}
|
7068df46579a528f785a3f30f0b42024452ac248
|
[
"C#"
] | 5
|
C#
|
BugsyFTW/globallib-extensions
|
f842d6c194c43cbcfe00bd7c15f38e765acf84ce
|
2cd1ddefb7729b87c7943032b9a8d3983d272464
|
refs/heads/master
|
<repo_name>nakoukal/fpc_convert<file_sep>/include/convert.h
#ifndef CONVERT_H
#define CONVERT_H
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
class Convert
{
public:
Convert(string srcFileName,string dstFileName);
virtual ~Convert();
void read_from_file();
void write_from_vector();
protected:
private:
string _srcFileName,_dstFileName,_pre_wo_short,_pre_mlfb,_pre_9000_mlfb;
vector <vector <string> > operation;
void process(vector<string>& v);
void tokenize(const string& str, vector<string>& tokens, const string& delimiters);
void printV(const vector<string>& v);
};
#endif // CONVERT_H
<file_sep>/main.cpp
#include <convert.h>
using namespace std;
/**
FPC CONVERT function to prepare sap output with operation for fpc import.
parameters souce file destination file
**/
int main(int argc, char* argv[])
{
if(argc > 1)
{
string srcFileName = argv[1];
string dstFileName = argv[2];
Convert c(srcFileName,dstFileName);
c.read_from_file();
c.write_from_vector();
}
else
{
cout << "Nespravny pocet argumentu!" << endl;
}
}
<file_sep>/src/convert.cpp
#include "convert.h"
Convert::Convert(string srcFileName,string dstFileName)
{
this->_pre_wo_short = "";
this->_pre_mlfb = "";
this->_srcFileName = srcFileName;
this->_dstFileName = dstFileName;
}
Convert::~Convert()
{
//destructor
}
void Convert::read_from_file()
{
ifstream in_stream;
string line;
in_stream.open(this->_srcFileName);
/*
read line from file correct and add to vector
*/
while(!in_stream.eof())
{
getline(in_stream, line);
vector<string> v;
this->tokenize(line,v,"\u00A6");
//this->printV(v);
this->process(v);
if(v.size() == 16 && v[3] == "9000" && v[5]!="ZMETKY")
{
this->operation.push_back(v);
//this->printV(v);
}
}
in_stream.close();
}
/*
function to show vecrot items
*/
void Convert::printV(const std::vector<string>& v) {
for(auto& i : v)
std::cout << i << '\n';
}
void Convert::write_from_vector()
{
ofstream of_stream;
string wo_short;
of_stream.open (this->_dstFileName);
for(auto& row : this->operation)
{
int icol = 0;
for(auto& col : row)
{
if(icol==0)
{
of_stream << col;
}else
{
of_stream << ";" << col;
}
icol++;
}
of_stream << endl;
}
of_stream.close();
}
/**
Funkce vytridi radky podle kriterii
*/
void Convert::process(vector<string>& v)
{
//provede se pouze pokud ma soubor 16 sloupcu
if(v.size() == 16)
{
//kontrola zda se jedna o operaci 9000
if(v[3] == "9000" && v[5]!="ZMETKY")
{
if(this->_pre_wo_short != "")
{
v[4] = this->_pre_wo_short; // zame na woid
v[12] = "X"; // nastaveni uzivatel. klice na x po zamene woid
this->_pre_wo_short = ""; //vynulovani promenne po zamene woid
}else
{
//nastaveni klice uzivatelskeho pole standadne "Z" nebo "P" zamenime na "" nebo "X"
if(v[12] == "P" || v[12] == "M")
{
v[12] = "X";
}else
{
v[12] = "";
}
}
//kontrola zda se jedna o prvni operaci 9000 pro jedno mlfb
if(v[0] == _pre_9000_mlfb)
{
//pokud ne zameni se varianta postupu na 1A
v[7] = "1A";
}
//zapamatujeme si posledni mlfb s operaci 9000
_pre_9000_mlfb = v[0];
}
//v pripade ze je na zadku P nebo M (camline) zapamatuj si wo_short_text
if(v[12] == "P" || v[12] == "M")
this->_pre_wo_short = v[4];
//pokud je zmena v mlfb vynuluj pre_wo_short
if(v[0]!=_pre_mlfb)
this->_pre_wo_short = "";
_pre_mlfb = v[0];
}
}
/**
Funkce rozdeli radek do poli podle oddelovace
*/
void Convert::tokenize(const string& s, vector<string>& tokens, const string& delim)
{
for (std::string::size_type start(0); start != s.npos; )
{
std::string::size_type end(s.find_first_of(delim, start));
if(start < end)
tokens.push_back(s.substr(start, end != s.npos? end - start: end));
start = end != s.npos? end + 1: s.npos;
}
}
|
c2c4f4a1493ab2be88bb1a1e76a62127e6db1fb7
|
[
"C++"
] | 3
|
C++
|
nakoukal/fpc_convert
|
8ab2b31efb8c5d1d0d6919226b78ae599f498f35
|
2cd1937e476df40ef359a16511b1ed1329419554
|
refs/heads/master
|
<repo_name>maria-azb/Languages<file_sep>/README.md
# Languages
Проверка запуска автотестов для разных языков интерфейса
<file_sep>/test_items.py
import time
from selenium.common.exceptions import NoSuchElementException
link = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/"
def test_button_add_to_basket_present(browser):
browser.get(link)
time.sleep(10)
try:
browser.find_element_by_css_selector(".btn-add-to-basket")
is_button = True
except (NoSuchElementException):
is_button = False
assert is_button == True, "Button 'add to basket' wasn't found"
|
46e553a989118d0e899abf1c0044cc236cd860be
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
maria-azb/Languages
|
33cd7164f8eedfc606fac83bfe0be6c41bb67426
|
411972e72995367b22d53923661b3a500939ef62
|
refs/heads/master
|
<repo_name>huyue2255/Javascript-Learning<file_sep>/index.js
const obj = {name: 'hello'}
function clone(obj) {
return {...obj};
}
function updateName(obj) {
const obj2 = clone(obj);
obj2.name = 'Nana'
return obj2;
}
const updatedObj = updateName(obj);
console.log(obj,updatedObj)
// HOF
const hof = (fn) => fn(5);
hof(function a(x) {return x});
// Closure
const closure = function() {
let count = 55;
return function getCounter() {
count++
return count;
}
}
const test = closure();
test();
test();
test();
// currying
const mutiply = (a,b) => a*b;
const curriedMutiply = (a) => (b) => a*b;
const curriedMutiplyBy5 = curriedMutiply(7)
curriedMutiplyBy5(4);
// Partial Appplication
const mutiply1 = (a,b,c) => a*b*c;
const particalMutiplyBy5 = mutiply1.bind(null,5);
particalMutiplyBy5(3,10);
// caching
function memorizedAddTo80(n) {
let cache = {};
return function(n) {
if (n in cache) {
return cache[n];
} else {
console.log('long time');
cache[n] = n + 80;
return cache[n];
}
}
}
const memorized = memorizedAddTo80();
console.log('1',memorized(5));
console.log('2',memorized(5));
// Compose (right to left) & Pipe (left to right)
fn1(fn2(fn3(50)));
compose(fn1, fn2, fn3)(50)
pipe(fn3, fn2, fn1)(50)
const compose = (f, g) => (data) => f(g(data));
const pipe = (f,g) => (data) => g(f(data));
const mutiplyBy3 = (num) => num*3;
const makePositive = (num) => Math.abs(num);
const mutiplyBy3AndAbsolute = compose(mutiplyBy3, makePositive);
mutiplyBy3AndAbsolute(-50)
|
b01c6f683cfe8b0fef4026cc3150d2b5266a670c
|
[
"JavaScript"
] | 1
|
JavaScript
|
huyue2255/Javascript-Learning
|
5ffa5d7067292edf8902d6bdf60ec0aa249abb48
|
896a1a4cd249fe15e75c9bfafa36d0913a34df64
|
refs/heads/master
|
<file_sep>package pingcontroller
import (
"encoding/json"
"film-service/utils/response"
"net/http"
)
//Ping --> Check server is up
func Ping(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]bool{"ok": true})
}
//UpgradedPing --> Check server is up
func UpgradedPing(w http.ResponseWriter, r *http.Request) {
response.Success(w, 200, map[string]bool{"ok": true})
}
<file_sep>package main
import (
"context"
"film-service/proxy/logger"
"film-service/routes"
"log"
"net/http"
"os"
"os/signal"
"time"
)
func main() {
r := routes.DefineRoutes()
logger.Init()
srv := &http.Server{
Handler: r,
Addr: ":8000",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
// Run our server in a goroutine so that it doesn't block.
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Println(err)
}
logger.Info("Successfully started the server")
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
defer cancel()
srv.Shutdown(ctx)
log.Println("shutting down")
os.Exit(0)
}
<file_sep>module film-service
go 1.14
require (
github.com/go-delve/delve v1.5.0 // indirect
github.com/go-sql-driver/mysql v1.5.0
github.com/gorilla/mux v1.8.0
github.com/jmoiron/sqlx v1.2.0
github.com/rs/zerolog v1.19.0
)
<file_sep>version: '3'
services:
film-service:
image: golang:1.14
command: ./scripts/dev.sh
volumes:
- .:/go/src/film-service
working_dir: /go/src/film-service
environment:
- GO111MODULE=on
ports:
- "8000:8000"
- "40000:40000"
<file_sep>package filmservice
import (
"film-service/domain"
"film-service/proxy/logger"
"film-service/proxy/mysqlproxy"
"log"
"strconv"
)
//GetFilmsByID --> Fetches list of film by id
func GetFilmsByID(IDs []string) ([]domain.Film, error) {
query := `SELECT
film_id,
title,
description,
release_year,
f.language_id,
l.name
FROM
film f
INNER JOIN language l on f.language_id = l.language_id
WHERE
f.film_id in (:ids)`
params := make([]int, len(IDs))
for i, id := range IDs {
params[i], _ = strconv.Atoi(id)
}
arg := map[string]interface{}{
"ids": params,
}
rows, queryError := mysqlproxy.ExecuteNamedQuery(query, arg)
if queryError != nil {
log.Fatal("Failed to parse struct", queryError.Error())
return nil, queryError
}
var films []domain.Film
for rows.Next() {
var film domain.Film
err := rows.StructScan(&film)
if err != nil {
log.Fatal("Failed to parse struct", err)
}
films = append(films, film)
}
logger.Info("Retrieved films:", len(films))
return films, nil
}
//UpsertFilms --> Creates/Updates list of films
func UpsertFilms(Films []domain.Film) {
}
<file_sep>package domain
// Film struct properties
type Film struct {
FilmID int64 `json:"id" db:"film_id"`
Title string `json:"title" db:"title"`
Description string `json:"description" db:"description"`
ReleaseYear string `json:"releaseYear" db:"release_year"`
LanguageID int64 `json:"languageId" db:"language_id"`
Language string `json:"language" db:"name"`
}
<file_sep>package logger
import (
"fmt"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
//Init --> Sets log level
func Init() {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
Warn("Setting log level:", zerolog.DebugLevel)
}
//Fatal --> Info logs
func Fatal(message string, args ...interface{}) {
toLog := fmt.Sprintf(message, args...)
log.Fatal().Msg(toLog)
}
//Error --> Info logs
func Error(message string, args ...interface{}) {
toLog := fmt.Sprintf(message, args...)
log.Error().Msg(toLog)
}
//Warn --> Info logs
func Warn(message string, args ...interface{}) {
toLog := fmt.Sprintf(message, args...)
log.Warn().Msg(toLog)
}
//Info --> Info logs
func Info(message string, args ...interface{}) {
toLog := fmt.Sprintf(message, args...)
log.Info().Msg(toLog)
}
//Debug --> Info logs
func Debug(message string, args ...interface{}) {
toLog := fmt.Sprintf(message, args...)
log.Debug().Msg(toLog)
}
<file_sep>package routes
import (
filmcontroller "film-service/controllers/film"
pingcontroller "film-service/controllers/ping"
loggingmiddleware "film-service/middleware/logger"
"net/http"
"github.com/gorilla/mux"
)
// DefineRoutes setup the routes for the service
func DefineRoutes() *mux.Router {
r := mux.NewRouter()
r.Use(loggingmiddleware.Middleware)
r.HandleFunc("/ping", pingcontroller.Ping).Methods(http.MethodGet)
r.HandleFunc("/upgraded-ping", pingcontroller.UpgradedPing).Methods(http.MethodGet)
r.HandleFunc("/get-films", filmcontroller.GetFilms).Methods(http.MethodGet)
r.HandleFunc("/create-films", filmcontroller.CreateFilms).Methods(http.MethodPost)
return r
}
<file_sep>package mysqlproxy
import (
"film-service/proxy/logger"
"sync"
"time"
// Register mysql driver
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
var db *sqlx.DB
var once sync.Once
//GetDal --> Returns mysql dal object
func GetDal() (*sqlx.DB, error) {
var err error
once.Do(func() {
db, err = sqlx.Connect("mysql", "root:sakila@tcp(mysql:3306)/sakila")
logger.Info("Successfully created mysql instance")
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
})
if err != nil {
logger.Error("Failed to initialize db")
}
return db, nil
}
// ExecuteNamedQuery --> Returns named query to execute
func ExecuteNamedQuery(query string, arg map[string]interface{}) (*sqlx.Rows, error) {
query, args, _ := sqlx.Named(query, arg)
query, args, _ = sqlx.In(query, args...)
dal, _ := GetDal()
query = dal.Rebind(query)
rows, queryError := dal.Queryx(query, args...)
return rows, queryError
}
<file_sep>package response
import (
"encoding/json"
"fmt"
"net/http"
)
type errorResponse struct {
Message string `json:"message"`
}
// Success --> Returns successfull response
func Success(w http.ResponseWriter, statusCode int, response interface{}) {
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(response)
}
// Error --> Returns error response
func Error(w http.ResponseWriter, statusCode int, err interface{}) {
body, _ := json.Marshal(errorResponse{Message: fmt.Sprint(err)})
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(body)
}
<file_sep>package filmcontroller
import (
"encoding/json"
"film-service/domain"
"film-service/proxy/logger"
filmservice "film-service/service/film"
"film-service/utils"
"film-service/utils/response"
"net/http"
"strings"
)
// CreateFilms --> Create films from the request body
func CreateFilms(res http.ResponseWriter, req *http.Request) {
var body struct {
Films []domain.Film `json:"films"`
}
err := json.NewDecoder(req.Body).Decode(&body)
if err != nil {
response.Error(res, http.StatusBadRequest, map[string]string{"message": "Mandatory params missing"})
return
}
response.Success(res, 200, map[string]bool{"ok": true})
}
// GetFilms --> Fetches list of films from the database
func GetFilms(res http.ResponseWriter, req *http.Request) {
queryParams := utils.ParseQueryParams(req.URL.Query())
logger.Info("Retriving film information for params:", queryParams)
if _, fetchByID := queryParams["id"]; fetchByID {
ids := strings.Split(queryParams["id"], ",")
films, err := filmservice.GetFilmsByID(ids)
if err != nil {
logger.Error("Failed to get films", err.Error())
response.Error(res, 500, err.Error())
}
response.Success(res, 200, films)
return
}
response.Error(res, http.StatusBadRequest, map[string]string{"message": "Mandatory params missing"})
}
<file_sep>package loggingmiddleware
import (
"film-service/proxy/logger"
"net/http"
)
//Middleware --> Logs the request
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Info("HTTP %s %v", r.Method, r.URL)
w.Header().Set("Content-Type", "application/json")
next.ServeHTTP(w, r)
})
}
<file_sep>package utils
import (
"net/url"
)
//ParseQueryParams --> Elegantly parse queryparams to key value pair
func ParseQueryParams(params url.Values) map[string]string {
paramsMap := make(map[string]string)
for key, value := range params {
paramsMap[key] = value[0]
}
if _, hasLimit := paramsMap["limit"]; !hasLimit {
paramsMap["limit"] = "100"
}
if _, hasSkip := paramsMap["skip"]; !hasSkip {
paramsMap["skip"] = "0"
}
return paramsMap
}
<file_sep>#!/bin/bash
go get github.com/go-delve/delve/cmd/dlv
go build -gcflags="all=-N -l" -o $PWD "$PWD/main.go"
echo "Build succeeded!!!!"
dlv --listen=:40000 --headless=true --api-version=2 --accept-multiclient exec "$PWD/main"
# go run -race $PWD
|
c25defd9a7a8b87018b0bfc4b999e2d19235da78
|
[
"Go Module",
"Go",
"YAML",
"Shell"
] | 14
|
Go
|
karthikeyan-raman/film-service
|
0f587d828f963e40bbfa4296d43956faf2505a70
|
e9a4df00e63e20ff6b64ecb82a4a465c8339e096
|
refs/heads/master
|
<repo_name>zoudong0836/JavaRepo<file_sep>/HibernateDemo/src/com/dzou/manyToOneFK/doubleWay/README.md
## 一对多(多对一)双向外键
1. 多方 (多方持有一方的引用)
* @ManyToOne(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
* JoinColumn(name="cid", referencedColumnName="CID")
2. 一方 (一方持有多方的集合)
* OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.LAZY)
* JoinColumn(name="cid")<file_sep>/HibernateDemo/src/com/dzou/manyToManyFK/singleWay/README.md
## 多对多单向外键
* @ManyToMany
* @JoinTable(name="teachers_students", joinColumns={@JoinColumn(name="sid")}, inverseJoinColumns={@JoinColumn(name="tid")})<file_sep>/SpringDemo/src/com/dzou/spring/jdbcTemplates/db.properties
jdbc_driver=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://192.168.51.241:3306/mybatis?useSSL=false&characterEncoding=utf8
jdbc_username=root
jdbc_password=<PASSWORD><file_sep>/SpringMyBatis/src/main/java/com/dzou/utils/GetApplicationContext.java
package com.dzou.utils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class GetApplicationContext {
private static ApplicationContext applicationContext;
private GetApplicationContext() {
}
public static ApplicationContext getInstance() {
if(applicationContext == null) {
synchronized (GetApplicationContext.class) {
if(applicationContext == null) {
applicationContext = new ClassPathXmlApplicationContext("spring/spring-config.xml");
}
}
}
return applicationContext;
}
}
<file_sep>/MyBatisDemo/src/test/java/com/dzou/test1.java
package com.dzou;
import com.dzou.dao.userMapper;
import com.dzou.pojo.user;
import com.dzou.utils.GetSqlSessionFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* 示例: 通过接口操作数据库
*/
public class test1 {
private static SqlSession sqlSession;
private static userMapper mapper;
@BeforeClass
public static void setUp() {
SqlSessionFactory sqlSessionFactory = GetSqlSessionFactory.getInstance();
sqlSession = sqlSessionFactory.openSession();
mapper = sqlSession.getMapper(userMapper.class);
}
@AfterClass
public static void tearDown() {
sqlSession.clearCache();
sqlSession.close();
}
@Test
public void testAddUser() {
user users = new user();
users.setName("dzou");
int result = mapper.insert(users);
sqlSession.commit();
System.out.println("result = " + result);
}
@Test
public void testQueryUser() {
user users = mapper.selectByPrimaryKey(6);
System.out.println(users);
}
}
<file_sep>/SpringDemo/src/com/dzou/spring/jdbcTemplates/JTest.java
package com.dzou.spring.jdbcTemplates;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JTest {
private ApplicationContext ctx;
private JdbcTemplate jdbcTemplate;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
{
ctx = new ClassPathXmlApplicationContext("com/dzou/spring/jdbcTemplates/spring-config-jdbc.xml");
jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
namedParameterJdbcTemplate = (NamedParameterJdbcTemplate) ctx.getBean("namedParameterJdbcTemplate");
}
/**
* 测试数据库连接
*
* @throws SQLException
*/
@Test
public void testDataSource() throws SQLException {
DataSource dataSource = ctx.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
}
/**
* 添加一条记录
*/
@Test
public void testUpdate() {
String sql = "update users set age = ? where id = ?";
jdbcTemplate.update(sql, 22, 1);
}
/**
* 执行批量操作
*/
@Test
public void testBatchUpdate() {
String sql = "INSERT INTO users(name, age) VALUES(?, ?)";
List<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(new Object[]{"AA", 30});
batchArgs.add(new Object[]{"BB", 31});
batchArgs.add(new Object[]{"CC", 32});
jdbcTemplate.batchUpdate(sql, batchArgs);
}
/**
* 从数据库中获取一条记录, 返回一个对象
* 1. RowMapper指定如何去映射结果集的行, 常用的实现类为 BeanPropertyRowMappe
* 2. 使用 SQL 中列的别名完成列名和类的属性名的映射. 例如last_name lastName
* 3. 不支持级联属性. JdbcTemplate 到底是一个 JDBC 的小工具, 而不是 ORM 框架
*/
@Test
public void testQueryForObject() {
String sql = "SELECT id, name, age FROM users where id = ?";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
User user = jdbcTemplate.queryForObject(sql, rowMapper, 1);
System.out.println(user);
}
/**
* 返回一个对象集合
*/
@Test
public void testQueryForObjectList() {
String sql = "SELECT id, name, age FROM users where id > ?";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
List<User> users = jdbcTemplate.query(sql, rowMapper, 1);
System.out.println(users);
}
/**
* 查询单个值
*/
@Test
public void testQueryForSingleValue() {
String sql = "SELECT count(*) FROM users";
long count = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count);
}
/**
* 为参数命名
*/
@Test
public void testNamedParameterJdbcTemplate() {
String sql = "INSERT INTO users(name, age) VALUES(:name, :age)";
Map<String, Object> paramSource = new HashMap<>();
paramSource.put("name", "FF");
paramSource.put("age", 40);
namedParameterJdbcTemplate.update(sql, paramSource);
}
/**
* 通过实例对象更新SQL语句
* 如果SQL语句中的参数名和类的属性不一致时, 需要使用SQL中列的别名完成列名和类的属性名的映射
*/
@Test
public void testNamedParameterJdbcTemplateObject() {
String sql = "INSERT INTO users(name, age) VALUES(:name, :age)";
User user = new User(-1, "GG", 41);
SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(user);
namedParameterJdbcTemplate.update(sql, parameterSource);
}
}
<file_sep>/SpringMyBatis/src/test/java/com/dzou/test1.java
package com.dzou;
import com.dzou.dao.UserMapper;
import com.dzou.pojo.User;
import com.dzou.utils.GetApplicationContext;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
/**
* 示例: 通过接口操作数据库
*/
public class test1 {
private static UserMapper mapper;
@BeforeClass
public static void setUp() {
ApplicationContext applicationContext = GetApplicationContext.getInstance();
mapper = (UserMapper) applicationContext.getBean("userMaper");
}
@Test
public void testAddUser() {
User user = new User();
user.setName("dzou");
mapper.addUser(user);
}
@Test
public void testQueryUser() {
User user = mapper.selectById(8);
System.out.println(user);
}
}
<file_sep>/SpringDemo/src/com/dzou/spring/aspect/annotations/ArithmeticCalculatorAspect.java
package com.dzou.spring.aspect.annotations;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Aspect // 声明为一个切面
@Component // 切面必须是IoC中的Bean
public class ArithmeticCalculatorAspect {
// 定义一个方法, 用于声明切入点表达式 (一般地, 该方法中不再需要添入其它 的代码)
@Pointcut("execution(* com.dzou.spring.aspect.annotations.ArithmeticCalculatorImpl.*(int, int))")
public void declareJoinPointExpression() {
}
// 前置通知, 在方法执行之前执行
@Before("declareJoinPointExpression()")
public void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
}
// 后置通知, 在方法执行之后执行 (无论该方法是否出现异常)
@After("declareJoinPointExpression()")
public void AfterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " ends");
}
// 返回通知, 在方法返回结果之后执行 (可以访问方法的返回结果)
@AfterReturning(value = "declareJoinPointExpression()", returning = "result")
public void afterRunning(JoinPoint joinPoint, Object result) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " ends with result [ " + result + " ]");
}
// 异常通知, 在方法抛出异常之后
@AfterThrowing(value = "declareJoinPointExpression()", throwing = "ex")
public void afterThrowing(JoinPoint joinPoint, Exception ex) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " occurs exception: " + ex);
}
/**
* 环绕通知需携带 ProceedingJoinPoint 类型的参数
* 环绕通知类似于动态代理的全过程: ProceedingJoinPoint 类型的参数可以决定是否执行目标方法
* 环绕通知必须由返回值, 返回值即为目标方法的返回值
*/
@Around("declareJoinPointExpression()")
public Object around(ProceedingJoinPoint pjd) {
Object result = null;
String methodName = pjd.getSignature().getName();
try {
// 前置通知
System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
// 执行目标方法
result = pjd.proceed();
// 返回通知
System.out.println("The method " + methodName + " ends with " + result);
} catch (Throwable e) {
// 异常通知
System.out.println("The method " + methodName + " occurs exception: " + e);
e.printStackTrace();
}
// 后置通知
System.out.println("The method " + methodName + " ends");
return result;
}
}
<file_sep>/HibernateDemo/src/com/dzou/oneToOneFK/UnionKey/README.md
## 一对一双向外键联合主键
* 创建主键类
* 主键类必须实现serializable接口, 重写hashCode()和equals()方法
1) 主键类 @Embeddable
2) 实体类 @EmbeddedId
<file_sep>/HibernateDemo/src/com/dzou/oneToOneFK/doubleWay/README.md
## 一对一单向外加
* @OneToOne(cascade=CascadeType.ALL)
* @JoinColumn(name="pid", unique=true)
## 一对一双向外键
* 主控方的配置同一对一单向外加关联相同
* @OneToOne(mappedBy="card") // 被控方
* 双向关联, 必须设置mappedBy属性; 因为双向关联只能交给一方去控制, 不可能在双方都设置外键保存关联关系, 否则双方都无法保存<file_sep>/HibernateDemo/src/com/dzou/oneToManyFK/singleWay/README.md
## 一对多单向外键
* @OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.LAZY)
* JoinColumn(name="cid")
总结: 多对一时候, 多方设置EAGER, 一方设置LAZY<file_sep>/HibernateDemo/src/com/dzou/manyToOneFK/singleWay/README.md
## 多对一单向外键
* @ManyToOne(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
* JoinColumn(name="cid", referencedColumnName="CID")
|
f0c808036193842e1283e6b1359eef5a35719be2
|
[
"Markdown",
"Java",
"INI"
] | 12
|
Markdown
|
zoudong0836/JavaRepo
|
5e9c9db6b7b2062d66ce9e6e6dcc27c4bfbaa20a
|
91231132bab72e9f79008b6d1894d21644a84522
|
refs/heads/main
|
<file_sep>import styled from 'styled-components'
export const Container = styled.div`
display: flex;
justify-content: center;
flex-direction:column;
height: 100%;
max-width: 1370px;
margin: 0 auto;
width: 100%;
.Money-text{
margin-top:40px;
margin-left:80px;
/* background-color:red; */
line-height:60px;
width:400px;
height:400px;
.moneyh1{
color:#fff;
font-family:'Josefin Sans';
font-weight:bold;
font-size:50px;
}
}
.btns-aplication{
display:flex;
align-items:center;
justify-content:space-between;
flex-direction:row;
width:25%;
height:80px;
margin-left:4%;
margin-top:-4%;
.singup{
display:flex;
align-items:center;
justify-content:center;
color: #fff;
font-weight:bold;
font-size:18px;
background-color:#8900FF;
border:none;
cursor: pointer;
height:47px;
width:138px;
border-radius: 30px;
}
.explore{
display:flex;
align-items:center;
justify-content:center;
color: #fff;
margin-right:40px;
font-weight:bold;
font-size:18px;
background-color:transparent;
border:none;
cursor: pointer;
height:47px;
width:138px;
border-radius: 30px;
border: 2px solid #fff;
}
}
.purplediv{
max-height: 710px;
background: #100808 ;
background-color:#7F7ACF;
color:#fff;
width:205px;
height:205px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:0px;
-webkit-border-radius:50%;
/* border-top-right-radius: 0%; */
margin-left:-100px;
margin-top:330px;
/* border-bottom-right-radius: 0%; */
}
.rosediv{
max-height: 710px;
background: #100808 ;
background-color:#D39079;
color:#fff;
width:110px;
height:110px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:0px;
-webkit-border-radius:50%;
/* border-top-right-radius: 0%; */
margin-left:450px;
margin-top:330px;
/* border-bottom-right-radius: 0%; */
}
@media screen and (max-width: 900px) {
display: flex;
justify-content: center;
flex-direction:column;
height: 100px;
max-width: 1370px;
margin: 0 auto;
width: 100px;
.Money-text{
margin-top:400px;
margin-left:-240px;
/* background-color:red; */
line-height:60px;
width:400px;
height:400px;
.moneyh1{
color:#fff;
font-family:'Josefin Sans';
font-weight:bold;
font-size:50px;
}
}
.btns-aplication{
display:flex;
align-items:center;
justify-content:space-between;
flex-direction:row;
width:350px;
height:80px;
margin-left:-270px;
margin-top:-4%;
.singup{
display:flex;
align-items:center;
justify-content:center;
color: #fff;
font-weight:bold;
font-size:18px;
background-color:#8900FF;
border:none;
cursor: pointer;
height:47px;
width:138px;
border-radius: 30px;
}
.explore{
display:flex;
align-items:center;
justify-content:center;
color: #fff;
margin-right:40px;
font-weight:bold;
font-size:18px;
background-color:transparent;
border:none;
cursor: pointer;
height:47px;
width:138px;
border-radius: 30px;
border: 3px solid #fff;
}
}
.purplediv{
max-height: 710px;
background: #100808 ;
background-color:#7F7ACF;
color:#fff;
width:205px;
height:205px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:0px;
-webkit-border-radius:50%;
/* border-top-right-radius: 0%; */
margin-left:-100px;
margin-top:330px;
/* border-bottom-right-radius: 0%; */
}
.rosediv{
max-height: 710px;
background: #100808 ;
background-color:#D39079;
color:#fff;
width:110px;
height:110px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:0px;
-webkit-border-radius:50%;
/* border-top-right-radius: 0%; */
margin-left:330px;
margin-top:330px;
}
}
@media screen and (max-width: 576px) {
display: flex;
justify-content: center;
flex-direction:column;
height: 100px;
margin: 0 auto;
width: 10px;
.Money-text{
margin-top:400px;
margin-left:-160px;
/* background-color:red; */
line-height:60px;
width:400px;
height:400px;
.moneyh1{
color:#fff;
font-family:'Josefin Sans';
font-weight:bold;
font-size:45px;
}
}
.btns-aplication{
display:flex;
align-items:center;
justify-content:space-between;
flex-direction:row;
width:350px;
height:80px;
margin-left:-180px;
margin-top:-4%;
.singup{
display:flex;
align-items:center;
justify-content:center;
color: #fff;
font-weight:bold;
font-size:18px;
background-color:#8900FF;
border:none;
cursor: pointer;
height:47px;
width:138px;
border-radius: 30px;
}
.explore{
display:flex;
align-items:center;
justify-content:center;
color: #fff;
margin-right:40px;
font-weight:bold;
font-size:18px;
background-color:transparent;
border:none;
cursor: pointer;
height:47px;
width:138px;
border-radius: 30px;
border: 3px solid #fff;
}
}
.purplediv{
max-height: 710px;
background: #100808 ;
background-color:#7F7ACF;
color:#fff;
width:205px;
height:205px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:0px;
-webkit-border-radius:50%;
/* border-top-right-radius: 0%; */
margin-left:-100px;
margin-top:330px;
/* border-bottom-right-radius: 0%; */
}
.rosediv{
max-height: 710px;
background: #100808 ;
background-color:#D39079;
color:#fff;
width:110px;
height:110px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:0px;
-webkit-border-radius:50%;
/* border-top-right-radius: 0%; */
margin-left:330px;
margin-top:330px;
}
}
`
export const Header = styled.div`
display: flex;
align-self: center;
justify-content: space-between;
gap:20px;
flex-direction:row;
height: 80px;
max-width: 1370px;
margin: 0 auto;
width: 100%;
background-color:blue;
z-index:3;
background-color:transparent;
.nav-link{
display:flex;
gap:65px;
margin-left:45%;
font-family:'Josefin Sans';
font-weight:bold;
cursor: pointer;
.btn-signup{
display:flex;
align-items:center;
justify-content:center;
font-size:17px;
cursor: pointer;
width:140px;
background-color: #fff;
border:none;
border-radius:30px;
color:#6E84DB;
font-family:'Josefin Sans';
font-weight:bold;
}
}
.headerdiv{
display:flex;
align-items:center;
background-color:transparent;
gap:100px;
height:100%;
width:100%;
color:#fff;
/* border: 1px solid #fff; */
margin-top:2.5%;
.App-logo{
width:5%;
height:50%;
margin-left:2%;
cursor: pointer;
}
}
@media screen and (max-width: 900px) {
display: flex;
align-self: center;
justify-content: space-between;
gap:20px;
flex-direction:row;
height: 80px;
max-width: 1370px;
margin: 0 auto;
width: 100%;
background-color:blue;
z-index:3;
background-color:transparent;
.nav-link{
display:flex;
gap:65px;
font-family:'Josefin Sans';
font-weight:bold;
cursor: pointer;
/* margin-left:-200px; */
.btn-signup{
display:flex;
align-items:center;
justify-content:center;
font-size:17px;
cursor: pointer;
width:140px;
background-color: #fff;
border:none;
border-radius:30px;
color:#6E84DB;
font-family:'Josefin Sans';
font-weight:bold;
}
}
.headerdiv{
display:flex;
align-items:center;
background-color:transparent;
gap:100px;
height:100%;
width:100%;
color:#fff;
/* border: 1px solid #fff; */
margin-top:420px;
.App-logo{
width:30%;
height:80%;
margin-left:-27
0%;
cursor: pointer;
}
}
}
@media screen and (max-width: 576px) {
display: flex;
align-self: center;
justify-content: space-between;
gap:20px;
flex-direction:row;
height: 80px;
max-width: 1370px;
margin: 0 auto;
width: 100%;
background-color:blue;
z-index:3;
background-color:transparent;
margin-left:-120px;
.nav-link{
display:flex;
gap:65px;
font-family:'Josefin Sans';
font-weight:bold;
cursor: pointer;
/* margin-left:-200px; */
.btn-signup{
display:flex;
align-items:center;
justify-content:center;
font-size:17px;
cursor: pointer;
width:140px;
background-color: #fff;
border:none;
border-radius:30px;
color:#6E84DB;
font-family:'Josefin Sans';
font-weight:bold;
}
}
.headerdiv{
display:flex;
align-items:center;
background-color:transparent;
gap:100px;
height:100%;
width:100%;
color:#fff;
/* border: 1px solid #fff; */
margin-top:420px;
.App-logo{
width:35px;
height:80%;
margin-top: -10px;
cursor: pointer;
}
}
}
`
export const Section = styled.div`
display: flex;
align-self: center;
height:100%;
.bluecircle{
max-height: 710px;
background: #100808 ;
background: -webkit-linear-gradient(bottom,#689EE2 , #6734A1 );
background: -moz-linear-gradient(bottom, #689EE2 , #6734A1 );
background: linear-gradient(130deg, #689EE2 20%, #6734A1 65%);
color:#fff;
width:700px;
height:110%;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:0px;
-webkit-border-radius:60%;
border-top-right-radius: 0%;
/* border-top-left-radius: 55%; */
border-bottom-right-radius: 0%;
.rosedivblue{
max-height: 710px;
background: #100808 ;
background-color:#CB6796;
color:#fff;
width:150px;
height:150px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:-3.5%;
margin-left:-50px;
-webkit-border-radius:50%;
margin-top:170px
}
.grrendivblue{
max-height: 710px;
background: -webkit-linear-gradient(bottom,#85F19F , #41C4B9 );
background: -moz-linear-gradient(bottom, #85F19F , #41C4B9 );
background: linear-gradient(160deg, #85F19F 20%, #41C4B9 65%);
color:#fff;
width:230px;
height:230px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:280px;
-webkit-border-radius:50%;
margin-top:200px;
z-index:1;
}
img{
color: -webkit-linear-gradient(bottom,#85F19F , #41C4B9 );
color: -moz-linear-gradient(bottom, #85F19F , #41C4B9 );
color: linear-gradient(160deg, #85F19F 20%, #41C4B9 65%);
z-index:999;
position: relative;
opacity:0.87;
width:500px;
height:500px;
margin-top:140px;
margin-left:15%;
color:transparent;
}
}
@media screen and (max-width: 900px) {
display: flex;
align-self: center;
height:100%;
.bluecircle{
max-height: 710px;
background: #100808 ;
background: -webkit-linear-gradient(bottom,#689EE2 , #6734A1 );
background: -moz-linear-gradient(bottom, #689EE2 , #6734A1 );
background: linear-gradient(130deg, #689EE2 20%, #6734A1 65%);
color:#fff;
width:700px;
height:110%;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:90px;
-webkit-border-radius:60%;
border-top-right-radius: 0%;
/* border-top-left-radius: 55%; */
border-bottom-right-radius: 0%;
margin-top: 300px;
.rosedivblue{
max-height: 710px;
background: #100808 ;
background-color:#CB6796;
color:#fff;
width:120px;
height:120px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:-3.5%;
margin-left:-50px;
-webkit-border-radius:50%;
margin-top: 160px;
}
.grrendivblue{
max-height: 710px;
background: -webkit-linear-gradient(bottom,#85F19F , #41C4B9 );
background: -moz-linear-gradient(bottom, #85F19F , #41C4B9 );
background: linear-gradient(160deg, #85F19F 20%, #41C4B9 65%);
color:#fff;
width:230px;
height:230px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:230px;
-webkit-border-radius:50%;
z-index:1;
margin-top: 200px;
}
img{
color: -webkit-linear-gradient(bottom,#85F19F , #41C4B9 );
color: -moz-linear-gradient(bottom, #85F19F , #41C4B9 );
color: linear-gradient(160deg, #85F19F 20%, #41C4B9 65%);
z-index:999;
position: relative;
opacity:0.8;
width:500px;
height:500px;
margin-top:140px;
margin-left:5%;
color:transparent;
margin-top: 130px;
}
}
}
@media screen and (max-width: 576px) {
display: flex;
align-self: center;
height:100%;
.bluecircle{
max-height: 710px;
background: #100808 ;
background: -webkit-linear-gradient(bottom,#689EE2 , #6734A1 );
background: -moz-linear-gradient(bottom, #689EE2 , #6734A1 );
background: linear-gradient(130deg, #689EE2 20%, #6734A1 65%);
color:#fff;
width:600px;
height:110%;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:135px;
-webkit-border-radius:60%;
border-top-right-radius: 0%;
/* border-top-left-radius: 55%; */
border-bottom-right-radius: 0%;
margin-top: 300px;
.rosedivblue{
max-height: 710px;
background: #100808 ;
background-color:#CB6796;
color:#fff;
width:120px;
height:120px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:-3.5%;
margin-left:-50px;
-webkit-border-radius:50%;
margin-top: 160px;
}
.grrendivblue{
max-height: 710px;
background: -webkit-linear-gradient(bottom,#85F19F , #41C4B9 );
background: -moz-linear-gradient(bottom, #85F19F , #41C4B9 );
background: linear-gradient(160deg, #85F19F 20%, #41C4B9 65%);
color:#fff;
width:230px;
height:230px;
position: fixed;
border-radius:50%;
-moz-border-radius:50%;
margin-top:-100px;
margin-left:230px;
-webkit-border-radius:50%;
z-index:1;
margin-top: 200px;
}
img{
color: -webkit-linear-gradient(bottom,#85F19F , #41C4B9 );
color: -moz-linear-gradient(bottom, #85F19F , #41C4B9 );
color: linear-gradient(160deg, #85F19F 20%, #41C4B9 65%);
z-index:999;
position: relative;
opacity:0.8;
width:370px;
height:370px;
margin-left:5%;
color:transparent;
margin-top: 200px;
}
}
}
`
<file_sep>import logo from './assets/card.svg';
import credit from './assets/21.svg';
import './App.css';
import {Container, Header,Section}from './styles';
function App() {
return (
<Container>
<Header>
<div className="headerdiv">
<img src={logo} className="App-logo" alt="logo" />
<div className="nav-link">
<p>Features</p>
<p>Pricing</p>
<p>About</p>
<button className="btn-signup">
Sign up
</button>
</div>
</div>
</Header>
<Section>
<div className="bluecircle">
<div className="rosedivblue">
</div>
<div className="grrendivblue">
</div>
<img src={credit} color="visa" alt="visacredit"></img>
</div>
</Section>
<div className="Money-text">
<h1 className="moneyh1">Money<br/> really does<br/> grow on <br/>trees.<br/> Really!</h1>
</div>
<div className="btns-aplication">
<button className="singup">
Sign up
</button>
<button className="explore">
Explore
</button>
<div className="purplediv">
</div>
<div className="rosediv">
</div>
</div>
</Container>
);
}
export default App;
|
ad515e1e1cc9c51240c94d0e53e915869c4f02ac
|
[
"JavaScript"
] | 2
|
JavaScript
|
Jorge989/VisaStudy
|
9ea33254048965205f3d8443bcf5ef2bc960e6d5
|
88672417efe850fa87537756c0121238e7b7c9a1
|
refs/heads/master
|
<file_sep>import random
import numpy
import math
'''
@author <NAME>
@email <EMAIL>
'''
class Cuckoo():
def __init__(self, NP, N_Gen, pa, Lower, Upper, function):
self.D = len(Lower) # dimension
self.NP = NP # population size
self.N_Gen = N_Gen # generations
self.Lower = Lower # lower bound
self.Upper = Upper # upper bound
self.f_min = 0.0 # minimum fitness
self.pa = pa # alpha
self.Sol = [[0 for i in range(self.D)] for j in range(self.NP)] # population of solutions
self.newSol = [[0 for i in range(self.D)] for j in range(self.NP)] # population of solutions
self.Fitness = [0] * self.NP # fitness
self.best = [0] * self.D # best solution
self.Fun = function
def init_ff(self):
for i in range(self.NP):
for j in range(self.D):
rnd = random.uniform(0, 1)
self.Sol[i][j] = self.Lower[j] + (self.Upper[j] - self.Lower[j]) * numpy.random.uniform(0, 1)
self.Fitness[i] = self.Fun(self.Sol[i])
def findRange(self):
for i in range(len(self.newSol)):
for j in range(len(self.newSol[i])):
if self.newSol[i][j] < self.Lower[j]: self.newSol[i][j] = self.Lower[j]
if self.newSol[i][j] > self.Upper[j]: self.newSol[i][j] = self.Upper[j]
def get_best_nest(self):
#% Evaluating all new solutions
for j in range(self.NP):
fnew=self.Fun(self.newSol[j])
if fnew<self.Fitness[j]:
self.Fitness[j]=fnew
self.Sol[j]=[self.newSol[j][k] for k in range(self.D)]
#% Find the current best
if fnew<self.f_min:
self.f_min=fnew
self.best=[self.newSol[j][k] for k in range(self.D)]
def get_cuckoos(self):
# levy flights
n = self.NP
# levy exp and coef
beta=3.0/2
sigma = (math.gamma(1+beta)*math.sin(math.pi*beta/2)/(math.gamma((1+beta)/2)*beta*2**((beta-1)/2)))**(1/beta)
for i in range(n):
s = [self.Sol[i][j] for j in range(self.D)]
# levy flights by mantegna's algorithm
u = [numpy.random.normal()*sigma for j in range(self.D)]
v = [numpy.random.normal() for j in range(self.D)]
step = [u[j]/(math.fabs(v[j])**(1/beta)) for j in range(self.D)]
stepsize = [0.01*step[j]*(s[j]-self.best[j]) for j in range(self.D)]
s=[s[j]+stepsize[j]*numpy.random.normal() for j in range(self.D)]
for j in range(self.D):
if s[j]<self.Lower[j]:
self.newSol[i][j] = self.Lower[j]
elif s[j]>self.Upper[j]:
self.newSol[i][j] = self.Upper[j]
else:
self.newSol[i][j] = s[j]
def empty_nest(self):
n = self.NP
# new_nest = [[self.Sol[i][j] for j in range(self.D)] for i in range(n)]
for i in range(n):
K = [numpy.random.uniform(0,1)>self.pa for j in range(self.NP)]
rand = numpy.random.uniform(0,1)
perm=numpy.random.permutation(n)
ind1=perm[0]
ind2=perm[1]
nest1 = [self.Sol[ind1][j] for j in range(self.D)]
nest2 = [self.Sol[ind2][j] for j in range(self.D)]
stepsize = [rand*(nest1[j]-nest2[j]) for j in range(self.D)]
#self.newSol=[self.Sol[i][j] for j in range(self.D)]
for j in range(self.D):
if K[j]:
self.newSol[i][j] = self.Sol[i][j] + stepsize[j]
if self.newSol[i][j]>self.Upper[j]:
self.newSol[i][j] = self.Upper[j]
elif self.newSol[i][j]<self.Lower[j]:
self.newSol[i][j]=self.Lower[j]
def move_cc(self):
self.init_ff()
t=0
while t <self.N_Gen:
self.get_cuckoos()
self.get_best_nest()
t = t+self.NP
self.empty_nest()
self.get_best_nest()
t = t+self.NP
# print self.f_min
class BBatAlgorithm():
# no need to change
def __init__(self, D, NP, N_Gen, A, r, Qmin,
Qmax, function):
self.D = D #dimension
self.NP = NP #population size
self.N_Gen = N_Gen #generations
self.A = A #loudness
self.r = r #pulse rate
self.Qmin = Qmin #frequency min
self.Qmax = Qmax #frequency max
self.f_min = 0.0 #minimum fitness
self.Lb = [0] * self.D #lower bound
self.Ub = [0] * self.D #upper bound
self.Q = [0] * self.NP #frequency
self.v = [[0 for i in range(self.D)] for j in range(self.NP)] #velocity
self.Sol = [[False for i in range(self.D)] for j in range(self.NP)] #population of solutions
self.Fitness = [0] * self.NP #fitness
self.best = [0] * self.D #best solution
self.Fun = function
# the best individu is defined by minimize function
def best_bat(self):
j = 0
for i in range(self.NP):
if self.Fitness[i] < self.Fitness[j]:
j = i
for i in range(self.D):
self.best[i] = self.Sol[j][i]
self.f_min = self.Fitness[j]
# need to modify in representation of individu to binary
# solve
def init_bat(self):
for i in range(self.NP):
self.Q[i] = 0
for j in range(self.D):
rnd = numpy.random.uniform(0, 1)
self.v[i][j] = 0.0
if (rnd<=numpy.random.uniform(0, 1)):
self.Sol[i][j] = 0
else :
self.Sol[i][j] = 1
#self.Sol[i][j] = self.Lb[j] + (self.Ub[j] - self.Lb[j]) * rnd
self.Fitness[i] = self.Fun(self.Sol[i])
self.best_bat()
# need to modify in transfer function, done
def move_bat(self):
goodInitiation = False
while not goodInitiation:
self.init_bat()
testGoodness = [0 for i in range(self.D)]
for ii in self.Sol:
for idx, jj in enumerate(ii):
if jj == 1: testGoodness[idx] = 1
goodInitiation = numpy.sum(testGoodness) == self.D
for t in range(self.N_Gen):
print("Generation : ", t)
for i in range(self.NP):
tempSol = [self.Sol[i][k] for k in range(self.D)]
for j in range(self.D):
rnd = numpy.random.uniform(0, 1)
self.Q[i] = self.Qmin + (self.Qmax - self.Qmin) * rnd
self.v[i][j] = self.v[i][j] + (self.Sol[i][j] -
self.best[j]) * self.Q[i]
rnd = numpy.random.uniform(0,1)
# Equation 9 in the paper
V_shaped_transfer_function = math.fabs((2/math.pi)*
math.atan((math.pi/2)*
self.v[i][j]))
if rnd < V_shaped_transfer_function:
if tempSol[j]:
tempSol[j] = 0
else:
tempSol[j] = 1
rnd = numpy.random.uniform(0,1)
if rnd > self.r:
tempSol[j]=self.best[j]
Fnew = self.Fun(tempSol)
rnd = numpy.random.uniform(0,1)
if (Fnew <= self.Fitness[i]) and (rnd < self.A):
for j in range(self.D):
self.Sol[i][j] = tempSol[j]
self.Fitness[i] = Fnew
if Fnew <= self.f_min:
for j in range(self.D):
self.best[j] = tempSol[j]
self.f_min = Fnew
<file_sep># AutomatedEmbryoPrediction
This is a project that aims to predict the embryo stages in
its early development. The stages of embryo development is
indicated by the number of blastomer of embryo. In this project
we detect up to 5-cell stage. This project utilize CRF that
developed by Khan et, al [1]. This project using mouse embryo
dataset from celltracking.bio.nyu.edu. This project has a good
result in predicting 1-cell, 2-cells, and 4-cells stages, worst
in predicting 3-cell stage, Acceptable for predicting 5-cells
stages.
Overall this project has an unique point in feature extraction.
we do not using common feature extraction as GLCM, SIFT, or Bag of
Visual Words. In this project we use histogram of distance of edge
to extract the feature from an embryo image.
It is very recomended running this project in python 3.5 environment.
# Image Pre-Processing
we utilize skimage library to perform pre-processing. pre-processing
is the most important step in this project. there are two independent
pre-processing. the first one is used in frame based prediction.
and the other is used for transition prediction.
the first one utilize frangi filter and sobel to do edge detection.
the purpose of this preprocessing is to extract embryo membrane from
mouse embryo image.
and the second utilize sobel only to do edge detection. the purpose
of this preprocessing is to extract 'edge' shape from embryo image.
# Feature
from both preprocessing then all points that represent edge will be
extract and will be used to constructed list of points P={(x1,y1),(x2,y2),..
,(xn,yn)}. using a points called 'center points' then we will compute the distance
of all points in list of points P to produce a histogram of distance. this
histogram of distance will be used as feature for frame based prediction and
transition prediction.
special for transition prediction, the feature will have more computation
to calculate the difference of feature from two contigous frames.
# Frame based Prediction
frame based prediction (fbp) aims to make a prediction based on one independent frame.
fbp will predict probabiity from each number of blastomer from one frame. in the process
we do feature selection for improve the prediction performance. we utilize binary bat algorithm [2]
to do the selection. we use 30 iteration and 20 particle (artificial bat) in utilizing bba.
# Transition Prediction
transition prediction aims to make a prediction of probability of transition from two
contigous frames.
# CRF
Conditional random field is utilized to stabilize the prediction. combination of
frame based prediction and transition prediction is used in the process. more frames
in sequance will produce better result in prediction.
# Experiment
we recomend do experiment with portion of train and test 50-50 percent. for time purpose
we only use 10 sequance from original dataset (train: E00,E06,E11,E16E25 || test:E03,E24,E26,E27,E30).
we do experiment several times to get the best result. each experiment will produce different
result based on which feature is selected.
run experiment : LS.py
# Visualization
we provide simple program to see performance of our model. run the script and you will see a simple GUI.
with this GUI you can choose the sequance folder and the model will make a prediction of all frame in
this sequance. while the process is running please do not intervene the GUI.
run : GUIAEP.py
# refrence:
[1] <NAME>, <NAME>, and <NAME>,“Automated monitoring of human embryonic cells up to the 5-cell
stage in time-lapse microscopy images,” 12th International Symposium
on Biomedical Imaging (ISBI), pp. 389–393, 2015.
[2] <NAME>., <NAME>., <NAME>,"Binary bat algorithm," Neural
Computing and Applications, 25(3):663–681, 2014.
# Folder structure
if you want to add some sequance in any folder please follow these structure.
- training
|- sequance1
|- class1
|- frame1
|- frame2
|- frame-n
|- class2
|- class3
|- class4
|- class5
|- sequance2
|- sequance-m
- test
|- sequance1
|- class1
|- frame1
|- frame2
|- frame-n
|- class2
|- class3
|- class4
|- class5
|- sequance2
|- sequance-m
- sequance
|- sequance1
|- frame1
|- frame2
|- frame-n
<file_sep>import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegressionCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn import tree
from skimage.io import imread
import numpy as np
from os import listdir
import os.path
import pickle
from helper import featureExtractionFBP, featureExtractionTP
from Optimization import BBatAlgorithm
'''
@author <NAME>
@email <EMAIL>
'''
class LearningSystemFBP():
def __init__(self,loadDataSet=False):
self.RANDOM_STATE = 123
self.machine = RandomForestClassifier(warm_start=True,
max_features='sqrt',
oob_score=True,
random_state=self.RANDOM_STATE)
self.oobErrorList=[]
self.errorTest=[]
self.fileName="LearningSystemFBP.pkl"
self.min_estimator = 30
self.max_estimator = 100
self.loadDataSet=loadDataSet
self.selectedFeature=None
self.number = 0
self.n_estimator = None
self.X = None
self.y = None
self.Xtest = None
self.ytest = None
def save(self):
with open(self.fileName,'wb') as output:
pickle.dump(self,output,pickle.HIGHEST_PROTOCOL)
def load(self):
with open(self.fileName,'rb') as input:
obj = pickle.load(input)
self.RANDOM_STATE = obj.RANDOM_STATE
self.machine = obj.machine
self.oobErrorList = obj.oobErrorList
self.errorTest = obj.errorTest
self.selectedFeature = obj.selectedFeature
self.n_estimator = obj.n_estimator
self.X = obj.X
self.y = obj.y
self.Xtest = obj.Xtest
self.ytest = obj.ytest
def readImageAndExtractImageFeature(self,fname):
if fname.find("Frame") != -1 and fname.find(".png") != -1:
img = imread(fname, as_grey=False)
if img.shape.__len__() == 2:
return featureExtractionFBP(img)
else:
return None
else:
return None
def getDataSet(self, path):
fullPath = []
for dir in listdir(path):
for f in listdir(path+dir):
fullPath.extend([path+dir+"\\"+f])
X=[]
y=[]
for dir in fullPath:
tempX=[self.readImageAndExtractImageFeature(dir+"\\"+imgFname) for imgFname in listdir(dir)]
tempX=[ii for ii in tempX if type(ii) != type(None)]
X.extend(tempX)
strSplit = dir.split("\\")
y.extend([strSplit[strSplit.__len__()-1] for i in range(tempX.__len__())])
return (X,y)
def trainTemporaryMachine(self,x,X,y,Xtest,ytest):
selectedFeature = [idx for idx, val in enumerate(x) if val==1]
clf = tree.DecisionTreeClassifier()
if np.sum(selectedFeature) == 0: return 10
clf.fit(X[:,selectedFeature], y)
yPTest = clf.predict(Xtest[:,selectedFeature])
yP = clf.predict(X[:,selectedFeature])
yPTestval = clf.predict_proba(Xtest[:,selectedFeature])
yPval = clf.predict_proba(X[:,selectedFeature])
yPTestval = np.max(yPTestval, axis=1)
yPval = np.max(yPval, axis=1)
acc1 = np.sum(yPTestval[yPTest==ytest])
acc2 = np.sum(yPval[yP==y])
return -(acc1+acc2)
def train(self):
if not self.loadDataSet:
trainDataSetPath = "training\\"
testDataSetPath = "test\\"
self.X, self.y = self.getDataSet(trainDataSetPath)
self.Xtest, self.ytest = self.getDataSet(testDataSetPath)
X=np.array([np.array(ii) for ii in self.X])
y=np.array(self.y)
Xtest=np.array([np.array(ii) for ii in self.Xtest])
ytest=np.array(self.ytest)
else :
print("load dataset")
self.load()
X=np.array([np.array(ii) for ii in self.X])
y=np.array(self.y)
Xtest=np.array([np.array(ii) for ii in self.Xtest])
ytest=np.array(self.ytest)
self.selectedFeature = None
if self.selectedFeature is None:
self.selectedFeature = [idx for idx in range(X.shape[1])]
D = X[0].__len__()
opt = BBatAlgorithm(D=D,
NP=40,
N_Gen=30,
A=0.4,
r=0.8,
Qmin=0,
Qmax=2,
function=lambda x: self.trainTemporaryMachine(x,X,y,Xtest,ytest))
opt.move_bat()
self.selectedFeature = [idx for idx, val in enumerate(opt.best) if val==1]
else :
print("using previous selected feature")
self.oobErrorList = []
self.errorTest = []
X=X[:,self.selectedFeature]
Xtest=Xtest[:,self.selectedFeature]
self.machine = RandomForestClassifier(warm_start=True,
max_features='sqrt',
oob_score=True,
random_state=self.RANDOM_STATE)
tempOObError = 1
min_estimator = 20
tempParams = min_estimator
max_estimator = self.max_estimator
for i in range(min_estimator,max_estimator+1):
self.machine.set_params(n_estimators=i)
self.machine.fit(X,y)
oob_error = 1 - self.machine.oob_score_
self.oobErrorList.append((i,oob_error))
yPTest = self.machine.predict(Xtest)
oob_error2 = 1 - np.mean(ytest==yPTest)
self.errorTest.append((i,oob_error2))
if oob_error2 < tempOObError:
tempParams = i
tempOObError = oob_error2
self.n_estimator = tempParams
def build(self,retrain=True):
if os.path.isfile(self.fileName) and not retrain:
self.load()
else:
self.train()
self.save()
X=np.array([np.array(ii) for ii in self.X])
y=np.array(self.y)
Xtest=np.array([np.array(ii) for ii in self.Xtest])
ytest=np.array(self.ytest)
X=X[:,self.selectedFeature]
Xtest=Xtest[:,self.selectedFeature]
print("retrain new machine")
machine = RandomForestClassifier(warm_start=True,
max_features='sqrt',
oob_score=True,
random_state=self.RANDOM_STATE)
machine.set_params(n_estimators=self.n_estimator)
machine.fit(X,y)
ypred = machine.predict(X)
ytpred = machine.predict(Xtest)
ytpred_prob = machine.predict_proba(Xtest)
print(np.sum(np.max(ytpred_prob,axis=1)[ytpred==ytest]))
cnf_matrix_train = confusion_matrix(y, ypred)
print(cnf_matrix_train)
cnf_matrix_test = confusion_matrix(ytest, ytpred)
print(cnf_matrix_test)
print(np.mean(ytest==ytpred))
print(np.min(self.errorTest))
print(self.n_estimator)
def plotOOBError(self):
xs, ys = zip(*self.oobErrorList)
plt.plot(xs,ys,label="train")
xtest, ytest = zip(*self.errorTest)
plt.plot(xtest, ytest,label="test")
plt.xlim(self.min_estimator, self.max_estimator)
plt.xlabel("n_estimators")
plt.ylabel("OOB error rate")
plt.legend(loc="upper right")
plt.show()
def predict_proba(self,fname=None,img=None):
if fname is not None :
feature = self.readImageAndExtractImageFeature(fname)
if img is not None :
feature = featureExtractionFBP(img)
if feature is None: return None
return self.machine.predict_proba([feature[self.selectedFeature]])[0]
class LearningSystemTP():
def __init__(self,loadDataSet=False):
self.RANDOM_STATE=123
self.machine = LogisticRegressionCV(tol=1e-6)
self.pathTraining = "training\\"
self.pathTest = "test\\"
self.fileName = "LearningSystemTP.pkl"
self.selectedFeature = None
self.loadDataSet = loadDataSet
self.X = None
self.y = None
self.Xtest = None
self.ytest = None
self.n_estimator = 20
self.min_estimator = 30
self.max_estimator = 100
def save(self):
with open(self.fileName,'wb') as output:
pickle.dump(self,output,pickle.HIGHEST_PROTOCOL)
def load(self):
with open(self.fileName,'rb') as input:
obj = pickle.load(input)
self.machine = obj.machine
self.selectedFeature = obj.selectedFeature
self.X = obj.X
self.y = obj.y
self.Xtest = obj.Xtest
self.ytest = obj.ytest
self.n_estimator = obj.n_estimator
def readAndValidateImg(self, fname):
if fname.find("Frame") != -1 and fname.find(".png") != -1:
img = imread(fname, as_grey=False)
if img.shape.__len__() == 2:
return featureExtractionTP(img)
else:
return None
else:
return None
def pred_prob(self,img1=None,img2=None):
if img1 is None and img2 is None:
print("error img1 and img2 is found to be None")
if img2 is None:
print("error img2 should not be None")
desc1 = None
if img1 is not None:
desc1 = featureExtractionTP(img=img1)
desc2 = featureExtractionTP(img=img2)
feature = self.extractDiffFromImage(desc1,desc2)
return self.machine.predict_proba([feature])[0]
def extractDiffFromImage(self,hedfit0,hedfit1):
""" method ini memiliki tugas untuk membuat fitur dari dua gambar yg berdampingang
'contigous frame'."""
if hedfit0 is None:
hedfit0 = np.copy(hedfit1)
return np.sqrt((hedfit0-hedfit1)**2)
def getDataFromTheClass(self, classPath):
""" method ini memiliki tugas untuk mengolah seluruh gambar pada
kelas yg direpresentasikan sebagai sebuah folder dg nama 'classPath'.
Tugas fungsi ini ada 3, pertama untuk mengembalikan gambar pertama
pada folder, kedua membuat list 'feature' dari gambar yang berdampingan,
ketiga untuk mengembalikan gambar terakhir """
listImg = []
for imgfname in listdir(classPath):
listImg.extend([classPath+imgfname])
f_img = None
idx = 0
while f_img is None:
f_img = self.readAndValidateImg(fname=listImg[idx])
idx += 1
tempX = []
l_img = None
l_idx = listImg.__len__()
ff_img = f_img
while idx < l_idx:
ss_img = None
while ss_img is None:
ss_img = self.readAndValidateImg(listImg[idx])
if ss_img is None:
idx += 1
idx +=1
l_img = ss_img
tempX.extend([self.extractDiffFromImage(ff_img,ss_img)])
ff_img = ss_img
return f_img, tempX, l_img
def getDataSet(self, path):
fullPath = []
for sequanceName in listdir(path):
fullPath.extend([path+sequanceName+"\\"])
X = []
y = []
for sequancePath in fullPath:
tempDir = []
for dir in listdir(sequancePath):
tempDir.extend([sequancePath+dir+"\\"])
firstImg = None
for class_of_the_seq in tempDir:
f_img, tempX, l_img = self.getDataFromTheClass(class_of_the_seq)
tx = [self.extractDiffFromImage(firstImg,f_img)]
if firstImg is None:
ty = [0]
else:
ty = [1]
firstImg = l_img
tx.extend(tempX)
ty.extend([0 for i in tempX])
X.extend(tx)
y.extend(ty)
return (X,y)
def train(self):
if self.loadDataSet:
self.load()
X = self.X
y = self.y
Xtest = self.Xtest
ytest = self.ytest
X=np.array([np.array(ii) for ii in X])
y=np.array(y)
else:
X,y = self.getDataSet(self.pathTraining)
Xtest,ytest = self.getDataSet(self.pathTest)
X=np.array([np.array(ii) for ii in X])
y=np.array(y)
Xtest=np.array([np.array(ii) for ii in Xtest])
ytest=np.array(ytest)
self.X = X
self.Xtest = Xtest
self.y = y
self.ytest = ytest
self.save()
self.selectedFeature = [idx for idx in range(X.shape[1])]
X=X[:,self.selectedFeature]
self.machine = RandomForestClassifier(warm_start=True,
max_features='sqrt',
oob_score=True,
random_state=self.RANDOM_STATE)
self.machine.set_params(n_estimators=20)
self.machine.fit(X,y)
def build(self,retrain=True):
if retrain:
""" train the classifier """
self.train()
self.save()
else:
""" load the trained model """
self.load()
self.report()
def report(self):
""" fungsi ini bertugas untuk membuat laporan yang berkaitan dengan
hasil leraning """
ys = self.ytest#[0:400]
xs = np.array(range(ys.__len__()))
plt.plot(xs,ys,label="label")
ytest = self.machine.predict_proba(self.Xtest[:,self.selectedFeature])
xtest = np.copy(xs)
plt.plot(xtest, ytest[:,1],label="pred")
plt.xlabel("frame")
plt.ylabel("pred")
plt.legend(loc="upper right")
plt.show()
class LearningSystemCRF():
def __init__(self):
self.fbp = LearningSystemFBP()
self.fbp.load()
self.tp = LearningSystemTP()
self.tp.load()
self.X_fbp = None
self.y = None
self.X_tp = None
self.fileName = "LearningSystemCRF.pkl"
def save(self):
with open(self.fileName,'wb') as output:
pickle.dump(self,output,pickle.HIGHEST_PROTOCOL)
def load(self):
with open(self.fileName,'rb') as input:
obj = pickle.load(input)
self.X_fbp = obj.X_fbp
self.y = obj.y
self.X_tp = obj.X_tp
def makeNewPrediction(self, list_of_cp, pred_prob, tp_prob):
if list_of_cp is None:
return [[[None, -np.log2(ii)] for ii in pred_prob]]
else :
temp_oc = []
ll = list_of_cp[-1]
for idx, ii in enumerate(pred_prob):
tidx = idx
ts = -np.log2(ii)+ll[idx][1]
for idxl in range(idx+1):
tn = -np.log2(ii)+ll[idxl][1]
if idxl < idx:
tn = tn+1-tp_prob[1]
else:
tn = tn+tp_prob[1]
if ts > tn:
ts = tn
tidx = idxl
temp_oc.extend([[tidx,ts]])
list_of_cp.extend([temp_oc])
return list_of_cp
def translateListOfCP(self,list_of_cp):
pred = []
rr = np.sort(-np.array(range(list_of_cp.__len__())))*-1
iidx = list_of_cp[-1][-1][0]
val = list_of_cp[-1][-1][-1]
for ii in list_of_cp[-1]:
if ii[1] < val:
iidx = ii[0]
val = ii[1]
pred.extend([iidx])
for ii in rr:
iidx = list_of_cp[ii][iidx][0]
pred.extend([iidx])
arrR = np.array(pred)
return arrR[rr]
def predictPerSequence(self, pathSequance, load=False):
if not load:
fullPath = []
for className in listdir(pathSequance):
fullPath.extend([pathSequance+"\\"+className])
X_fbp=[]
X_tp = []
y=[]
ff_img = None
for dir in fullPath:
tempX=[self.fbp.predict_proba(dir+"\\"+imgFname) for imgFname in listdir(dir)]
tempX=[ii for ii in tempX if ii is not None]
X_fbp.extend(tempX)
strSplit = dir.split("\\")
y.extend([strSplit[strSplit.__len__()-1] for i in range(tempX.__len__())])
f_img, tempX, l_img = self.tp.getDataFromTheClass(dir+"\\")
tx = [self.tp.extractDiffFromImage(ff_img,f_img)]
ff_img = l_img
tx.extend(tempX)
X_tp.extend(tx)
pred_prob_tp = self.tp.machine.predict_proba(X_tp)
self.X_fbp = X_fbp
self.y = y
self.X_tp = X_tp
self.save()
else:
self.load()
X_fbp = self.X_fbp
y = self.y
X_tp = self.X_tp
pred_prob_tp = self.tp.machine.predict_proba(X_tp)
X_fbp = np.array(X_fbp)
X_fbp[X_fbp==0] = 1e-62
list_of_cp = None
for idx, ii in enumerate(X_fbp):
list_of_cp = self.makeNewPrediction(list_of_cp,ii,pred_prob_tp[idx,:])
arrR = np.array(self.translateListOfCP(list_of_cp))+1
return arrR
def testPredSeq(self):
path = "test\\E03"
print(path)
pp = self.predictPerSequence(path,load=False)
print(pp)
print(self.y.__len__())
cnf_matrix_train = confusion_matrix(self.y, [ii.__str__() for ii in pp])
print(np.mean([int(ii) for ii in self.y]==pp))
print(cnf_matrix_train)
class LCRF():
def __init__(self):
self.fbp = LearningSystemFBP()
self.fbp.load()
self.tp = LearningSystemTP()
self.tp.load()
self.list_of_cp = None
self.pred_prob_fbp = None
self.pred_prob_tp = None
self.list_of_img = None
self.min_n_img = 2
self.seq_is_complete = False
self.n=10
def set_params(self,seq_is_complete = False):
self.seq_is_complete = seq_is_complete
def makeNewPrediction(self):
list_of_cp = self.list_of_cp
pred_prob = self.pred_prob_fbp[-1]
pred_prob[pred_prob==0]=1e-50
tp_prob = self.pred_prob_tp[-1]
if list_of_cp is None:
self.list_of_cp = [[[None, -np.log2(ii)] for ii in pred_prob]]
else :
temp_oc = []
ll = list_of_cp[-1]
for idx, ii in enumerate(pred_prob):
tidx = idx
ts = -np.log2(ii)+ll[idx][1]
for idxl in range(idx+1):
tn = -np.log2(ii)+ll[idxl][1]
if idxl < idx:
tn = tn+1-tp_prob[1]
else:
tn = tn+tp_prob[1]
if ts > tn:
ts = tn
tidx = idxl
temp_oc.extend([[tidx,ts]])
list_of_cp.extend([temp_oc])
self.list_of_cp = list_of_cp
def add_new_img(self,img):
if img.shape != (480,480):
print("image must have size 480x480")
else:
if self.list_of_img is None:
self.list_of_img = np.array([img])
self.pred_prob_fbp = np.array([self.fbp.predict_proba(img=img)])
self.pred_prob_tp = np.array([self.tp.pred_prob(img1=None,img2=img)])
else :
self.pred_prob_tp = np.append(self.pred_prob_tp,[self.tp.pred_prob(img1=self.list_of_img[-1,:,:],img2=img)],axis=0)
self.list_of_img = np.append(self.list_of_img,[img],axis=0)
self.pred_prob_fbp = np.append(self.pred_prob_fbp,[self.fbp.predict_proba(img=img)],axis=0)
self.makeNewPrediction()
def pred_img(self,n=1):
if self.list_of_img is None:
print("cannot make a prediction without input sequance of image")
elif n==0 and self.list_of_img.shape[0] == 1:
print("cannot make a prediction using one image, at least the sequance contain "+self.n.__str__()+" of contigous image")
elif n== self.list_of_img.shape[0]-1:
if self.seq_is_complete:
list_of_cp = self.list_of_cp
ll = list_of_cp[n]
minV = ll[0][1]
iidx = 0
for idx, ii in enumerate(ll):
if ii[1]<minV:
iidx = idx
minV = ii[1]
return iidx+1
else:
print("the sequance is not complete thus cannot make a prediction of last frame, "
"the predicition only be made for frame t-"+self.n.__str__())
elif n < self.list_of_img.shape[0]-self.n:
list_of_cp = self.list_of_cp
nn = self.list_of_img.shape[0]-1
ll = list_of_cp[nn]
minV = ll[0][1]
iidx = 0
for idx, ii in enumerate(ll):
if ii[1]<minV:
iidx = idx
minV = ii[1]
while nn > n+1:
iidx = self.list_of_cp[nn][iidx][0]
nn-=1
return list_of_cp[nn][iidx][0]+1
else:
if self.seq_is_complete:
list_of_cp = self.list_of_cp
nn = self.list_of_img.shape[0]-1
ll = list_of_cp[nn]
minV = ll[0][1]
iidx = 0
for idx, ii in enumerate(ll):
if ii[1]<minV:
iidx = idx
minV = ii[1]
while nn > n+1:
iidx = self.list_of_cp[nn][iidx][0]
nn-=1
return list_of_cp[nn][iidx][0]+1
else:
print("the sequance is not complete thus cannot make the prediction of this frame, "
"the predicition only be made for frame t-"+self.n.__str__())
class testLCRF():
def __init__(self):
self.machine = LCRF()
def readAndValidateImg(self, fname):
if fname.find("Frame") != -1 and fname.find(".png") != -1:
img = imread(fname, as_grey=False)
if img.shape.__len__() == 2:
return img
else:
return None
else:
return None
def runningTest(self):
path = "test\\E03"
fullPath = []
for className in listdir(path):
fullPath.extend([path+"\\"+className])
n_in_img = 0
n_pred = 0
arr = []
y = []
for dir in fullPath:
print(dir)
yy = dir[-1]
for imgFname in listdir(dir):
# print(imgFname)
img = self.readAndValidateImg(dir+"\\"+imgFname)
if img is not None:
y.extend([yy])
self.machine.add_new_img(img)
n_in_img += 1
pp = self.machine.pred_img(n_pred)
if pp is not None:
arr.extend([pp])
# print(pp)
n_pred+=1
self.machine.set_params(seq_is_complete=True)
while n_pred != n_in_img:
pp = self.machine.pred_img(n_pred)
if pp is not None:
arr.extend([pp])
# print(pp)
n_pred+=1
arr = np.array(arr)
print(arr.shape)
cnf_matrix_train = confusion_matrix(y, [ii.__str__() for ii in arr])
print(cnf_matrix_train)
if __name__ == "__main__":
ls = LearningSystemFBP(loadDataSet=False)
ls.build(retrain=True)
print(ls.selectedFeature)
ls = LearningSystemTP(loadDataSet=False)
ls.build(retrain=True)
ls.report()
ls = LearningSystemCRF()
ls.testPredSeq()
ls = testLCRF()
ls.runningTest()
<file_sep>import tkinter as tk
from tkinter.filedialog import askdirectory
from LS import *
from skimage.io import imread
from os.path import exists
'''
@author <NAME>
@email <EMAIL>
'''
class Application(tk.Frame):
def __init__(self, master=None,retrain=False):
super().__init__(master)
self.pack()
self.img = None
self.create_widgets()
self.machine = LCRF()
def create_widgets(self):
self.search = tk.Button(self, text="browse",
command=self.getName)
self.search.pack(side="right")
self.image = tk.Label(self, image=self.img)
self.image["text"] = "choose the sequance"
# self.image["image"] = self.img
self.image.pack(side="left")
def readAndValidateImg(self, fname):
if fname.find("Frame") != -1 and fname.find(".png") != -1:
img = imread(fname, as_grey=False)
if img.shape.__len__() == 2:
return img
else:
return None
else:
return None
def getName(self):
path = askdirectory()
if exists(path):
fullPath = []
for fName in listdir(path):
fullPath.extend([path+"\\"+fName])
n_img = 0
n_pred = 0
self.changePhotoAndLable(fileName=fullPath[0],pred=0)
for fileName in fullPath:
img = self.readAndValidateImg(fileName)
if img is not None:
self.machine.add_new_img(img)
n_img += 1
pp = self.machine.pred_img(n_pred)
if pp is not None:
self.changePhotoAndLable(fileName=fullPath[n_pred],pred=pp)
n_pred+=1
self.machine.set_params(seq_is_complete=True)
while n_pred != n_img:
pp = self.machine.pred_img(n_pred)
if pp is not None:
self.changePhotoAndLable(fileName=fullPath[n_pred],pred=pp)
n_pred+=1
def changePhotoAndLable(self,fileName,pred):
self.img = tk.PhotoImage(file=fileName)
self.image["image"] = self.img
prediction = pred
self.search["text"] = prediction
self.image.pack()
self.image.update_idletasks()
self.image.update()
if __name__ == "__main__":
root = tk.Tk()
app = Application(master=root)
app.mainloop()<file_sep>from skimage.filters import frangi, sobel
from skimage import exposure
from skimage.morphology import erosion, square
from scipy import ndimage as ndi
from sklearn.decomposition import PCA
import numpy as np
'''
@author <NAME>
@email <EMAIL>
'''
equalize = lambda img : exposure.equalize_adapthist(img, clip_limit=0.03)
def featureExtractionFBP(img):
len = 90
img = equalize(img)
img2=img[len:-len,len:-len]
img = frangi(img2)
hist, rr = np.histogram(img, bins=100)
img = img > rr[10]
img = erosion(img, square(3))
label_objects, nb_labels = ndi.label(img)
sizes = np.bincount(label_objects.ravel())
sizes[0]=0
mask_sizes = sizes >= 400#np.max(sizes) #& (sizes<40000)#((np.max(sizes)+np.mean(sizes))*0.3)
filled_cleaned = mask_sizes[label_objects]
img1 = erosion(sobel(filled_cleaned)>0,square(2))
img3 = sobel(img2)
img2 = img3>0.1
img2 = erosion(img2,square(2))
kp =[]
for idx, ii in enumerate(img2):
for idxy, jj in enumerate(ii):
if jj:
kp.extend([[idx,idxy]])
kp=np.array(kp)
cp = np.mean(kp,axis=0)
feature = []
bins = 10
points_img1=[]
for idxx, i in enumerate(img1):
for idxy, val in enumerate(i):
if val:
points_img1.extend([[idxx,idxy]])
points_img1 = np.array(points_img1)
dist_p1 = np.sqrt(np.sum((points_img1-cp)**2,axis=1))
hist1_img1, _ = np.histogram(dist_p1, bins=bins,
range=(0,220),
density=True)
feature.extend(hist1_img1)
feature.extend([np.var(dist_p1)])
reduced_data = PCA(n_components=1).fit_transform(points_img1)
hist2_img1, _ = np.histogram(reduced_data, bins=bins,
density=True)
feature.extend(hist2_img1)
return np.array(feature)
def featureExtractionTP(img):
img2 = equalize(img)
len=90
img2=img2[len:-len,len:-len]
img3 = sobel(img2)
img2 = img3>0.1
img2 = erosion(img2,square(2))
kp =[]
for idx, ii in enumerate(img2):
for idxy, jj in enumerate(ii):
if jj:
kp.extend([[idx,idxy]])
kp=np.array(kp)
cp = np.mean(kp,axis=0)
dist1 = np.sqrt(np.sum((kp-cp)**2,axis=1))
hist,_ = np.histogram(dist1,bins=22,range=(0,220), density=True)
reduced_data = PCA(n_components=1).fit_transform(kp)
hist2_img1, _ = np.histogram(reduced_data, bins=22,
density=True)
hist = np.append(hist,hist2_img1)
return np.append(hist,[np.mean(img2)])
|
0cb51425eb3790a66ec345abfc61dbccc1e06ea9
|
[
"Markdown",
"Python"
] | 5
|
Python
|
imksuma/AutomatedEmbryoPrediction
|
b5709adb3b1c17fd02458c8e1147f86b8275ae4a
|
645ddbf3c46a5ba1bc43f7fc87f1da68c3bfe79f
|
refs/heads/master
|
<repo_name>jdedea/bien<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :reviews
root "reviews#index"
end
|
5555b49f5a19bb5b3ef1c58730386ca28abb5e7b
|
[
"Ruby"
] | 1
|
Ruby
|
jdedea/bien
|
c11745b941af61f1fa1f7e04ca92deb95ae494d2
|
d603ad47cb84d023986474246b37c9cb5e8e4710
|
refs/heads/main
|
<file_sep>// Below is a function that returns a promise that is empty at this time.
// If data isn't a number, return a promise rejected instantly and give the data "error" (in a string)
// If data is an odd number, return a promise resolved 1 second later and give the data "odd" (in a string)
// If data is an even number, return a promise rejected 2 seconds later and give the data "even" (in a string)
// Function to return a promise
function newJob(data) {
return new Promise((resolve, reject) => {
});
}
// To check output with string input, expect promise to be rejected
let strCheck = newJob('Oops');
strCheck.then((data) => {
console.log("That's not right, data: ", data)
})
.catch((data) => {
console.log("Nicely done.")
});
// To check output with odd number input, expect promise to resolve after 1 second
let oddCheck = newJob(7);
oddCheck.then((data) => {
console.log('Nicely done. Check for timing.')
}).catch((data) => {
console.log("That's not right, data: ", data)
})
// To check output with even number input, expect promise to be rejected after 2 seconds
let evenCheck = newJob(2);
evenCheck.then((data) => {
console.log("That's not right, data: ", data)
}).catch((data) => {
console.log('Nicely done. Check for timing.')
});
|
4a8e66a8003b68064e4d4f40bee45bf7e7e03132
|
[
"JavaScript"
] | 1
|
JavaScript
|
roesnera/PromisePracticeProject
|
11f08e80bc4ffd5e4a6ce971b62758cfe2829b2e
|
bee7c95e56902f2a407d1d7760a4033c0dd9e924
|
refs/heads/master
|
<file_sep># Demo managed application for Azure
* `README.md` is this file
* `deploy-base.sh` deploys the storage account for all the zips
* `release-appdef-package.sh` deploys the zip that tells the managed app what to do
* `release-function-app-package.sh` deploys the zip for the Function App
* Not implemented at this time
* `demoappdef/` deploys an app definition
* Requires URI of app def package as input
* `demoappdef/package/` contains JSON for the app's portal UI and ARM for the managed resources
* It needs to be zipped and pushed to blob storage, and the URI of that package given to `demoappdef/`
* `testapp/` deploys an instance of the managed application
* Requires app def ARM ID as input
<file_sep>#!/bin/bash
set -e
resource_group_name=mgdapppoc1
storage_account_name=mgdapppoc1
blob_container_name=appdef
az storage account create -g "$resource_group_name" -n "$storage_account_name" -l australiaeast --sku Standard_LRS
az storage container create --account-name "$storage_account_name" -n "$blob_container_name" --only-show-errors
<file_sep>#!/bin/bash
set -e
resource_group_name=mgdapppoc1
storage_account_name=mgdapppoc1
blob_container_name=appdef
appdef_package_name=foom
# Zip
(cd demoappdef/package; zip ../../appdef-package.zip -r .)
# Upload
az storage blob upload --account-name "$storage_account_name" --container-name "$blob_container_name" -n "${appdef_package_name}appdef.zip" -f appdef-package.zip --only-show-errors
# Get blob URI and print for use in application definition
url="$(az storage blob url --account-name "$storage_account_name" --container-name "$blob_container_name" -n "${appdef_package_name}appdef.zip" --only-show-errors -o tsv)"
echo "$url"
|
e87f0c96668c673ddaafe969584c67a4f9cd4084
|
[
"Markdown",
"Shell"
] | 3
|
Markdown
|
pacon-vib/azure-managed-application-demo
|
049c83a16689acffdfe30cf3e249fe017179e888
|
e5518b646fbd7ed1aae094c03ccbac88554f6c1d
|
refs/heads/master
|
<file_sep># PizzApp
PizzApp Full JS API NodeJs
## Démarrage
Veuillez suivre les recommendations suivantes pour installer le projet sur votre environnement
### Pré-requis
[Node.js](https://nodejs.org/en/download/) 8.8+.
[MongoDB](https://www.mongodb.com/download).
### Installation
Cloner ce repo sur votre environnement
Installer les modules
```
npm i
```
Puis démarrer le serveur
```
npm server.js
```
## Lancer les Tests unitaires
```
npm test
```
## Autheur
**<NAME>** - <EMAIL>
## Licence
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
<file_sep><!DOCTYPE html>
<html>
<head>
<title>server.js</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<link rel="stylesheet" media="all" href="docco.css" />
</head>
<body>
<div id="container">
<div id="background"></div>
<ul id="jump_to">
<li>
<a class="large" href="javascript:void(0);">Jump To …</a>
<a class="small" href="javascript:void(0);">+</a>
<div id="jump_wrapper">
<div id="jump_page_wrapper">
<div id="jump_page">
<a class="source" href="appSpec.html">
appSpec.js
</a>
<a class="source" href="ingredientController.html">
ingredientController.js
</a>
<a class="source" href="pizzaController.html">
pizzaController.js
</a>
<a class="source" href="userController.html">
userController.js
</a>
<a class="source" href="controllersSpec.html">
controllersSpec.js
</a>
<a class="source" href="mainTest.html">
mainTest.js
</a>
<a class="source" href="ingredient.html">
ingredient.js
</a>
<a class="source" href="pizza.html">
pizza.js
</a>
<a class="source" href="user.html">
user.js
</a>
<a class="source" href="server.html">
server.js
</a>
</div>
</div>
</li>
</ul>
<ul class="sections">
<li id="title">
<div class="annotation">
<h1>server.js</h1>
</div>
</li>
<li id="section-1">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-1">¶</a>
</div>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-meta">'use strict'</span>
<span class="hljs-comment">/**
* @file server.js
* @desc Point d'entrée de l'application 'PizzApp'. <br />
* L'application PizzApp permet de gérer une carte des Pizzas.
* Date de Création 20/10/2017 <br />
* Date de modification 20/10/2017 <br />
*
* @version Alpha 1.0.0
*
* @author <NAME> <<EMAIL>>
*
*/</span>
<span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>;
<span class="hljs-keyword">const</span> config = <span class="hljs-built_in">require</span>(<span class="hljs-string">'config'</span>);
<span class="hljs-keyword">let</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">let</span> app = express();
<span class="hljs-keyword">let</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">let</span> server = http.Server(app);
<span class="hljs-keyword">let</span> io = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>)(server);
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'body-parser'</span>);</pre></div></div>
</li>
<li id="section-2">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-2">¶</a>
</div>
<p>CONTROLEURS</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-keyword">const</span> pizzaController = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./controllers/pizzaController'</span>);
<span class="hljs-keyword">const</span> ingredientController = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./controllers/ingredientController'</span>);</pre></div></div>
</li>
<li id="section-3">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-3">¶</a>
</div>
<p>Pour ouvrir l’API (cross origin) IP acceptée</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-keyword">const</span> cors = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>);
<span class="hljs-keyword">let</span> options = {
<span class="hljs-attr">server</span>: { <span class="hljs-attr">socketOptions</span>: { <span class="hljs-attr">keepAlive</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">connectTimeoutMS</span>: <span class="hljs-number">30000</span> } },
<span class="hljs-attr">replset</span>: { <span class="hljs-attr">socketOptions</span>: { <span class="hljs-attr">keepAlive</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">connectTimeoutMS</span> : <span class="hljs-number">30000</span> } }
};</pre></div></div>
</li>
<li id="section-4">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-4">¶</a>
</div>
<p>Database Connection</p>
</div>
<div class="content"><div class='highlight'><pre>mongoose.connect(config.DBHost, options);
<span class="hljs-keyword">let</span> db = mongoose.connection;
db.on(<span class="hljs-string">'error'</span>, () => {
<span class="hljs-built_in">console</span>.error.bind(<span class="hljs-built_in">console</span>, <span class="hljs-string">'connection error:'</span>);
process.exit(<span class="hljs-number">1</span>);
}
);</pre></div></div>
</li>
<li id="section-5">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-5">¶</a>
</div>
<p>CONF</p>
</div>
<div class="content"><div class='highlight'><pre>app.use(bodyParser.json({<span class="hljs-attr">limit</span>: <span class="hljs-string">'25mb'</span>}));
app.use(bodyParser.urlencoded({<span class="hljs-attr">extended</span>: <span class="hljs-literal">true</span>}, {<span class="hljs-attr">limit</span>: <span class="hljs-string">'25mb'</span>}));
app.use(cors());</pre></div></div>
</li>
<li id="section-6">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-6">¶</a>
</div>
<p>var node permettant d’avoir le fichier courant</p>
</div>
<div class="content"><div class='highlight'><pre>app.use(express.static(path.join(__dirname, <span class="hljs-string">'View'</span>)));
app.use(<span class="hljs-string">'/ingredients'</span>, ingredientController);
app.use(<span class="hljs-string">'/pizzas'</span>, pizzaController);
server.listen(port,() => {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Starting WebServer at <span class="hljs-subst">${port}</span>`</span>);
});</pre></div></div>
</li>
<li id="section-7">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-7">¶</a>
</div>
<p>Export du module io</p>
</div>
<div class="content"><div class='highlight'><pre>global.io = io;
<span class="hljs-built_in">module</span>.exports = app;</pre></div></div>
</li>
</ul>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<html>
<head>
<title>ingredientController.js</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<link rel="stylesheet" media="all" href="docco.css" />
</head>
<body>
<div id="container">
<div id="background"></div>
<ul id="jump_to">
<li>
<a class="large" href="javascript:void(0);">Jump To …</a>
<a class="small" href="javascript:void(0);">+</a>
<div id="jump_wrapper">
<div id="jump_page_wrapper">
<div id="jump_page">
<a class="source" href="appSpec.html">
appSpec.js
</a>
<a class="source" href="ingredientController.html">
ingredientController.js
</a>
<a class="source" href="pizzaController.html">
pizzaController.js
</a>
<a class="source" href="userController.html">
userController.js
</a>
<a class="source" href="controllersSpec.html">
controllersSpec.js
</a>
<a class="source" href="mainTest.html">
mainTest.js
</a>
<a class="source" href="ingredient.html">
ingredient.js
</a>
<a class="source" href="pizza.html">
pizza.js
</a>
<a class="source" href="user.html">
user.js
</a>
<a class="source" href="server.html">
server.js
</a>
</div>
</div>
</li>
</ul>
<ul class="sections">
<li id="title">
<div class="annotation">
<h1>ingredientController.js</h1>
</div>
</li>
<li id="section-1">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-1">¶</a>
</div>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-meta">'use strict'</span>;
<span class="hljs-comment">/**
* Ingredients' controller.
* @namespace IngredientController
*/</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> router = express.Router();
<span class="hljs-keyword">const</span> Ingredient = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../models/ingredient'</span>);</pre></div></div>
</li>
<li id="section-2">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-2">¶</a>
</div>
<p><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong>**</strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong> //
ROUTES //
<strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong>**</strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong> //</p>
</div>
<div class="content"><div class='highlight'><pre>router.get(<span class="hljs-string">'/'</span>, (req, res, next) => {
getIngredients(req, res, next);
});
router.get(<span class="hljs-string">'/:id'</span>, (req, res, next) => {
getIngredientById(req, res, next);
});
router.post(<span class="hljs-string">'/'</span>, (req, res, next) => {
postIngredient(req, res, next);
});
router.put(<span class="hljs-string">'/:id'</span>, (req, res, next) => {
putIngredient(req, res, next);
});
router.delete(<span class="hljs-string">'/:id'</span>, (req, res, next) => {
deleteIngredient(req, res, next);
});</pre></div></div>
</li>
<li id="section-3">
<div class="annotation">
<div class="pilwrap ">
<a class="pilcrow" href="#section-3">¶</a>
</div>
<p><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong>**</strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong> //
FONCTIONS //
<strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong><strong>**</strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong></strong> //</p>
</div>
<div class="content"><div class='highlight'><pre><span class="hljs-comment">/**
* Find all ingredients
*
* @function getIngredients
* @memberof IngredientController
* @param {Object} req - Request object.
* @param {Object} res - Response object.
* @returns {Promise.<void>} Call res.status() with a status code to say what happens and res.json() to send data if there is any.
*/</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getIngredients</span>(<span class="hljs-params">req, res, next</span>)</span>{
Ingredient.find({ <span class="hljs-string">'deleted'</span>: <span class="hljs-literal">false</span> },(err, ingredient) => {
<span class="hljs-keyword">if</span> (err) {
res.status(<span class="hljs-number">500</span>).send(err);
} <span class="hljs-keyword">else</span> {
res.status(<span class="hljs-number">200</span>).send(ingredient);
}
});
}
<span class="hljs-comment">/**
* Find ingredient by ID
*
* @function getIngredientById
* @memberof IngredientController
* @param {Object} req - Request object.
* @param {string} req.params.id - Ingredient's ID to find.* @param {Object} res - Response object.
* @returns {Promise.<void>} Call res.status() with a status code to say what happens and res.json() to send data if there is any.
*/</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getIngredientById</span>(<span class="hljs-params">req, res, next</span>)</span>{
Ingredient.findById(req.params.id, (err, ingredient) => {
<span class="hljs-keyword">if</span> (err) {
res.status(<span class="hljs-number">500</span>).send(err)
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ingredient === <span class="hljs-literal">null</span>) {
res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">`Aucun ingredient trouvé avec cet identifiant...`</span>);
} <span class="hljs-keyword">else</span> {
res.status(<span class="hljs-number">200</span>).send(ingredient);
}
});
}
<span class="hljs-comment">/**
* Post new Ingredient
*
* @function postIngredient
* @memberof IngredientController
* @param {Object} req - Request object.
* @param {string} req.params.id - Ingredient's ID to find.
* @param {string} req.query.name - Ingredient's name to query.
* @param {string} req.query.description - Ingredient's description to query.
* @param {string} req.query.price - Ingredient's price to query.
* @param {string} req.query.img - Ingredient's image to query.
* @param {Object} res - Response object.
* @returns {Promise.<void>} Call res.status() with a status code to say what happens and res.json() to send data if there is any.
*/</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">postIngredient</span>(<span class="hljs-params">req, res, next</span>)</span>{
<span class="hljs-keyword">const</span> ingredient = <span class="hljs-keyword">new</span> Ingredient(req.body);
ingredient.save(<span class="hljs-function">(<span class="hljs-params">err, pizza</span>) =></span> {
<span class="hljs-keyword">if</span> (err) {
res.status(<span class="hljs-number">500</span>).send(err);
}
res.status(<span class="hljs-number">200</span>).send(pizza);
});
}
<span class="hljs-comment">/**
* Put Ingredient
*
* @function putIngredient
* @memberof IngredientController
* @param {Object} req - Request object.
* @param {string} req.params.id - Ingredient's ID to update.
* @param {string} req.query.name - Ingredient's name to query.
* @param {string} req.query.description - Ingredient's description to query.
* @param {string} req.query.weight - Ingredient's weight to query.
* @param {string} req.query.price - Ingredient's price to query.
* @param {string} req.query.img - Ingredient's image to query.
* @param {Object} res - Response object.
* @returns {Promise.<void>} Call res.status() with a status code to say what happens and res.json() to send data if there is any.
*/</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">putIngredient</span>(<span class="hljs-params">req, res, next</span>)</span>{
<span class="hljs-keyword">let</span> ingredient = {};
ingredient.name = req.body.name || ingredient.name;
ingredient.weight = req.body.weight || ingredient.weight;
ingredient.description = req.body.description || ingredient.description;
ingredient.img = req.body.img || ingredient.img;
ingredient.price = req.body.price || ingredient.price;
ingredient.deleted = req.body.deleted || ingredient.deleted;
ingredient.updated_at = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>;
Ingredient.findOneAndUpdate({<span class="hljs-attr">_id</span>: req.params.id}, ingredient, { <span class="hljs-attr">new</span>: <span class="hljs-literal">true</span> }, (err, ingredient) => {
<span class="hljs-keyword">if</span> (err) {
res.status(<span class="hljs-number">500</span>).send(err);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ingredient === <span class="hljs-literal">null</span>) {
res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">'Aucun ingredient trouvé avec cet Identifiant...'</span>);
} <span class="hljs-keyword">else</span> {
res.status(<span class="hljs-number">200</span>).send(ingredient);
}
});
}
<span class="hljs-comment">/**
* Delete Ingredient
*
* @function deleteIngredient
* @memberof IngredientController
* @param {Object} req - Request object.
* @param {Object} res - Response object.
* @returns {Promise.<void>} Call res.status() with a status code to say what happens and res.json() to send data if there is any.
*/</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">deleteIngredient</span>(<span class="hljs-params">req, res, next</span>)</span>{
Ingredient.findByIdAndRemove(req.params.id, (err, ingredient) => {
<span class="hljs-keyword">if</span> (err) {
res.status(<span class="hljs-number">500</span>).send(err);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ingredient === <span class="hljs-literal">null</span>) {
res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">`Aucun ingredient trouvé avec cet identifiant...`</span>);
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">let</span> response = {
<span class="hljs-attr">message</span>: <span class="hljs-string">`L'ingredient <span class="hljs-subst">${req.params.id}</span> a été correctement supprimé`</span>,
<span class="hljs-attr">ingredient</span>: ingredient
};
res.status(<span class="hljs-number">200</span>).send(response);
}
next();
});
}
<span class="hljs-built_in">module</span>.exports = router;</pre></div></div>
</li>
</ul>
</div>
</body>
</html>
<file_sep>'use strict';
process.env.NODE_ENV = 'test';
require('./test/pizzaControllerSpec.js');
require('./test/ingredientControllerSpec.js');<file_sep>'use strict';
const mongoose = require('mongoose');
const server = require('../server');
const ingredientSchema = require('../models/ingredient');
const mocha = require('mocha');
const chai = require('chai');
const chaiHttp = require('chai-http');
const should = chai.should();
chai.use(chaiHttp);
describe('Ingredient', () => {
beforeEach((done) => {
ingredientSchema.remove({}, () => {
done();
});
});
describe('Get All Ingredient', () => {
it('it should GET all the ingredients', (done) => {
chai.request(server)
.get('/ingredients')
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('array');
res.body.length.should.be.eql(0);
done();
});
});
});
describe('Return ingredient after insert', () => {
it('it should Return ingredient after insert', (done) => {
const ingredient = new ingredientSchema({
name: "poulet",
price: 3
});
ingredient.save((err, ingredient) => {
chai.request(server)
.get('/ingredients/' + ingredient._id)
.send(ingredient)
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('name');
res.body.should.have.property('price');
res.body.should.have.property('_id').eql(`${ingredient._id}`);
done();
});
});
});
});
describe('Create Ingredient', () => {
it('it should not POST an ingredient without the missing property', (done) => {
let ingredient = {
name: "poulet",
description: "Du bon poulet sa mère !"
};
chai.request(server)
.post('/ingredients')
.send(ingredient)
.end((err, res) => {
res.should.have.status(500);
res.body.should.be.a('object');
res.body.should.have.property('errors');
// Vérification d'une propriété non transmise
res.body.errors.should.have.property('price');
done();
});
});
it('it should POST an ingredient ', (done) => {
let ingredient = {
name: "poulet",
price : 3,
description: "Du bon poulet sa mère !"
};
chai.request(server)
.post('/ingredients')
.send(ingredient)
.end((err, res) => {
// console.log(res.body);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('name');
res.body.should.have.property('price');
res.body.should.have.property('description');
done();
});
});
});
describe('Update Ingredient', () => {
it('it should UPDATE a ingredient', (done) => {
let ingredient = new ingredientSchema({
name: "Poulet",
weight: "21Kg",
price: 4
});
ingredient.save((err, ingredient) => {
chai.request(server)
.put('/ingredients/' + ingredient._id)
.send({name: "Coq", price: 3})
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('name').eql("Coq");
res.body.should.have.property('price').eql('3');
done();
});
});
});
});
describe('Delete Ingredient', () => {
it('it should DELETE a ingredient', (done) => {
let ingredient = new ingredientSchema({
name: "Poulet",
weight: "10Kg",
price: 5
});
ingredient.save((err, ingredient) => {
chai.request(server)
.delete('/ingredients/' + ingredient._id)
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.ingredient.should.have.property('_id').eql(`${ingredient._id}`);
done();
});
});
});
});
});
<file_sep>'use strict';
/**
* Pizzas' controller.
* @namespace PizzaController
*/
const express = require('express');
const router = express.Router();
const Pizza = require('../models/pizza');
// ************************************************************************** //
// ROUTES //
// ************************************************************************** //
router.get('/', (req, res, next) => {
getPizzas(req, res, next);
});
router.get('/:id', (req, res, next) => {
getPizzaById(req, res, next);
});
router.post('/', (req, res, next) => {
postPizza(req, res, next);
});
router.put('/:id', (req, res, next) => {
putPizza(req, res, next);
});
router.delete('/:id', (req, res, next) => {
deletePizza(req, res, next);
});
// ************************************************************************** //
// FONCTIONS //
// ************************************************************************** //
/**
* Find all pizzas
*
* @function getPizzas
* @memberof PizzaController
* @param {Object} req - Request object.
* @param {Object} res - Response object.
* @returns {Promise.<void>} Call res.status() with a status code to say what happens and res.json() to send data if there is any.
*/
function getPizzas(req, res, next){
Pizza.find((err, pizza) => {
if (err) {
res.status(500).send(err)
} else {
res.status(200).send(pizza);
}
}).sort({created_at: 'desc'}).populate({
path: 'ingredients',
match: { deleted: false }
}).exec(function (err, story) {
if (err) return console.log(err);
});
}
/**
* Get Pizza By Id
*
* @function getPizzaById
* @memberof PizzaController
* @param {Object} req - Request object.
* @param {string} req.params.id - Pizza's ID to find.
* @param {Object} res - Response object.
* @returns {Promise.<void>} Call res.status() with a status code to say what happens and res.json() to send data if there is any.
*/
function getPizzaById(req, res, next){
Pizza.findById(req.params.id, (err, pizza) => {
if (err) {
res.status(500).send(err)
} else if (pizza === null) {
res.status(404).send('Pas de pizza trouvé avec cet Identifiant...')
} else {
res.status(200).send(pizza)
}
}).populate({
path: 'ingredients',
match: { deleted: false }
}).exec(function (err, story) {
if (err) return console.log(err);
});
}
/**
* Post new Pizza
*
* @function postPizza
* @memberof PizzaController
* @param {Object} req - Request object.
* @param {string} req.params.id - Pizza's ID to find.
* @param {string} req.query.name - Pizza's name to query.
* @param {string} req.query.description - Pizza's description to query.
* @param {string} req.query.price - Pizza's price to query.
* @param {string} req.query.img - Pizza's image to query.
* @param {Object} res - Response object.
* @returns {Promise.<void>} Call res.status() with a status code to say what happens and res.json() to send data if there is any.
*/
function postPizza(req, res, next){
const pizza = new Pizza(req.body);
pizza.save((err, pizza) => {
if (err) {
res.status(500).send(err);
} else {
res.status(200).send(pizza);
// SOCKET
global.io.emit('[Pizza][post]', pizza);
global.io.emit('[Toast][new]', {type: 'success', title: `Nouvelle Pizza`, message: 'Une nouvelle pizza a été ajoutée !'});
}
});
}
/**
* Put Pizza
*
* @function putPizza
* @memberof PizzaController
* @param {Object} req - Request object.
* @param {string} req.params.id - Pizza's ID to update.
* @param {string} req.query.name - Pizza's name to query.
* @param {string} req.query.description - Pizza's description to query.
* @param {string} req.query.price - Pizza's price to query.
* @param {string} req.query.img - Pizza's image to query.
* @param {Object} res - Response object.
* @returns {Promise.<void>} Call res.status() with a status code to say what happens and res.json() to send data if there is any.
*/
function putPizza(req, res, next){
var pizza = {};
pizza.name = req.body.name || pizza.name;
pizza.img = req.body.img || pizza.img;
pizza.description = req.body.description || pizza.description;
pizza.price = req.body.price || pizza.price;
pizza.updated_at = new Date;
pizza.ingredients = req.body.ingredients || pizza.ingredients;
Pizza.findOneAndUpdate({_id: req.params.id}, pizza, { new: true }, (err, pizza) => {
if (err) {
res.status(500).send(err);
} else if (pizza === null) {
res.status(404).send('Pas de pizza trouvé avec cet Identifiant...');
} else {
res.status(200).send(pizza);
// SOCKET
global.io.emit('[Pizza][put]', pizza);
global.io.emit('[Toast][new]', {type: 'warning', title: `Pizza ${pizza.name} améliorée`, message: 'Découvrez les améliorations !'});
}
});
}
/**
* Delete Pizza
*
* @function deletePizza
* @memberof PizzaController
* @param {Object} req - Request object.
* @param {Object} res - Response object.
* @returns {Promise.<void>} Call res.status() with a status code to say what happens and res.json() to send data if there is any.
*/
function deletePizza(req, res, next){
Pizza.findByIdAndRemove(req.params.id, (err, pizza) => {
if (err) {
res.status(500).send(err);
} else if (pizza === null) {
res.status(404).send('Aucune pizza trouvée avec cet identifiant...');
} else {
let response = {
message: `La pizza ${req.params.id} a été correctement supprimée`,
pizza: pizza
};
res.status(200).send(response);
// SOCKET
global.io.emit('[Pizza][delete]', pizza);
global.io.emit('[Toast][new]', {type: 'error', title: `La pizza ${pizza.name} indisponible`, message: `Trop tard, la pizza n'est plus diposnible !`});
}
});
}
module.exports = router;<file_sep>'use strict';
const mongoose = require('mongoose');
const server = require('../server');
const pizzaSchema = require('../models/pizza');
const mocha = require('mocha');
const chai = require('chai');
const chaiHttp = require('chai-http');
const should = chai.should();
chai.use(chaiHttp);
describe('Pizza', () => {
beforeEach((done) => {
pizzaSchema.remove({}, () => {
console.log('Clean collection');
done();
});
});
describe('Get All Pizza', () => {
it('it should GET all the pizzas', (done) => {
chai.request(server)
.get('/pizzas')
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('array');
res.body.length.should.be.eql(0);
Object.keys(res.body).length.should.to.eql(0);
done();
});
});
});
describe('Create Pizza', () => {
it('it should not POST a pizza without the missing property', (done) => {
let pizza = {
// name: "test",
description: "Une incroyable pizza !!",
price: 2900,
img: "dfgdf",
ingredients: []
};
chai.request(server)
.post('/pizzas')
.send(pizza)
.end((err, res) => {
res.should.have.status(500);
res.body.should.be.a('object');
res.body.should.have.property('errors');
res.body.errors.should.have.property('name');
res.body.errors.name.should.have.property('kind').eql('required');
done();
});
});
it('it should POST a pizza ', (done) => {
let pizza = {
name: "Reine",
description: "La meilleure pizza",
price: 15,
img : "nothing",
ingredients: []
};
chai.request(server)
.post('/pizzas')
.send(pizza)
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('name');
res.body.should.have.property('description');
res.body.should.have.property('price');
res.body.should.have.property('img');
res.body.should.have.property('ingredients');
done();
});
});
});
describe('Get By Id', () => {
it('it should GET a pizza by the given id', (done) => {
let pizza = new pizzaSchema({ name: "maxipizza", description: "Une grosse pizza pour les gros mangeurs", price: 1954, img: "ggguyg", ingredients: [] });
pizza.save((err, pizza) => {
chai.request(server)
.get('/pizzas/' + pizza.id)
.send(pizza)
.end((err, res) => {
// console.log(res.body);
// console.log(pizza.id);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('name');
res.body.should.have.property('description');
res.body.should.have.property('price');
res.body.should.have.property('ingredients');
res.body.should.have.property('_id').eql(pizza.id);
done();
});
});
});
});
describe('PUT Pizza', () => {
it('it should UPDATE a pizza', (done) => {
let pizza = new pizzaSchema({
name: "Reine",
description: "La meilleure Pizza",
price: 15,
img: "ihbiu",
ingredients: []
});
pizza.save((err, pizza) => {
chai.request(server)
.put('/pizzas/' + pizza.id)
.send({description: "Une très bonne pizza", price: 18})
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('price').eql('18');
res.body.should.have.property('description').eql("Une très bonne pizza");
done();
});
});
});
});
describe('Delete Pizza', () => {
it('it should DELETE a pizza', (done) => {
let pizza = new pizzaSchema({
name: "Reine",
description: "Une magnifique pizza",
price: 855,
img: "ihbiu",
ingredients: []
});
pizza.save((err, pizza) => {
chai.request(server)
.delete('/pizzas/' + pizza._id)
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
done();
});
});
});
});
});
|
faafe853ea829948f24801029bfaa85568ccd3d9
|
[
"Markdown",
"JavaScript",
"HTML"
] | 7
|
Markdown
|
GuilhemSirop/nodejs-api
|
3fc107e93a08229a5d11c08875f088b177a16cf0
|
ac9c6ecd37d665f30230abcc3558dcf18f07bb96
|
refs/heads/master
|
<file_sep>namespace Soonoo.Services {
}
<file_sep>namespace Reversi.Services {
}
<file_sep>namespace Hnefatafl.Services {
}
<file_sep>namespace ChineseCheckers.Services {
}
<file_sep>namespace Mancala.Services {
}
<file_sep>namespace Passalch.Services {
}
<file_sep>namespace SpiderSolitaire.Services {
}
<file_sep>namespace Sokoban.Services {
}
<file_sep>namespace Hextris.Services {
}
<file_sep>namespace Hexxagon.Services {
}
<file_sep>namespace Checkers.Services {
}
<file_sep>namespace CarChamp.Services {
}
<file_sep>namespace Monaco.Services {
}
<file_sep>namespace Backgammon.Services {
}
<file_sep>namespace Abalone.Services {
}
|
c99ec58785bec5b48aa39dd7a794b534988969a4
|
[
"TypeScript"
] | 15
|
TypeScript
|
EdMacall/tenohnatul
|
2970beea0fd4cd25f71260b99f310b81c5225551
|
5eb227f57154d9b90634ec8c53ff243a0813a202
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <complex.h>
#include <string>
#include <stdexcept>
#include <math.h>
#include "solver.hpp"
namespace solver
{
using namespace std;
const RealVariable operator*(const RealVariable &x, const RealVariable &y)
{
return RealVariable(x._a * y._c + y._a * x._c + x._b * y._b, x._b * y._c + x._c * y._b, x._c * y._c);
}
const RealVariable operator-(const RealVariable &x, const RealVariable &y)
{
return RealVariable(x._a - y._a, x._b - y._b, x._c - y._c);
}
const RealVariable operator/(const RealVariable &x, double n)
{
if (n == 0)
throw std::out_of_range{"empty word cant be find"};
return RealVariable(x._a / n, x._b / n, x._c / n);
}
const RealVariable operator^(const RealVariable &x, int pow)
{
if (pow == 1)
return x;
if (pow == 0)
return 1;
pow--;
return x * (x ^ pow);
}
const RealVariable operator==(const RealVariable &x, const RealVariable &y)
{
return RealVariable(x - y);
}
const RealVariable operator+(const RealVariable &x, const RealVariable &y)
{
return RealVariable(x._a + y._a, x._b + y._b, x._c + y._c);
}
double solve(const RealVariable &y)
{
double a = y.a();
double b = y.b();
double c = y.c();
if (a == 0)
{
if (b == 0)
__throw_logic_error("try divid by 0");
return (-c / b);
return double(-c / b);
}
else
{
if (double(std::pow(b, 2) - double(double(4 * a) * c)) < 0)
__throw_logic_error("no real root");
return double((-b + sqrt(double(std::pow(b, 2) - double(double(4 * a) * c))))) / double(2 * a);
}
}
const ComplexVariable operator*(const ComplexVariable &x, const ComplexVariable &y)
{
return ComplexVariable(x._a * y._c + y._a * x._c + x._b * y._b, x._b * y._c + x._c * y._b, x._c * y._c);
}
const ComplexVariable operator/(const ComplexVariable &x, double n)
{
if (n == 0)
throw std::out_of_range{"mmm"};
return ComplexVariable(x._a / n, x._b / n, x._c / n);
}
const ComplexVariable operator-(const ComplexVariable &x, const ComplexVariable &y)
{
return ComplexVariable(x._a - y._a, x._b - y._b, x._c - y._c);
}
const ComplexVariable operator^(const ComplexVariable &x, int pow)
{
if (pow == 1)
return x;
if (pow == 0)
return 1;
pow--;
return x * (x ^ pow);
}
const ComplexVariable operator+(const ComplexVariable &x, const ComplexVariable &y)
{
return ComplexVariable(x._a + y._a, x._b + y._b, x._c + y._c);
}
const ComplexVariable operator==(const ComplexVariable &x, const ComplexVariable &y)
{
return ComplexVariable(x - y);
}
// const ComplexVariable operator-(const ComplexVariable &n) // TODO unary minus
// {
// return ComplexVariable(0);
// }
std::complex<double> solve(const ComplexVariable &y)
{
std::complex<double> a = y.a();
std::complex<double> b = y.b();
std::complex<double> c = y.c();
if (a.imag() == 0 && a.real() == 0)
{
if (b.imag() == 0 && b.real() == 0)
__throw_logic_error("try divid by 0");
return (-c / b);
}
else
{
return complex<double>(-b + sqrt(complex<double>(std::pow(b, 2) - complex<double>((complex<double>(a)) * 4.0 * c)))) / complex<double>(2.0 * a);
}
}
} // namespace solver<file_sep>#include "doctest.h"
#include <string>
#include "FamilyTree.hpp"
using namespace family;
using namespace std;
TEST_CASE("Test addMother")
{
family::Tree t("ori");
t.addMother("ori", "hana");
t.addMother("hana", "sara");
t.addMother("sara", "miriam");
t.addMother("miriam", "rivka");
t.addMother("rivka", "hadas");
CHECK(t.find("mother") == string("yosef"));
CHECK(t.find("grandmother") == string("yitzhak"));
CHECK(t.find("great-grandmother") == string("yaakov"));
CHECK(t.find("great-great-grandmother") == string("david"));
CHECK(t.find("great-great-great-grandmother") == string("nisim"));
}
TEST_CASE("Test addFather")
{
family::Tree t("ori");
t.addFather("ori", "yosef");
t.addFather("yosef", "yitzhak");
t.addFather("yitzhak", "yaakov");
t.addFather("yaakov", "david");
t.addFather("david", "nisim");
CHECK(t.find("father") == string("yosef"));
CHECK(t.find("grandfather") == string("yitzhak"));
CHECK(t.find("great-grandfather") == string("yaakov"));
CHECK(t.find("great-great-grandfather") == string("david"));
CHECK(t.find("great-great-great-grandfather") == string("nisim"));
}
TEST_CASE("Test find")
{
family::Tree t("ori");
t.addFather("ori", "yosef");
t.addMother("ori", "hana");
t.addFather("yosef", "yitzhak");
t.addMother("yosef", "sara");
t.addFather("yitzhak", "yaakov");
t.addMother("yitzhak", "miriam");
t.addFather("yaakov", "david");
t.addMother("yaakov", "keren");
t.addFather("david", "nisim");
t.addMother("david", "rivka");
CHECK_NOTHROW(t.find("father") );
CHECK_NOTHROW(t.find("mother") );
CHECK_NOTHROW(t.find("grandfather") );
CHECK_NOTHROW(t.find("grandmother") );
CHECK_NOTHROW(t.find("great-grandfather") );
CHECK_NOTHROW(t.find("great-grandmother") );
CHECK_NOTHROW(t.find("great-great-grandfather") );
CHECK_NOTHROW(t.find("great-great-grandmother") );
CHECK_NOTHROW(t.find("great-great-great-grandfather"));
CHECK_NOTHROW(t.find("great-great-great-grandmother") );
CHECK(t.find("father") == string("yosef"));
CHECK(t.find("mother") == string("hana"));
CHECK(t.find("grandfather") == string("yitzhak"));
CHECK(t.find("grandmother") == string("sara"));
CHECK(t.find("great-grandfather") == string("yaakov"));
CHECK(t.find("great-grandmother") == string("miriam"));
CHECK(t.find("great-great-grandfather") == string("david"));
CHECK(t.find("great-great-grandmother") == string("keren"));
CHECK(t.find("great-great-great-grandfather") == string("nisim"));
CHECK(t.find("great-great-great-grandmother") == string("rivka"));
CHECK_THROWS(t.find("uncle"));
CHECK_THROWS(t.find("aunt"));
CHECK_THROWS(t.find("son"));
CHECK_THROWS(t.find("daughter"));
CHECK_THROWS(t.find("brother"));
CHECK_THROWS(t.find("sister"));
CHECK_THROWS(t.find("nephew"));
CHECK_THROWS(t.find("niece"));
CHECK_THROWS(t.find("grand_mother"));
CHECK_THROWS(t.find("dad"));
CHECK_THROWS(t.find("mom"));
CHECK_THROWS(t.find("grandpa"));
CHECK_THROWS(t.find("grandad"));
CHECK_THROWS(t.find("grandma"));
CHECK_THROWS(t.find("Great grandmother"));
}
TEST_CASE("Test relation")
{
family::Tree t("ori");
t.addFather("ori", "yosef");
t.addMother("ori", "hana");
t.addFather("yosef", "yitzhak");
t.addMother("yosef", "sara");
t.addFather("yitzhak", "yaakov");
t.addMother("yitzhak", "miriam");
t.addFather("yaakov", "david");
t.addMother("yaakov", "keren");
t.addFather("david", "nisim");
t.addMother("david", "rivka");
CHECK_NOTHROW(t.relation("ori"));
CHECK_NOTHROW(t.relation("yosef"));
CHECK_NOTHROW(t.relation("hana"));
CHECK_NOTHROW(t.relation("yitzhak"));
CHECK_NOTHROW(t.relation("sara"));
CHECK_NOTHROW(t.relation("yaakov"));
CHECK_NOTHROW(t.relation("miriam"));
CHECK_NOTHROW(t.relation("david"));
CHECK_NOTHROW(t.relation("keren"));
CHECK_NOTHROW(t.relation("nisim"));
CHECK_NOTHROW(t.relation("rivka"));
CHECK(t.relation("yosef") == string("father"));
CHECK(t.relation("hana") == string("mother"));
CHECK(t.relation("yitzhak") == string("grandfather"));
CHECK(t.relation("sara") == string("grandmother"));
CHECK(t.relation("yaakov") == string("great-grandfather"));
CHECK(t.relation("miriam") == string("great-grandmother"));
CHECK(t.relation("david") == string("great-great-grandfather"));
CHECK(t.relation("keren") == string("great-great-grandmother"));
CHECK(t.relation("nisim") == string("great-great-great-grandfather"));
CHECK(t.relation("rivka") == string("great-great-great-grandmother"));
CHECK(t.relation("moshe") == string("unrelated"));
CHECK(t.relation("hadas") == string("unrelated"));
CHECK(t.relation("yoyo") == string("unrelated"));
CHECK(t.relation("jojo") == string("unrelated"));
CHECK(t.relation("ori") == string("me"));
}
TEST_CASE("Test remove")
{
family::Tree t("ori");
t.addFather("ori", "yosef");
t.addMother("ori", "hana");
t.addFather("yosef", "yitzhak");
t.addMother("yosef", "sara");
t.addFather("yitzhak", "yaakov");
t.addMother("yitzhak", "miriam");
t.addFather("yaakov", "david");
t.addMother("yaakov", "keren");
t.addFather("david", "nisim");
t.addMother("david", "rivka");
CHECK_NOTHROW(t.relation("ori"));
CHECK_NOTHROW(t.relation("yosef"));
CHECK_NOTHROW(t.relation("hana"));
CHECK_NOTHROW(t.relation("yitzhak"));
CHECK_NOTHROW(t.relation("sara"));
CHECK_NOTHROW(t.relation("yaakov"));
CHECK_NOTHROW(t.relation("miriam"));
CHECK_NOTHROW(t.relation("david"));
CHECK_NOTHROW(t.relation("keren"));
CHECK_NOTHROW(t.relation("nisim"));
CHECK_NOTHROW(t.relation("rivka"));
t.remove("david");
CHECK_NOTHROW(t.relation("keren"));
CHECK(t.relation("david") == string("unrelated"));
CHECK(t.relation("nisim") == string("unrelated"));
CHECK(t.relation("rivka") == string("unrelated"));
t.remove("yosef");
CHECK(t.relation("yosef") == string("unrelated"));
CHECK(t.relation("yitzhak") == string("unrelated"));
CHECK(t.relation("sara") == string("unrelated"));
CHECK(t.relation("yaakov") == string("unrelated"));
CHECK(t.relation("miriam") == string("unrelated"));
}
TEST_CASE("Test remove 2")
{
family::Tree t("ori");
t.addFather("ori", "yosef");
t.addMother("ori", "hana");
t.addFather("yosef", "yitzhak");
t.addMother("yosef", "sara");
t.addFather("yitzhak", "yaakov");
t.addMother("yitzhak", "miriam");
t.addFather("yaakov", "david");
t.addMother("yaakov", "keren");
t.addFather("david", "nisim");
t.addMother("david", "rivka");
t.remove("david");
CHECK_THROWS(t.relation("david"));
CHECK_THROWS(t.relation("nisim"));
CHECK_THROWS(t.relation("rivka"));
t.remove("yosef");
CHECK_THROWS(t.relation("yosef"));
CHECK_THROWS(t.relation("yitzhak"));
CHECK_THROWS(t.relation("sara"));
CHECK_THROWS(t.relation("yaakov"));
CHECK_THROWS(t.relation("miriam"));
}
TEST_CASE("father already exist- throw exeption")
{
family::Tree t("ori");
t.addFather("ori", "yosef");
CHECK_THROWS(t.addFather("ori", "moshe"));
}<file_sep>#pragma once
#include <iostream>
#include <complex.h>
namespace solver
{
using namespace std;
class RealVariable
{
private:
double _a, _b, _c;
public:
const double a() const
{
return _a;
}
const double b() const
{
return _b;
}
const double c() const
{
return _c;
}
RealVariable() : _a(0), _b(1), _c(0) {}
RealVariable(double a, double b, double c) : _a(a), _b(b), _c(c) {}
RealVariable(double c) : _a(0), _b(0), _c(c) {}
friend const RealVariable operator*(const RealVariable &x, const RealVariable &y);
friend const RealVariable operator/(const RealVariable &x, double n);
friend const RealVariable operator-(const RealVariable &x, const RealVariable &y);
friend const RealVariable operator^(const RealVariable &n, int pow);
friend const RealVariable operator==(const RealVariable &n, const RealVariable &m);
friend const RealVariable operator+(const RealVariable &n, const RealVariable &m);
};
class ComplexVariable
{
private:
std::complex<double> _a;
std::complex<double> _b;
std::complex<double> _c;
public:
const std::complex<double> a() const
{
return _a;
}
const std::complex<double> b() const
{
return _b;
}
const std::complex<double> c() const
{
return _c;
}
ComplexVariable() : _a(0), _b(1), _c(0) {}
ComplexVariable(const std::complex<double> a, const std::complex<double> b, const std::complex<double> c) : _a(a), _b(b), _c(c) {}
ComplexVariable(const std::complex<double> c) : _a(0), _b(0), _c(c) {}
ComplexVariable(double c) : _a(0), _b(0), _c(c) {}
friend const ComplexVariable operator*(const ComplexVariable &x, const ComplexVariable &y);
friend const ComplexVariable operator^(const ComplexVariable &n, int pow);
friend const ComplexVariable operator/(const ComplexVariable &x, double n);
friend const ComplexVariable operator-(const ComplexVariable &x, const ComplexVariable &y);
friend const ComplexVariable operator==(const ComplexVariable &n, const ComplexVariable &m);
friend const ComplexVariable operator+(const ComplexVariable &n, const ComplexVariable &m);
};
double solve(const RealVariable &x);
std::complex<double> solve(const ComplexVariable &y);
} // namespace solver
<file_sep>#include "doctest.h"
#include <string>
#include <complex>
#include "solver.hpp"
using namespace solver;
using namespace std;
TEST_CASE("solve linear")
{
RealVariable x;
CHECK(solve(5*x+4==24) == 4);
CHECK(solve(3*x+4-x==24) == 10);
CHECK(solve(2.5+2*x-x==24) == 21.5);
CHECK(solve(21.3+3*x==120.3) == 33);
CHECK(solve(4*x+8.7==88.7) == 20);
CHECK(solve(5*x+4==54) == 10);
CHECK(solve(3*x+4-x==92.8) == 44.4);
CHECK(solve(2.5+2*x-x==2.5) == 0);
CHECK(solve(21.3+33*x==120.3) == 3);
CHECK(solve(2*x+8.7==88.7) == 40);
ComplexVariable y;
CHECK(solve(5*y+4==24) == 4.0+0i);
CHECK(solve(3*y+4-y==24) == 10.0+0i);
CHECK(solve(2.5+2*y-y==24) == 21.5+0i);
CHECK(solve(21.3+3*y==120.3) == 33.0+0i);
CHECK(solve(4*y+8.7==88.7) == 20.0+0i);
CHECK(solve(5*y+4==24.0+10i) == 4.0+2i);
CHECK(solve(3*y+4-y-5i==24) == 10.0+2.5i);
CHECK(solve(2.5+2*y-y+3.4i==24) == 21.5-3.4i);
CHECK(solve(21.3+3*y==120.3) == 33.0+0i);
CHECK(solve(4*y+8.7==88.7) == 20.0+0i);
}
TEST_CASE("solve polynom")
{
RealVariable x;
CHECK(solve((x^2)-1==24) == 5);
CHECK(solve(2*(x^2)-1==199) == 10);
CHECK(solve(3*(x^2)==27) == 3);
CHECK(solve(2*(x^2)+4*x+2==0) == -1);
CHECK(solve(2*(x^2)+5*x+3==0) == -1);
ComplexVariable y;
CHECK(solve(2*(y^2)+2*y+1==0) == -(0.5)+0.5i);
CHECK(solve((y^2)+1==0) == 1i);
CHECK(solve(2.5+2*y-y==24) == 21.5+0i);
CHECK(solve(21.3+3*y==120.3) == 33.0+0i);
CHECK(solve(4*y+8.7==88.7) == 20.0+0i);
}
TEST_CASE("solve - throw aritmetic problem")
{
RealVariable x;
CHECK_THROWS(solve((x^2)==-16));
CHECK_THROWS(solve((x^2)==-1));
CHECK_THROWS(solve((x^2)-500==-1126));
CHECK_THROWS(solve((x^2)-3==-16));
CHECK_THROWS(solve((x^2)+70==-16));
CHECK_THROWS(solve((x^2)==-1.6));
CHECK_THROWS(solve((x^2)==-124253.2));
CHECK_THROWS(solve((x^2)-500==-1126.2));
CHECK_THROWS(solve((x^2)-3==-1612));
CHECK_THROWS(solve((x^2)+70==-1642.221));
CHECK_THROWS(solve((x^2)==-0.3));
CHECK_THROWS(solve((x^2)==-0.000999));
CHECK_THROWS(solve((x^2)-500==-2226));
CHECK_THROWS(solve((x^2)-3==-4));
CHECK_THROWS(solve((x^2)+70==-20));
CHECK_THROWS(solve((x^2)==-999));
CHECK_THROWS(solve((x^2)==-2.2));
CHECK_THROWS(solve((x^2)-500==-501));
CHECK_THROWS(solve((x^2)-3==-4));
CHECK_THROWS(solve((x^2)+70==69));
ComplexVariable y;
CHECK_THROWS(solve((y^2)==-16i));
CHECK_THROWS(solve((y^2)==-1i));
CHECK_THROWS(solve((y^2)-500==-1126i));
CHECK_THROWS(solve((y^2)-3==1i));
CHECK_THROWS(solve((y^2)+70==15i));
CHECK_THROWS(solve((y^2)==-1.6i));
CHECK_THROWS(solve((y^2)==0.2i));
CHECK_THROWS(solve((y^2)-500==52i));
CHECK_THROWS(solve((y^2)-3==4.3i));
CHECK_THROWS(solve((y^2)+70==-6.66666i));
}
TEST_CASE("real op+ ")
{
RealVariable x;
CHECK(x+5 == 7);
CHECK(x+x == 4);
CHECK(x+2+4 == 6);
CHECK(x+x+x+x == 8);
CHECK(12.5+x+3 == 17.5);
}
TEST_CASE("real op- ")
{
RealVariable x;
CHECK(x-5 == 7);
CHECK(x-1 == 1);
CHECK(x-2-4 == 6);
CHECK((x^2)-4 == 2);
CHECK(12.5-x-3 == 17.5);
CHECK(10-x == 10);
}
TEST_CASE("solve explict furmula")
{
RealVariable x;
CHECK(solve(x+5 ==0) ==-5.);
CHECK(solve(x-5==0)== 5.);
CHECK(solve((x^2)-4==0)== 2.);
CHECK(solve((x^2)-x==0) == 1.);
CHECK(solve(x+x==0) == 0.);
CHECK(solve(x+x*x -2*x ==0)== 1.);
CHECK(solve((x^2)-5==0) ==sqrt(5));
CHECK(solve(((x^2)+(x^2))/2 ==8)==2);
CHECK(solve(x==0)== 0);
CHECK(solve((2*x-2==0))== 2);
CHECK(solve(2*x-2==0) ==1 );
ComplexVariable y;
CHECK(solve(y+5 ==0) ==-5.+0i);
CHECK(solve(y+5 ==0) ==-5.);
CHECK(solve(y-5==0)== 5.);
CHECK(((solve((y^2)-4==0)== 2.)||(solve((y^2)-4==0)==-2.)));
CHECK(solve((y^2)-y==0) == -1.);
CHECK(solve(y+y==0) == 0.);
CHECK(solve(y+y*y -2*y ==0)== 1.);
CHECK(solve((y^2)-5==0) ==sqrt(5.));
CHECK(solve(((y^2)+(y^2))/2 ==8.)==2.);
CHECK(solve(y==0)== 0.);
CHECK(solve((2*y-2==0.))== 2.);
CHECK(solve(2*y-2==0.) ==1. );
CHECK(solve((y^2)-25.==0.+0i)==5.);
CHECK(solve(10*y-10i==0.) == 0.+1i);
CHECK(solve((y^2)+1.==0.)==0.+1i);
CHECK(solve(y-(5.-2i)*(5.+2i)==0.)== 29.);
CHECK(solve(y-(5.-2i)*(5.-2i)==0.)== 21.-20i);
CHECK(solve((y^2)-1i*1i==0.) ==0.+1i);
}
|
5a7bac1b052104cbb1327d839f4103b19aebe268
|
[
"C++"
] | 4
|
C++
|
bhori/CPP
|
ddac1cc637ffdd6bbad89320081c7a91b9a6e7df
|
bd6cd07449a5edfbc980d7df657552965760159b
|
refs/heads/master
|
<file_sep>#include<stdio.h>
int main()
{
int num,r,i;
scanf("%d",&num);
while(num>0)
{
r=num%10;
if(r==0) printf("Zero ")
}
}
<file_sep>#include<stdio.h>
int main()
{
char str1[20],str2[20],str[20];
printf("Enter str1:");
gets(str1);
printf("Enter str2:");
gets(str2);
printf("Before swapping:");
printf("str1=%s\n str2=%s\n\n",str1,str2);
int i=0,j=0;
while(str1[i]!='\0')
{
str[j]=str1[i];
i++;j++;
}
str[j]='\0';
i=0,j=0;
while(str2[i]!='\0')
{
str1[j]=str2[i];
i++;j++;
}
str[j]='\0';
i=0,j=0;
while(str[i]!='\0')
{
str2[j]=str[i];
i++;j++;
}
printf("After swapping:");
printf("str1=%s\n str2=%s\n",str1,str2);
return 0;
}
<file_sep>#include<stdio.h>
#include<math.h>
int main()
{
int bin,oct=0,dec=0,r,i=0,j=1,t,p,x;
printf("Enter your binary number :\t");
scanf("%d",&bin);
t=bin;
p=bin;
while(t!=0)
{
r=t%10;
if(r>1)
{
printf("Error");
return 0;
}
t=t/10;
}
while(p!=0)
{
r=p%10;
x=pow(2,i);
dec=dec+r*x;
p=p/10;
i++;
}
while(dec!=0)
{
r=dec%8;
oct=oct+r*j;
dec=dec/8;
j=j*10;
}
printf("After conversion Octal = %d",oct);
return 0;
}
<file_sep>#include<stdio.h>
#include<math.h>
int main()
{
int bin,dec=0,r,i=0,t,p,x;
printf("Enter your binary number :\t");
scanf("%d",&bin);
t=bin;
p=bin;
while(t!=0)
{
r=t%10;
if(r>1)
{
printf("Error");
return 0;
}
t=t/10;
}
while(p!=0)
{
r=p%10;
x=pow(2,i);
dec=dec+r*x;
p=p/10;
i++;
}
int j=0,k=0 ;
char hex[100];
while(dec>0)
{
r=dec%16;
if(r<10)
hex[k]=48+r;
else
hex[k]=55+r;
dec=dec/16;
k++;
j++;
}
for(k=j-1;k>=0;k--)
{
printf("%c",hex[k]);
}
return 0;
}
<file_sep>#include <stdio.h>
int main()
{
int n, i;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i<n; i++)
{
// condition for nonprime number
if(n%i==0)
{
printf("%d is not a prime number.",n);
break;
}
else
{
if(i==n-1)
printf("The number is prime");
}
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int n,i,num,large=0;
printf("How many numbers : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the %dth number \t" ,i);
scanf("%d",&num);
if(num>=large)
large=num;
}
printf("The largest number is %d",large);
return 0;
}
<file_sep>#include<stdio.h>
main()
{
printf("%d %d %d\n\n",2147483647,2147483647+1,2147483647+10);
printf("%lld %lld %lld\n\n",2147483647LL,2147483647LL+1LL,2147483647LL+10LL);
}
<file_sep>#include<stdio.h>
int main()
{
int i,sum=0,t,m,n;
scanf("%d",&t);
for(i=0;i<=t;i++)
{
scanf("%d%d",&m,&n);
sum=m+n;
printf("%d\n",sum);
}
return 0;
}
<file_sep>#include<stdio.h>
#include<math.h>
int main()
{
int bin,dec=0,r,i=0,t,p,x;
printf("Enter your binary number :\t");
scanf("%d",&bin);
t=bin;
p=bin;
while(t!=0)
{
r=t%10;
if(r>1)
{
printf("Error");
return 0;
}
t=t/10;
}
while(p!=0)
{
r=p%10;
//x=pow(2,i);
dec=dec+r*pow(2,i);
p=p/10;
i++;
}
printf("After conversion Decimal = %d",dec);
return 0;
}
<file_sep>#include<stdio.h>
#include<math.h>
int main()
{
int n,m,count=0,a,sum=0;
printf("enter an intiger number: ");
scanf("%d",&n);
m=n;
while(m>0)
{
count=count+1;
m/=10;
}
m=n;
while(m>0)
{
a=m%10;
sum+=pow(a,count);
m=m/10;
}
if(sum==n)
printf("The number is an armstrong number");
else
printf("The number is not an armstrong number");
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
if(a==b || b==c || c==a)
printf("two number is equal");
if(b>a && a>c || a>b && c>a)
printf("a is the middle number %d\n",a);
if(a>b && b>c || a<b && c>b)
printf("b is the middle number %d\n",b);
if(b>c && a<c || c>b && c<a)
printf("c is the middle number %d\n",c);
return 0;
}
<file_sep># C-programming
Problem solution in C
<file_sep>#include<stdio.h>
int main()
{
int array[100],n,i,search,first,last,middle;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&array[i]);
}
printf("Enter value to find : \n");
scanf("%d",&search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d found at location %d\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("%d is not present in the list\n", search);
return 0;
}
<file_sep>#include<stdio.h>
struct XYZ{
int x;
float y;
char z;
};
int main(){
struct XYZ arr[2];
int sz = (char*)&arr[1] - (char*)&arr[0];
printf("%d",sz);
return 0;
}
<file_sep>#include <stdio.h>
int main ()
{
int n,i;
char ch;
printf("How many characters?\n");
scanf("%d",&n);
printf("input %d character\n",(n-1));
char str[n+1];
str[n]='\0';
for(i=0;i<n;i++)
{
ch=getchar();
str[i]=ch;
}
printf("The string is : ");
puts(str);
return 0 ;
}
<file_sep>#include<stdio.h>
#include<math.h>
#define PI 3.1416
#define MAX 180
main()
{
int angle=0;
float x,y;
printf(" angle cos(angle)\n");
while(angle<=MAX)
{
y=(PI/MAX)*angle;
x=cos(y);
printf("%15d %15.5f\n",angle,x);
angle=angle+10;
}
}
<file_sep>#include <stdio.h>
#include <math.h>
double solution(int);
int main(void)
{
int n ;
scanf("%d",&n);
printf("%.0f\n",solution(n));
return 0;
}
double solution(int n)
{
double result;
if(n == 0 || n == 1)
return 1;
else
result = n*solution(n-1);
return result;
}
<file_sep>#include<stdio.h>
int main()
{
int i,j,n,sum,total_sum=0;
printf("Enter the limit : ");
scanf("%d",&n);
if(n>=0 && n<=1000)
{
for(i=1;i<=n;i++)
{
sum=0;
for(j=1;j<=i;j++)
{
sum=sum+j;
}
total_sum=total_sum+sum;
}
printf("Total sum is %d",total_sum);
}
else
printf("The input is not in range");
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
FILE *fpointer;
fpointer = fopen("My first file.txt", "w");
fprintf(fpointer,"Hello World!");
fclose(fpointer);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int n,t,r=1;
printf("Enter a number: ");
scanf("%d",&n);
t=n;
while(t>0)
{
t=t/10;
r = r*10;
}
printf("Each digits of given number are: ");
while(r>1)
{
r = r/10;
printf("%d ",n/r);
n = n % r;
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a,b,c,largest;
printf("Enter three numbers:\n ");
scanf("%d%d%d",&a,&b,&c);
if((a-b >=0 && a-c >=0) || (b-c >=0 && a-b >=0))
largest=a;
else if((a-c >=0 && b-a >=0) || (c-a >=0 && b-c >=0))
largest=b;
else
largest=c;
printf("The largest among three numbers is %d",largest);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
long int i,a,b;
scanf("%d",&a);
for(i=1;i<=a;i++)
{
scanf("%d",&b);
if(b%2==0 && b>=0)
printf("even\n");
if(b%2!=0 && b>=0)
printf("odd\n");
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
char string[50];
int c=0;
printf("Enter the string : \n");
gets(string);
while (string[c] != '\0')
{
if (string[c] >= 'A' && string[c] <= 'Z')
{
string[c] = string[c] + 32;
}
c++;
}
printf("%s",string);
return 0;
}
<file_sep>#include<stdio.h>
#include<ctype.h>
main()
{
char str1[50],str2[50],str3[50],str4[50],i=0;
printf("enter a string to convert into uppercase : \n");
gets(str1);
while(str1[i]!='\0')
{
str3[i]=toupper(str1[i]);
i++;
}
puts(str3);
i=0;
printf("enter a string to convert into lowercase : \n");
gets(str2);
while(str2[i]!='\0')
{
str3[i]=tolower(str2[i]);
i++;
}
puts(str3);
}
<file_sep>#include<stdio.h>
int main()
{
int m,count=0;
printf("Enter a number : \n");
scanf("%d",&m);
while(m>0)
{
count=count+1;
m=m/10;
}
printf("The number of digits are %d",count);
return 0;
}
<file_sep>#include<stdio.h>
#include<math.h>
int main()
{
int n,t,r,count=0,x;
scanf("%d",&n);
t=n;
while(t>0)
{
t=t/10;
count++;
}
while(n>0)
{
count--;
x=pow(10,count);
r=n/x;
printf(" %d",r);
n=n % x;
}
return 0;
}
<file_sep>#include<stdio.h>
long fact(int n)
{
long i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
int main()
{
int i,n;
double sum=0;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum = sum+(fact(i)/i);
}
printf("sum :%lf",sum);
return 0;
}
<file_sep>#include <stdio.h>
#include<math.h>
int main()
{
int oct ,dec=0 ,t ,p, r ,i=0 ,x;
printf("Enter your octal number :\t");
scanf("%d",&oct);
t=oct;
p=oct;
while(t!=0)
{
r=t%10;
if(r>=8)
{
printf("Error");
return ;
}
t=t/10;
}
while(p!=0)
{
r=p%10;
x=pow(8,i);
dec=dec+r*x;
p=p/10;
i++;
}
printf("The decimal conversion of the octal number %d is %d ",oct,dec);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int dec,oct=0,r,t,i=1;
printf("Enter your decimal number :\t");
scanf("%d",&dec);
while(dec!=0)
{
r=dec%8;
oct=oct+r*i;
dec=dec/8;
i=i*10;
}
printf("After conversion octal = %d",oct);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int n1,n2,sum;
printf("enter the two number\n ");
scanf("%d%d",&n1,&n2);
sum=n1 + (~n2 + 1);
printf("The result is %d",sum);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int n,i,j,k,c=1;
printf("Enter the number of rows : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=1;j<=n-i;j++)
printf(" ");
for(k=0;k<=i;k++)
{
if(k==0 || i==0)
c=1;
else
c=c*(i-k+1)/k;
printf("%4d",c);
}
printf("\n");
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a,i,r;
printf("enter the number : ");
scanf("%d",a);
for(i=1;i<=10;i++)
{
printf("%d X %d=%d",a,i,r);
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int n1,n2,sum=0;
printf("Enter two number : ");
scanf("%d%d",&n1,&n2);
sum=n1-(-n2);
printf("The sum is %d",sum);
return 0;
}
<file_sep>//14. ASCII Value of all Characters
#include<stdio.h>
int main()
{
int i;
for(i=33;i<=126;i++)
{
printf("The ASCII value of %c character5 is %d\n",i,i);
}
return 0;
}
<file_sep>//18. Sum of Digits
#include<stdio.h>
int main()
{
int n,d,sum=0;
printf("enter your number : ");
scanf("%d",&n);
while(n>0)
{
d=n%10;
sum=sum+d;
n=n/10;
}
printf("The sum of the digits is %d",sum);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("my name is Tahmid\n");
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
FILE *fpointer;
fpointer = fopen("string file.txt", "w");
char str[200];
gets(str);
fprintf(fpointer,"%s",str);
fclose(fpointer);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a,b,i,j,k,count=0,count1;
scanf("%d",&a);
for(i=1;i<=a;i++)
{
count1=0;
for(j=1;j<=10;j++)
{
count=0;
scanf("%d",&b);
for(k=2;k<=b/2;k++)
{
if(b%k==0)
count++;
}
if(count==0 && b!= 1)
{
count1++;
}
}
printf("%d",count1);
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int dec,i=0,j=0,r;
char hex[100];
printf("Enter a decimal number : \n");
scanf("%d",&dec);
while(dec>0)
{
r=dec%16;
if(r<10)
hex[i]=48+r;
else
hex[i]=55+r;
dec=dec/16;
i++;
j++;
}
for(i=j-1;i>=0;i--)
{
printf("%c",hex[i]);
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a,b;
printf("Enter the value of a & b : \n");
scanf("%d%d",&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf("The new value of a & b is : %d & %d",a,b);
return 0;
}
<file_sep>#include <stdio.h>
int main()
{
long long int dec,t, r = 0,bin=0,i=1;
printf("Enter a decimal number to convert:\n");
scanf("%lld", &dec);
t=dec;
while(t>0)
{
r=t%2;
t=t/2;
bin = bin + r*i;
i=i*10;
}
printf("The binary number of %lld is %lld",dec,bin);
return 0;
}
<file_sep>#include<stdio.h>
#include<math.h>
int bin(int dec);
int dec(int bin);
int main()
{
int bin1,bin2,sum;
printf("Enter two binary number to add : \n");
scanf("%d%d",&bin1,&bin2);
sum=dec(bin1)+dec(bin2);
sum=bin(sum);
printf("sum = %d",sum);
return 0;
}
int bin(int dec)
{
int t, r = 0,bin=0,i=1;
t=dec;
while(t>0)
{
r=t%2;
t=t/2;
bin = bin + r*i;
i=i*10;
}
return bin;
}
int dec(int bin)
{
int dec=0,r,i=0,t,p,x;
t=bin;
p=bin;
while(t!=0)
{
r=t%10;
if(r>1)
{
printf("Error\n");
return 0;
}
t=t/10;
}
while(p!=0)
{
r=p%10;
x=pow(2,i);
dec=dec+r*x;
p=p/10;
i++;
}
return dec;
}
<file_sep>#include<stdio.h>
#include<math.h>
int main()
{
double a,b,c,d,x1,x2,real_part,imaginary_part;
printf("enter the value of a,b & c :");
scanf("%lf%lf%lf",&a,&b,&c);
d=b*b-4*a*c;
if(d>0)
{
x1=(-b+d*0.5)/(2*a);
x2=(-b-d*0.5)/(2*a);
printf("x1 = %.2lf x2 = %.2lf",x1,x2);
}
else if(d==0)
{
x1=-b/(2*a);
x2=-b/(2*a);
printf("x1 = %.2lf x2 = %.2lf",x1,x2);
}
else
{
real_part=-b/(2*a);
imaginary_part=sqrt(-d)/(2*a);
printf("x1= %.2lf+%.2lfi x2=%.2lf-%.2lfi",real_part,imaginary_part,real_part,imaginary_part);
}
return 0;
}
<file_sep>#include<stdio.h>
#include<math.h>
int main()
{
int n,i;
printf("Enter your number : ");
scanf("%d",&n);
while(n%2==0)
{
printf(" %d", 2);
n=n/2;
}
for(i=3;i<=n;i=i+2)
{
while(n%i==0)
{
printf(" %d", i);
n=n/i;
}
}
if(n>2)
printf(" %d", n);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
long int i=0;
char bin[100], hex[100];
printf("Enter any hexadecimal number : ");
scanf("%s",hex);
printf("\nEquivalent Binary value is : ");
while(hex[i])
{
switch(hex[i])
{
case '0' : printf("0000");
break;
case '1' : printf("0001");
break;
case '2' : printf("0010");
break;
case '3' : printf("0011");
break;
case '4' : printf("0100");
break;
case '5' : printf("0101");
break;
case '6' : printf("0110");
break;
case '7' : printf("0111");
break;
case '8' : printf("1000");
break;
case '9' : printf("1001");
break;
case 'A' : printf("1010");
break;
case 'B' : printf("1011");
break;
case 'C' : printf("1100");
break;
case 'D' : printf("1101");
break;
case 'E' : printf("1110");
break;
case 'F' : printf("1111");
break;
case 'a' : printf("1010");
break;
case 'b' : printf("1011");
break;
case 'c' : printf("1100");
break;
case 'd' : printf("1101");
break;
case 'e' : printf("1110");
break;
case 'f' : printf("1111");
break;
default : printf("\nInvalid hexadecimal digit %c",hex[i]);
}
i++;
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a,b,lcm;
printf("Enter two number:\n");
scanf("%d%d",&a,&b);
lcm = (a>b)?a:b;
while(1)
{
if(lcm%a==0 && lcm%b==0)
{
printf("The lcm is %d ",lcm);
break;
}
else
lcm++;
}
return 0;
}
<file_sep>#include<stdio.h>
int printing(unsigned int n)
{
if(n<=100)
{
printf(" %d\t",n);
printing(n+1);
}
return;
}
int main()
{
printing(1);
return 0;
}
<file_sep>#include<stdio.h>
#include<math.h>
int main()
{
char hexdigits[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char hex[30];
long long int c=0,i=0,j,k=1,r,t,dec=0,power=0,bin=0;
printf("Enter a Hexadecimal Number : \n");
scanf("%s",&hex);
while(hex[i]!='\0')
{
c++;
i++;
}
for(i=c-1;i>=0;i--)
{
for(j=0;j<16;j++)
{
if(hex[i]==hexdigits[j])
dec=dec+j * pow(16,power);
}
power++;
}
//printf("dec = %lld\n",dec);
t=dec;
while(t>0)
{
r=t%2;
t=t/2;
bin = bin + r*k;
k=k*10;
}
printf("The converted binary number is %lld",bin);
return 0;
}
<file_sep>#include <stdio.h>
#include<math.h>
int main()
{
int oct ,dec=0 ,bin=0 ,t ,p, r ,s ,i=0 ,j=0 ,k=0 ,x;
char hex[100];
printf("Enter your octal number :\t");
scanf("%d",&oct);
t=oct;
p=oct;
while(t!=0)
{
r=t%10;
if(r>=8)
{
printf("Error");
return 0;
}
t=t/10;
}
while(p!=0)
{
r=p%10;
x=pow(8,i);
dec=dec+r*x;
p=p/10;
i++;
}
//printf("%d\n",dec);
while(dec>0)
{
r=dec%16;
if(r<10)
hex[j]=48+r;
else
hex[j]=55+r;
dec=dec/16;
j++;
k++;
}
for(j=k-1;j>=0;j--)
{
printf("%c",hex[j]);
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int n,i,a1=0,a2=1,sum=0;
printf("enter the number of terms : ");
scanf("%d",&n);
printf("The fibonacci series : \n");
for(i=1;i<=n;i++)
{
if(i<=1)
sum=i;
else
{
sum=a1+a2;
a1=a2;
a2=sum;
}
printf("%d\t",sum);
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int n,d,sum=0;
printf("Enter your number : ");
scanf("%d",&n);
while(n>=10)
{
sum=0;
while(n)
{
d=n%10;
sum=sum+d;
n=n/10;
}
if(sum>=10)
n=sum;
else
break;
}
printf("The generic root is %d",sum);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a,i,j,neg=0,pos=0;
scanf("%d",&a);
for(i=1;i<=a;i++)
{
scanf("%d %d %d",&j,&k,L);
if(j<0)
neg++;
if(j>0)
pos++;
}
printf("%d %d",pos,neg);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a,i,j,b,max=0,min=100;
scanf("%d",&a);
for(i=1;i<=a;i++)
{
max = 0;
min = 100;
for(j=1;j<=5;j++)
{
scanf("%d",&b);
if(b > max)
max = b;
if(min > b)
min = b;
}
printf("%d %d\n",max,min);
}
return 0;
}
<file_sep>#include <stdio.h>
int main() {
FILE *fptr;
char c;
fptr = fopen(__FILE__,"r");
while(c != EOF)
{
c = getc(fptr);
putchar(c);
}
fclose(fptr);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int n,t,r,i,j,fact=1,factsum=0;
printf("enter the limit : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
t=i;
while(t>0)
{
fact=1;
r=t%10;
for(j=1;j<=r;j++)
{
fact=fact*j;
}
factsum=factsum+fact;
t=t/10;
}
if(factsum==i)
printf("%d\t",factsum);
}
return 0;
}
<file_sep>//19. Power of Number
#include<stdio.h>
int main()
{
int base,power,result=1;
printf("Enter the base : ");
scanf("%d",&base);
printf("Enter the power: ");
scanf("%d",&power);
while(power!=0)
{
result=result*base;
power--;
}
printf("The result is %d",result);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int n,i;
scanf("%d",&n);
struct ss
{
int roll;
char name[25];
int marks;
char grade[3];
float gp;
};
struct ss student[n];
for(i=1;i<=n;i++)
{
printf("Enter roll , name & marks of student%d\n",i);
scanf("%d %s %d",&student[i].roll,student[i].name,&student[i].marks);
}
printf("roll \tname \tmarks\n");
for(i=1;i<=n;i++)
{
printf("%d \t%s \t%d",student[i].roll,student[i].name,student[i].marks);
printf("\n");
}
for(i=1;i<=n;i++)
{
if(student[i].marks>=80){
student[i].grade[0]='A';
student[i].grade[1]='+';
student[i].grade[2]='\0';
student[i].gp=4.00;
}
else if(student[i].marks>=75 && student[i].marks<=79){
student[i].grade[0]='A';
student[i].gp=3.75;
}
else if(student[i].marks>=70 && student[i].marks<=74){
student[i].grade[0]='A';
student[i].grade[1]='\0';
student[i].gp=3.50;
}
else if(student[i].marks>=65 && student[i].marks<=69){
student[i].grade[0]='B';
student[i].grade[1]='+';
student[i].grade[2]='\0';
student[i].gp=3.25;
}
else if(student[i].marks>=60 && student[i].marks<=64){
student[i].grade[0]='B';
student[i].grade[1]='\0';
student[i].gp=3.00;
}
else if(student[i].marks>=55 && student[i].marks<=59){
student[i].grade[0]='B','-';
student[i].gp=2.75;
}
else if(student[i].marks>=50 && student[i].marks<=54){
student[i].grade[0]='C','+';
student[i].gp=2.50;
}
else if(student[i].marks>=45 && student[i].marks<=49){
student[i].grade[0]='C';
student[i].gp=2.25;
}
else if(student[i].marks>=40 && student[i].marks<=44){
student[i].grade[0]='D';
student[i].gp=2.00;
}
else
{
student[i].grade[0]='F';
student[i].gp=0.00;
}
}
printf("roll \tname \tL.G \tG.P\n");
for(i=1;i<=n;i++)
{
printf("%d \t%s \t%s \t%.2f",student[i].roll,student[i].name,student[i].grade,student[i].gp);
printf("\n");
}
return 0;
}
<file_sep>#include<stdio.h>
int fact(int n);
int main()
{
int n,r,ncr;
printf("Enter the value of n & r :\n");
scanf("%d%d",&n,&r);
ncr=fact(n)/(fact(r)*fact(n-r));
printf("The ncr is %d",ncr);
return 0;
}
int fact(int n)
{
int i=1;
while(n!=0)
{
i=i*n;
n--;
}
return i;
}
<file_sep>#include<stdio.h>
struct student
{
int roll;
char name[20];
int marks;
};
int main()
{
// int n;
//scanf("%d",&n);
struct student s[10];
int i,n;
printf("enter the students number:\n");
scanf("%d",&n);
for(i=0;i<n;++i)
{
s[i].roll=i+1;
printf("\n for roll number:\t%d\n",s[i].roll);
printf("enter name:\n");
scanf("%s",s[i].name);
printf("enter marks:\n");
scanf("%d",&s[i].marks);
printf("\n");
}
for(i=0;i<n;i++)
{
printf("%d\t",s[i].roll);
printf("%s\t",s[i].name);
if(s[i].marks>=80)
printf("LG: A+ GP: 4.00\n");
else if(s[i].marks>=75)
printf("LG: A GP: 3.75\n");
else if(s[i].marks>=70)
printf("LG: A- GP: 3.50\n");
else if(s[i].marks>=65)
printf("LG: B+ GP: 3.25\n");
else if(s[i].marks>=60)
printf("LG: B GP: 3.00\n");
else if(s[i].marks>=55)
printf("LG: B- GP: 2.75\n");
else if(s[i].marks>=50)
printf("LG: C+ GP: 2.50\n");
else if(s[i].marks>=45)
printf("LG: C GP: 2.25\n");
else if(s[i].marks>=40)
printf("LG: D GP: 2.00\n");
else
printf("LG: F GP: 0.00\n");
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a,i,j,b,sum=0;
double avg;
scanf("%d",&a);
for(i=1;i<=a;i++)
{
sum=0;
for(j=1;j<=5;j++)
{
scanf("%d",&b);
sum=sum+b;
}
avg=sum/5;
printf("%lf",avg);
}
return 0;
}
<file_sep>#include <stdio.h>
#include<math.h>
int main()
{
int oct ,dec=0 ,bin=0 ,t ,p, r ,s ,i=0 ,j=1 ,x;
printf("Enter your octal number :\t");
scanf("%d",&oct);
t=oct;
p=oct;
while(t!=0)
{
r=t%10;
if(r>=8)
{
printf("Error");
return ;
}
t=t/10;
}
while(p!=0)
{
r=p%10;
x=pow(8,i);
dec=dec+r*x;
p=p/10;
i++;
}
while(dec!=0)
{
s=dec%2;
bin=bin+s*j;
dec=dec/2;
j=j*10;
}
printf("After conversion Binary = %d",bin);
return 0;
}
<file_sep>//4. Strong Number
#include<stdio.h>
int main()
{
int n,t,r,i,fact=1,factsum=0;
scanf("%d",&n);
t=n;
while(n>0)
{
fact=1;
r=n%10;
for(i=1;i<=r;i++)
{
fact=fact*i;
}
factsum=factsum+fact;
n=n/10;
}
if(factsum==t)
printf("The number is strong");
else
printf("The number is not strong");
return 0;
}
<file_sep>#include <stdio.h>
int main()
{
int marks;
scanf("%d",&marks);
if("marks<40")
{
printf("you are fail");
}
else
{
printf("you are pass");
}
return o;
}
<file_sep>#include<stdio.h>
int main()
{
int n,i,factorial=1;
scanf("%d",&n);
for(i=n;i>=1;i--)
{
factorial=factorial*i;
}
printf("the factorial of %d is %d",n,factorial);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int num,i,p;
printf("enter the number:");
scanf("%d",&num);
p=1;
for(i=2;i<=num/2;i++)
{
if(num%i==0)
p=0;
if(p==1)
printf("the number is prime\n");
else
printf("the number is not prime\n");
break;
}
return 0;
}
<file_sep>#include<stdio.h>
#include<math.h>
int main()
{
char hexdigits[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char hex[30];
int c=0,i=0,j,dec=0,power=0,r,oct=0,k=1;
printf("Enter a Hexadecimal Number : \n");
scanf("%s",&hex);
while(hex[i]!='\0')
{
c++;
i++;
}
for(i=c-1;i>=0;i--)
{
for(j=0;j<16;j++)
{
if(hex[i]==hexdigits[j])
dec=dec+j * pow(16,power);
}
power++;
}
printf("Decimal Number : %d\n", dec);
while(dec!=0)
{
r=dec%8;
oct=oct+r*k;
dec=dec/8;
k=k*10;
}
printf("After conversion octal = %d",oct);
return 0;
}
<file_sep>//Roll : 170121 Name : <NAME>
#include<stdio.h>
#include<math.h>
int main()
{
int n,t,u,a,x,y,z,v,c=0,m,s;
printf("Enter your number : ");
scanf("%d",&n);
v=n;
t=n;
u=n;
while(n>0)
{
c=c+1;
n/=10;
}
x=v%10;
a=(pow(10,(c-1)));
y=u/a;
z=t%a;
m=z/10;
s=x*pow(10,(c-1))+m*10+y;
printf("The desired number is %d",s);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
fp1=fopen("file","w");
}
<file_sep>//Roll : 170121 Name : Tahmid
#include<stdio.h>
#include<math.h>
int main()
{
int n,r,npr;
printf("Enter the value of n & r : ");
scanf("%d%d\n",&n,&r);
if(n<r)
printf("invalid output");
if(n>=0 && r<=15)
{
npr=fact(n)/fact(n-r);
printf("The npr is %d",npr);
}
else
printf("invalid input");
return 0;
}
int fact(int n)
{
int i=1;
while(n!=0)
{
i=i*n;
n--;
}
return i;
}
<file_sep>#include<stdio.h>
main()
{
int number;
float amount;
number=100;
amount=35.35+75.75;
printf("%d\n",number);
printf("%5.2f",amount);/*5.2 means minimum 5 places in all and two places to the right of the decimal point.*/
}
<file_sep>#include<stdio.h>
int main()
{
int a,b,t;
printf("Enter the value of a & b : \n");
scanf("%d%d",&a,&b);
t=a;
a=b;
b=t;
printf("The changed value is a = %d & b = %d",a,b);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
char str1[50],str2[50],i=0,j=0,length=0;
char *p;
printf("Enter first string : \n");
gets(str1);
printf("Enter second string : \n");
gets(str2);
while(str1[i]!='\0')
{
length++;
i++;
}
p=&str1[i];
i=0;
while(str2[i]!='\0')
{
*p=str2[i];
i++;
p=p+1;
}
j=i;
i=length+j;
int k=0;
printf("After concatenation : ");
while(k<i)
{
printf("%c",str1[k]);
k++;
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a[10],b[10],c[10],i;
printf("Enter First array :\n");
for (i=0;i<10;i++)
scanf("%d",&a[i]);
printf("Enter Second array :\n");
for (i=0;i<10;i++)
scanf("%d",&b[i]);
printf("Arrays before swapping\n");
printf("First array :\n");
for (i=0;i<10;i++)
{
printf("%d",a[i]);
}
printf("Second array :\n\n");
for (i=0;i<10;i++)
{
printf("%d",b[i]);
}
for (i=0;i<10;i++)
{
c[i]=a[i];
a[i]=b[i];
b[i]=c[i];
}
printf("Arrays after swapping :\n");
printf("First array :\n");
for (i=0;i<10;i++)
{
printf("%d",a[i]);
}
printf("Second array :\n
");
for (i=0;i<10;i++)
{
printf("%d",b[i]);
}
return 0;
}
<file_sep>#include<stdio.h>int \\
<file_sep>#include<stdio.h>
int main()
{
int i,j,n,sum=0,total_sum=0;
printf("Enter the limit : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=0;
for(j=1;j<=i;j++)
{
sum=sum+j;
}
total_sum=total_sum+sum;
}
printf("Total sum is %d",total_sum);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int length=0;
char str[20];
gets(str);
char *p;
p=str;
while(*p!='\0')
{
p=p+1;
length++;
}
printf("The length of the string is %d",length);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
char s[15]={'m','a','d','a','f','a','k','a','r','b','i','j','o','n','\0'};
int i=0;
while(s[i]!='\0')
{
i++;
}
printf("\n%d",i);
return 0;
}
<file_sep>//6. Palindrome Number
#include <stdio.h>
int main()
{
int n, t, r = 0;
printf("Enter a number to reverse\n");
scanf("%d", &n);
t=n;
while (t > 0)
{
r = r * 10;
r = r + t%10;
t = t/10;
}
if(n==r)
printf("The given number is palindrome");
else
printf("The given number is not palindrome");
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int num,reverse_number;
printf("Enter any number:\n");
scanf("%d",&num);
reverse_number=reverse_function(num);
printf("After reverse the no is :%d\n",reverse_number);
return 0;
}
int sum=0,r;
reverse_function(int num)
{
if(num)
{
r=num%10;
sum=sum*10+r;
reverse_function(num/10);
}
else
return sum;
return sum;
}
|
be1db7b85a7953ff1f92f0633f65e3ad800e67df
|
[
"Markdown",
"C"
] | 79
|
C
|
thm1d/C-programming
|
93762dbcb67ced6560587e1e1d4cb79d1928cf49
|
b7f5594e7ad96c5cf6d1986a8c68646e24d3a230
|
refs/heads/master
|
<file_sep>console.log("JS up and running")
|
039053fca37be1af87796a08620276b96213d0c4
|
[
"JavaScript"
] | 1
|
JavaScript
|
benjaminwest1046/portfolio
|
cac93ebe3bc66e8f6d2564a40a754b7b81260d3e
|
1af30566584a7125d66abd184a3656fdb95072f4
|
refs/heads/master
|
<file_sep>package main
// Version for app.
const Version = "3.4"
<file_sep>module github.com/mickep76/etcdtool
go 1.14
require (
github.com/BurntSushi/toml v0.2.1-0.20160426202516-f0aeabca5a12
github.com/bgentry/speakeasy v0.0.0-20150902231413-36e9cfdd6909
github.com/codegangsta/cli v1.16.1-0.20160502160658-415b5e766a61
github.com/coreos/etcd v2.3.1-0.20160502184358-a8139e2b0e23+incompatible
github.com/mickep76/etcdmap v0.0.0-20160502152020-c53d6e11e292
github.com/mickep76/iodatafmt v0.0.0-20181011194834-7c7e9a8f31cd
github.com/ugorji/go v0.0.0-20160328060740-a396ed22fc04
github.com/xeipuuv/gojsonpointer v0.0.0-20151027082146-e0fe6f683076
github.com/xeipuuv/gojsonreference v0.0.0-20150808065054-e02fc20de94c
github.com/xeipuuv/gojsonschema v0.0.0-20160430164825-d3178baac324
golang.org/x/net v0.0.0-20160501043121-35ec611a141e
gopkg.in/yaml.v2 v2.0.0-20160301204022-a83829b6f129
)
|
17d13c239a847d8f4fd6cb318e0ed05b730fc0a6
|
[
"Go Module",
"Go"
] | 2
|
Go
|
jsf5/etcdtool
|
8935604aa9089e2b2a721a671f38ff4efd3e326a
|
2ac9f464e2c79a126ed022d511cea8f0c5edc431
|
refs/heads/master
|
<file_sep>class "ClanSystem"
msgColors =
{
[ "err" ] = Color ( 255, 0, 0 ),
[ "info" ] = Color ( 0, 255, 0 ),
[ "warn" ] = Color ( 255, 100, 0 )
}
function ClanSystem:__init ( )
Events:Subscribe ( "ModuleLoad", self, self.ModuleLoad )
end
function ClanSystem:ModuleLoad ( )
self.active = false
self.LastTick = 0
self.playerClans = { }
self.clanMenu = { }
self.playerToRow = { }
self.clanMenu.window = GUI:Window ( "Castillo's Faction system - Menu", Vector2 ( 0.5, 0.5 ) - Vector2 ( 0.3, 0.45 ) / 2, Vector2 ( 0.3, 0.45 ) )
self.clanMenu.window:SetVisible ( false )
self.clanMenu.playersList = GUI:SortedList ( Vector2 ( 0.0, 0.0 ), Vector2 ( 0.53, 0.8 ), self.clanMenu.window, { { name = "Player" } } )
for player in Client:GetPlayers ( ) do
self:addPlayerToList ( player )
end
self:addPlayerToList ( LocalPlayer )
self.clanMenu.searchEdit = GUI:TextBox ( "", Vector2 ( 0.0, 0.82 ), Vector2 ( 0.53, 0.07 ), "text", self.clanMenu.window )
self.clanMenu.searchEdit:Subscribe ( "TextChanged", self, self.SearchPlayer )
self.clanMenu.cLabel = GUI:Label ( "Faction options", Vector2 ( 0.55, 0.01 ), Vector2 ( 0.20, 0.1 ), self.clanMenu.window )
self.clanMenu.manageClan = GUI:Button ( "Manage", Vector2 ( 0.55, 0.08 ), Vector2 ( 0.20, 0.1 ), self.clanMenu.window )
self.clanMenu.manageClan:Subscribe ( "Press", self, self.ManageClan )
self.clanMenu.leaveClan = GUI:Button ( "Leave", Vector2 ( 0.77, 0.08 ), Vector2 ( 0.20, 0.1 ), self.clanMenu.window )
self.clanMenu.leaveClan:Subscribe ( "Press", self, self.LeaveClan )
self.clanMenu.invitePlayer = GUI:Button ( "Invite player", Vector2 ( 0.55, 0.19 ), Vector2 ( 0.20, 0.1 ), self.clanMenu.window )
self.clanMenu.invitePlayer:Subscribe ( "Press", self, self.InvitePlayer )
self.clanMenu.pLabel = GUI:Label ( "Player options", Vector2 ( 0.55, 0.35 ), Vector2 ( 0.20, 0.1 ), self.clanMenu.window )
self.clanMenu.clanList = GUI:Button ( "Faction list", Vector2 ( 0.55, 0.41 ), Vector2 ( 0.20, 0.1 ), self.clanMenu.window )
self.clanMenu.clanList:Subscribe ( "Press", self, self.ClanList )
self.clanMenu.invitations = GUI:Button ( "Invitations", Vector2 ( 0.77, 0.41 ), Vector2 ( 0.20, 0.1 ), self.clanMenu.window )
self.clanMenu.invitations:Subscribe ( "Press", self, self.Invitations )
self.clanMenu.create = GUI:Button ( "Create", Vector2 ( 0.55, 0.52 ), Vector2 ( 0.20, 0.1 ), self.clanMenu.window )
self.clanMenu.create:Subscribe ( "Press", self, self.ShowCreate )
self.createClan = { }
self.createClan.window = GUI:Window ( "Castillo's Faction system - Create faction", Vector2 ( 0.5, 0.5 ) - Vector2 ( 0.2, 0.33 ) / 2, Vector2 ( 0.2, 0.33 ) )
self.createClan.window:SetVisible ( false )
self.createClan.nLabel = GUI:Label ( "Faction name:", Vector2 ( 0.0, 0.01 ), Vector2 ( 0.0, 0.0 ), self.createClan.window )
self.createClan.nLabel:SizeToContents ( )
self.createClan.nEdit = GUI:TextBox ( "", Vector2 ( 0.0, 0.1 ), Vector2 ( 0.96, 0.1 ), "text", self.createClan.window )
self.createClan.tLabel = GUI:Label ( "Faction tag", Vector2 ( 0.0, 0.23 ), Vector2 ( 0.0, 0.0 ), self.createClan.window )
self.createClan.tLabel:SizeToContents ( )
self.createClan.tEdit = GUI:TextBox ( "", Vector2 ( 0.0, 0.3 ), Vector2 ( 0.96, 0.1 ), "text", self.createClan.window )
self.createClan.ttLabel = GUI:Label ( "Faction type:", Vector2 ( 0.0, 0.43 ), Vector2 ( 0.0, 0.0 ), self.createClan.window )
self.createClan.ttLabel:SizeToContents ( )
self.createClan.type = GUI:ComboBox ( Vector2 ( 0.0, 0.51 ), Vector2 ( 0.96, 0.1 ), self.createClan.window, { "Open", "Closed" } )
self.createClan.cPick = GUI:Button ( "Faction colour", Vector2 ( 0.0, 0.65 ), Vector2 ( 0.96, 0.10 ), self.createClan.window )
self.createClan.cPick:Subscribe ( "Press", self, self.Colour )
self.createClan.create = GUI:Button ( "Create faction", Vector2 ( 0.0, 0.75 ), Vector2 ( 0.96, 0.10 ), self.createClan.window )
self.createClan.create:Subscribe ( "Press", self, self.Create )
self.colorPicker = { }
self.colorPicker.window = GUI:Window ( "Colour", Vector2 ( 0.5, 0.5 ) - Vector2 ( 0.2, 0.42 ) / 2, Vector2 ( 0.2, 0.42 ) )
self.colorPicker.window:SetVisible ( false )
self.colorPicker.picker = HSVColorPicker.Create ( )
self.colorPicker.picker:SetParent ( self.colorPicker.window )
self.colorPicker.picker:SetSizeRel ( Vector2 ( 1.06, 0.8 ) )
self.colorPicker.set = GUI:Button ( "Set colour", Vector2 ( 0.0, 0.82 ), Vector2 ( 0.76, 0.070 ), self.colorPicker.window )
self.colorPicker.set:Subscribe ( "Press", self, self.SetColour )
self.colorPicker.colour = { 255, 255, 255 }
self.manageClan = { }
self.manageClan.rows = { }
self.manageClan.window = GUI:Window ( "Castillo's Faction system - Faction management", Vector2 ( 0.5, 0.5 ) - Vector2 ( 0.4, 0.60 ) / 2, Vector2 ( 0.4, 0.60 ) )
self.manageClan.window:SetVisible ( false )
self.manageClan.mList = GUI:SortedList ( Vector2 ( 0.0, 0.0 ), Vector2 ( 0.64, 0.65 ), self.manageClan.window, { { name = "Name" }, { name = "Rank" }, { name = "Join date" } } )
self.manageClan.mList:SetButtonsVisible ( true )
self.manageClan.dLabel = GUI:Label ( "Faction name:", Vector2 ( 0.0, 0.67 ), Vector2 ( 0.0, 0.0 ), self.manageClan.window )
self.manageClan.dLabel:SizeToContents ( )
self.manageClan.mLabel = GUI:Label ( "Member options", Vector2 ( 0.66, 0.015 ), Vector2 ( 0.0, 0.0 ), self.manageClan.window )
self.manageClan.mLabel:SizeToContents ( )
self.manageClan.ranks = GUI:ComboBox ( Vector2 ( 0.66, 0.06 ), Vector2 ( 0.16, 0.06 ), self.manageClan.window, { "Co-Founder", "Deputy", "Member" } )
self.manageClan.kick = GUI:Button ( "Kick", Vector2 ( 0.66, 0.14 ), Vector2 ( 0.29, 0.068 ), self.manageClan.window )
self.manageClan.kick:Subscribe ( "Press", self, self.Kick )
self.manageClan.sRank = GUI:Button ( "Set rank", Vector2 ( 0.83, 0.06 ), Vector2 ( 0.12, 0.068 ), self.manageClan.window )
self.manageClan.sRank:Subscribe ( "Press", self, self.SetRank )
self.manageClan.cLabel = GUI:Label ( "Faction options", Vector2 ( 0.66, 0.23 ), Vector2 ( 0.0, 0.0 ), self.manageClan.window )
self.manageClan.cLabel:SizeToContents ( )
self.manageClan.bank = GUI:Button ( "Bank", Vector2 ( 0.68, 0.28 ), Vector2 ( 0.12, 0.068 ), self.manageClan.window )
self.manageClan.bank:Subscribe ( "Press", self, self.ShowBank )
self.manageClan.delete = GUI:Button ( "Delete", Vector2 ( 0.82, 0.28 ), Vector2 ( 0.12, 0.068 ), self.manageClan.window )
self.manageClan.delete:Subscribe ( "Press", self, self.Remove )
self.manageClan.log = GUI:Button ( "Log", Vector2 ( 0.82, 0.37 ), Vector2 ( 0.12, 0.068 ), self.manageClan.window )
self.manageClan.log:Subscribe ( "Press", self, self.ShowLog )
self.manageClan.motd = GUI:Button ( "MOTD", Vector2 ( 0.68, 0.37 ), Vector2 ( 0.12, 0.068 ), self.manageClan.window )
self.manageClan.motd:Subscribe ( "Press", self, self.ShowMotd )
--self.manageClan.chat = GUI:Button ( "Chat", Vector2 ( 0.68, 0.38 ), Vector2 ( 0.12, 0.068 ), self.manageClan.window )
self.bank = { }
self.bank.window = GUI:Window ( "Castillo's Faction system - Bank", Vector2 ( 0.5, 0.5 ) - Vector2 ( 0.2, 0.21 ) / 2, Vector2 ( 0.2, 0.21 ) )
self.bank.window:SetVisible ( false )
self.bank.balance = GUI:Label ( "Total balance: $0", Vector2 ( 0.0, 0.02 ), Vector2 ( 0.0, 0.0 ), self.bank.window )
self.bank.balance:SizeToContents ( )
self.bank.aLabel = GUI:Label ( "Amount:", Vector2 ( 0.0, 0.33 ), Vector2 ( 0.0, 0.0 ), self.bank.window )
self.bank.aLabel:SizeToContents ( )
self.bank.aEdit = GUI:TextBox ( "0", Vector2 ( 0.0, 0.45 ), Vector2 ( 0.96, 0.15 ), "numeric", self.bank.window )
self.bank.deposit = GUI:Button ( "Deposit", Vector2 ( 0.0, 0.63 ), Vector2 ( 0.46, 0.15 ), self.bank.window )
self.bank.deposit:Subscribe ( "Press", self, self.Deposit )
self.bank.withdraw = GUI:Button ( "Withdraw", Vector2 ( 0.49, 0.63 ), Vector2 ( 0.46, 0.15 ), self.bank.window )
self.bank.withdraw:Subscribe ( "Press", self, self.Withdraw )
self.confirm = { }
self.confirm.action = ""
self.confirm.window = GUI:Window ( "Confirm action", Vector2 ( 0.5, 0.5 ) - Vector2 ( 0.13, 0.13 ) / 2, Vector2 ( 0.13, 0.13 ) )
self.confirm.window:SetVisible ( false )
self.confirm.label = GUI:Label ( "Are you sure that you want to carry on with this action?", Vector2 ( 0.0, 0.0 ), Vector2 ( 0.90, 0.23 ), self.confirm.window )
self.confirm.label:SetWrap ( true )
self.confirm.accept = GUI:Button ( "Yes", Vector2 ( 0.0, 0.35 ), Vector2 ( 0.9, 0.25 ), self.confirm.window )
self.confirm.accept:Subscribe ( "Press", self, self.Confirm )
self.invitations = { }
self.invitations.rows = { }
self.invitations.window = GUI:Window ( "Castillo's Faction system - Invitations", Vector2 ( 0.5, 0.5 ) - Vector2 ( 0.25, 0.45 ) / 2, Vector2 ( 0.25, 0.45 ) )
self.invitations.window:SetVisible ( false )
self.invitations.list = GUI:SortedList ( Vector2 ( 0.0, 0.0 ), Vector2 ( 0.97, 0.8 ), self.invitations.window, { { name = "Faction" } } )
self.invitations.join = GUI:Button ( "Join faction", Vector2 ( 0.0, 0.8 ), Vector2 ( 0.97, 0.1 ), self.invitations.window )
self.invitations.join:Subscribe ( "Press", self, self.AcceptInvite )
self.clanList = { }
self.clanList.rows = { }
self.clanList.window = GUI:Window ( "Castillo's Faction system - Faction list", Vector2 ( 0.5, 0.5 ) - Vector2 ( 0.25, 0.45 ) / 2, Vector2 ( 0.25, 0.45 ) )
self.clanList.window:SetVisible ( false )
self.clanList.list = GUI:SortedList ( Vector2 ( 0.0, 0.0 ), Vector2 ( 0.97, 0.8 ), self.clanList.window, { { name = "Faction" }, { name = "Type" } } )
self.clanList.join = GUI:Button ( "Join faction", Vector2 ( 0.0, 0.8 ), Vector2 ( 0.97, 0.1 ), self.clanList.window )
self.clanList.join:Subscribe ( "Press", self, self.JoinClan )
self.motd = { }
self.motd.window = GUI:Window ( "Castillo's Faction system - MOTD", Vector2 ( 0.5, 0.5 ) - Vector2 ( 0.30, 0.50 ) / 2, Vector2 ( 0.30, 0.50 ) )
self.motd.window:SetVisible ( false )
self.motd.content = GUI:TextBox ( "", Vector2 ( 0.0, 0.0 ), Vector2 ( 0.96, 0.80 ), "multiline", self.motd.window )
self.motd.content:SetEnabled ( false )
self.motd.update = GUI:Button ( "Update MOTD", Vector2 ( 0.25, 0.82 ), Vector2 ( 0.50, 0.07 ), self.motd.window )
self.motd.update:Subscribe ( "Press", self, self.UpdateMotd )
self.log = { }
self.log.window = GUI:Window ( "Castillo's Faction system - Log", Vector2 ( 0.5, 0.5 ) - Vector2 ( 0.27, 0.50 ) / 2, Vector2 ( 0.27, 0.50 ) )
self.log.window:SetVisible ( false )
self.log.list = GUI:SortedList ( Vector2 ( 0.0, 0.0 ), Vector2 ( 0.97, 0.80 ), self.log.window, { { name = "Action" } } )
self.log.clear = GUI:Button ( "Clear Log", Vector2 ( 0.25, 0.82 ), Vector2 ( 0.50, 0.07 ), self.log.window )
self.log.clear:Subscribe ( "Press", self, self.ClearLog )
Network:Send ( "Clans:RequestSyncList", LocalPlayer )
Events:Subscribe ( "PostTick", self, self.PostTick )
Network:Subscribe ( "Clans:SyncPlayers", self, self.SyncPlayerClans )
Network:Subscribe ( "Clans:ReceiveData", self, self.ReceiveData )
Network:Subscribe ( "Clans:UpdateBankLabel", self, self.UpdateBankLabel )
Network:Subscribe ( "Clans:ReceiveInvitations", self, self.ReceiveInvitations )
Network:Subscribe ( "Clans:ReceiveClans", self, self.ReceiveClans )
Events:Subscribe ( "KeyUp", self, self.KeyUp )
Events:Subscribe ( "LocalPlayerInput", self, self.LocalPlayerInput )
Events:Subscribe ( "LocalPlayerExplosionHit", self, self.WeaponDamage )
Events:Subscribe ( "LocalPlayerBulletHit", self, self.WeaponDamage )
Events:Subscribe ( "LocalPlayeForcePulseHit", self, self.WeaponDamage )
Events:Subscribe ( "PlayerJoin", self, self.PlayerJoin )
Events:Subscribe ( "PlayerQuit", self, self.PlayerQuit )
self.clanMenu.window:Subscribe ( "WindowClosed", self, self.WindowClosed )
Events:Fire ( "HelpAddItem",
{
name = "SAUR factions",
text =
"Factions system scripted and designed by Castillo\n\nFeatures:\nCreate faction - Two types: Public or Invite Only\nInvite players\nSet member ranks\nFaction bank - Deposit/Withdraw\nFriendly fire disabled ( Can't kill between faction members)\nRead/Set MOTD\nView/Clear log\n\nPress F7 to access the factions menu"
}
)
Events:Subscribe ( "ModuleUnload", self, self.Unload )
end
function ClanSystem:Unload ( )
Events:Fire ( "HelpRemoveItem",
{
name = "SAUR factions"
}
)
end
function ClanSystem:GetActive ( )
return self.active
end
function ClanSystem:SetActive ( state )
self.active = state
self.clanMenu.window:SetVisible ( self.active )
Mouse:SetVisible ( self.active )
if ( not state ) then
self.createClan.window:SetVisible ( false )
self.colorPicker.window:SetVisible ( false )
self.manageClan.window:SetVisible ( false )
self.bank.window:SetVisible ( false )
self.confirm.window:SetVisible ( false )
self.invitations.window:SetVisible ( false )
self.clanList.window:SetVisible ( false )
end
end
function ClanSystem:KeyUp ( args )
if ( args.key == VirtualKey.F7 ) then
self:SetActive ( not self:GetActive ( ) )
end
end
function ClanSystem:LocalPlayerInput ( args )
if ( self:GetActive ( ) and Game:GetState ( ) == GUIState.Game ) then
return false
end
end
function ClanSystem:WindowClosed ( )
self:SetActive ( false )
end
function ClanSystem:SetColour ( )
local color = self.colorPicker.picker:GetColor ( )
self.colorPicker.colour = { color.r, color.g, color.b }
self.colorPicker.window:SetVisible ( false )
end
function ClanSystem:Colour ( )
self.colorPicker.window:SetVisible ( not self.colorPicker.window:GetVisible ( ) )
end
function ClanSystem:ManageClan ( )
Network:Send ( "Clans:GetData" )
end
function ClanSystem:LeaveClan ( )
self.confirm.window:SetVisible ( true )
self.confirm.action = "leave"
end
function ClanSystem:InvitePlayer ( )
local row = self.clanMenu.playersList:GetSelectedRow ( )
if ( row ~= nil ) then
local player = row:GetDataObject ( "id" )
Network:Send ( "Clans:Invite", player )
end
end
function ClanSystem:ClanList ( )
self.clanList.window:SetVisible ( true )
Network:Send ( "Clans:GetClans" )
end
function ClanSystem:Invitations ( )
self.invitations.window:SetVisible ( true )
Network:Send ( "Clans:Invitations" )
end
function ClanSystem:ReceiveInvitations ( invitations )
self.invitations.list:Clear ( )
if ( type ( invitations ) == "table" ) then
for index, clan in ipairs ( invitations ) do
self.invitations.rows [ clan ] = self.invitations.list:AddItem ( tostring ( clan ) )
self.invitations.rows [ clan ]:SetDataNumber ( "id", index )
end
end
end
function ClanSystem:AcceptInvite ( )
local row = self.invitations.list:GetSelectedRow ( )
if ( row ~= nil ) then
local clan = row:GetCellText ( 0 )
local index = row:GetDataNumber ( "id" )
Network:Send ( "Clans:AcceptInvite", { clan = clan, index = index } )
self.invitations.window:SetVisible ( false )
end
end
function ClanSystem:ReceiveClans ( clans )
self.clanList.list:Clear ( )
for name, data in pairs ( clans ) do
local item = self.clanList.list:AddItem ( tostring ( name ) )
item:SetCellText ( 1, ( data.type == "Open" and "Public" or "Invite Only" ) )
table.insert ( self.clanList.rows, item )
end
end
function ClanSystem:JoinClan ( )
local row = self.clanList.list:GetSelectedRow ( )
if ( row ~= nil ) then
local clan = row:GetCellText ( 0 )
Network:Send ( "Clans:JoinClan", clan )
self.clanList.window:SetVisible ( false )
end
end
function ClanSystem:ShowCreate ( )
self.createClan.window:SetVisible ( true )
end
function ClanSystem:Create ( )
local args = { }
args.name = self.createClan.nEdit:GetText ( )
if ( args.name ~= "" ) then
args.tag = self.createClan.tEdit:GetText ( )
args.colour = table.concat ( self.colorPicker.colour, ", " )
args.type = self.createClan.type:GetText ( )
Network:Send ( "Clans:Create", args )
self.createClan.window:SetVisible ( false )
else
LocalPlayer:Message ( "Faction: Please fill the name field.", "err" )
end
end
function ClanSystem:ReceiveData ( args )
self.manageClan.window:SetVisible ( true )
self.manageClan.dLabel:SetText ( "Faction name: ".. tostring ( args.clanData.name ) .."\n\nFaction tag: ".. tostring ( args.clanData.tag ) .."\n\nFaction type: ".. ( args.clanData.type == "Open" and "Public" or "Invite Only" ) .."\n\nTotal members: ".. tostring ( #args.members ) .."\n\nCreation date: ".. tostring ( args.clanData.creationDate ) )
self.manageClan.dLabel:SizeToContents ( )
self.motd.content:SetText ( args.clanData.motd )
self.bank.balance:SetText ( "Total balance: $".. convertNumberToString ( args.clanData.bank ) )
self.bank.balance:SizeToContents ( )
self.manageClan.mList:Clear ( )
for _, member in ipairs ( args.members ) do
local item = self.manageClan.mList:AddItem ( tostring ( member.name ) )
item:SetCellText ( 1, tostring ( member.rank ) )
item:SetCellText ( 2, tostring ( member.joinDate ) )
item:SetDataString ( "id", member.steamID )
table.insert ( self.manageClan.rows, item )
end
self.log.list:Clear ( )
if ( type ( args.messages ) == "table" ) then
for _, msg in ipairs ( args.messages ) do
if ( msg.type == "log" ) then
self.log.list:AddItem ( tostring ( msg.message ) )
end
end
end
end
function ClanSystem:Kick ( )
local row = self.manageClan.mList:GetSelectedRow ( )
if ( row ~= nil ) then
local steamID = row:GetDataString ( "id" )
local name = row:GetCellText ( 0 )
local rank = row:GetCellText ( 1 )
Network:Send ( "Clans:Kick", { name = name, steamID = steamID, rank = rank } )
end
end
function ClanSystem:SetRank ( )
local row = self.manageClan.mList:GetSelectedRow ( )
if ( row ~= nil ) then
local steamID = row:GetDataString ( "id" )
local name = row:GetCellText ( 0 )
local rank = self.manageClan.ranks:GetText ( )
local curRank = row:GetCellText ( 1 )
Network:Send ( "Clans:SetRank", { name = name, steamID = steamID, curRank = curRank, rank = rank } )
end
end
function ClanSystem:ShowBank ( )
self.bank.window:SetVisible ( not self.bank.window:GetVisible ( ) )
end
function ClanSystem:ShowLog ( )
self.log.window:SetVisible ( true )
end
function ClanSystem:ShowMotd ( )
self.motd.window:SetVisible ( true )
end
function ClanSystem:Remove ( )
self.confirm.window:SetVisible ( true )
self.confirm.action = "remove"
end
function ClanSystem:Chat ( )
end
function ClanSystem:Deposit ( )
local amount = tonumber ( self.bank.aEdit:GetText ( ) ) or 0
if ( amount > 0 ) then
Network:Send ( "Clans:UpdateBank", { action = "deposit", amount = amount } )
else
LocalPlayer:Message ( "Faction: Invalid amount.", "err" )
end
end
function ClanSystem:Withdraw ( )
local amount = tonumber ( self.bank.aEdit:GetText ( ) ) or 0
if ( amount > 0 ) then
Network:Send ( "Clans:UpdateBank", { action = "withdraw", amount = amount } )
else
LocalPlayer:Message ( "Faction: Invalid amount.", "err" )
end
end
function ClanSystem:UpdateBankLabel ( amount )
self.bank.balance:SetText ( "Total balance: $".. convertNumberToString ( amount ) )
self.bank.balance:SizeToContents ( )
end
function ClanSystem:Confirm ( )
if ( self.confirm.action == "remove" ) then
Network:Send ( "Clans:Remove" )
elseif ( self.confirm.action == "leave" ) then
Network:Send ( "Clans:Leave" )
end
self:SetActive ( false )
self.confirm.window:SetVisible ( false )
end
function ClanSystem:addPlayerToList ( player )
local item = self.clanMenu.playersList:AddItem ( tostring ( player:GetName ( ) ) )
item:SetVisible ( true )
item:SetDataObject ( "id", player )
self.playerToRow [ player:GetId ( ) ] = item
end
function ClanSystem:PlayerJoin ( args )
self:addPlayerToList ( args.player )
end
function ClanSystem:PlayerQuit ( args )
if ( self.playerToRow [ args.player:GetId ( ) ] ) then
self.clanMenu.playersList:RemoveItem ( self.playerToRow [ args.player:GetId ( ) ] )
end
end
function ClanSystem:SearchPlayer ( )
local text = self.clanMenu.searchEdit:GetText ( ):lower ( )
if ( text ~= "" and text:len ( ) > 0 ) then
for _, item in pairs ( self.playerToRow ) do
if ( type ( item ) == "userdata" ) then
item:SetVisible ( false )
if item:GetCellText ( 0 ):lower ( ):find ( text, 1, true ) then
item:SetVisible ( true )
end
end
end
else
for _, item in pairs ( self.playerToRow ) do
if ( type ( item ) == "userdata" ) then
item:SetVisible ( true )
end
end
end
end
function ClanSystem:SyncPlayerClans ( players )
self.playerClans = players
end
function ClanSystem:PostTick ( )
if ( Client:GetElapsedSeconds ( ) - self.LastTick >= 5 ) then
Network:Send ( "Clans:RequestSyncList", LocalPlayer )
self.LastTick = Client:GetElapsedSeconds ( )
end
end
function ClanSystem:GetPlayerClan ( player )
if ( type ( player ) == "userdata" ) then
if ( self.playerClans [ player:GetId ( ) ] ) then
return self.playerClans [ player:GetId ( ) ]
else
return false
end
else
return false
end
end
function ClanSystem:WeaponDamage ( args )
if ( type ( args.attacker ) == "userdata" ) then
if ( args.attacker:GetId ( ) ~= LocalPlayer:GetId ( ) ) then
local lpClan = self:GetPlayerClan ( LocalPlayer )
local atClan = self:GetPlayerClan ( args.attacker )
if ( lpClan and atClan ) then
if ( lpClan == atClan ) then
return false
end
end
end
end
end
function ClanSystem:UpdateMotd ( )
local text = self.motd.content:GetText ( )
Network:Send ( "Clans:UpdateMOTD", text )
end
function ClanSystem:ClearLog ( )
Network:Send ( "Clans:ClearLog" )
self.log.window:SetVisible ( false )
self.log.list:Clear ( )
end
clanSystem = ClanSystem ( )
function LocalPlayer:Message ( msg, color )
Chat:Print ( msg, msgColors [ color ] )
end
function convertNumberToString ( value )
if ( value and tonumber ( value ) ) then
local value = tostring ( value )
if string.sub ( value, 1, 1 ) == "-" then
return "-".. setCommasInNumber ( string.sub ( value, 2, #value ) )
else
return setCommasInNumber ( value )
end
end
return false
end
function setCommasInNumber ( value )
if ( #value > 3 ) then
return setCommasInNumber ( string.sub ( value, 1, #value - 3 ) ) ..",".. string.sub ( value, #value - 2, #value )
else
return value
end
end<file_sep>class "ClanSystem"
msgColors =
{
[ "err" ] = Color ( 255, 0, 0 ),
[ "info" ] = Color ( 0, 255, 0 ),
[ "warn" ] = Color ( 255, 100, 0 )
}
function ClanSystem:__init ( )
self.LastTick = 0
self.playerList = { }
self.clans = { }
self.clanMembers = { }
self.playerClan = { }
self.steamIDToPlayer = { }
self.invitations = { }
self.clanMessages = { }
self.permissions =
{
[ "Founder" ] =
{
kick = true,
invite = true,
setRank = true,
setMotd = true,
clearLog = true
},
[ "Co-Founder" ] =
{
kick = true,
invite = true,
setRank = true,
setMotd = true,
clearLog = true
},
[ "Deputy" ] =
{
kick = true,
invite = true,
setRank = false,
setMotd = false,
clearLog = false
},
[ "Member" ] =
{
kick = false,
invite = false,
setRank = false,
setMotd = false,
clearLog = false
},
}
for player in Server:GetPlayers ( ) do
self.steamIDToPlayer [ player:GetSteamId ( ).id ] = player
end
Network:Subscribe ( "Clans:Create", self, self.AddClan )
Network:Subscribe ( "Clans:Remove", self, self.RemoveClan )
Network:Subscribe ( "Clans:GetData", self, self.GetData )
Network:Subscribe ( "Clans:UpdateBank", self, self.UpdateBank )
Network:Subscribe ( "Clans:Leave", self, self.LeaveClan )
Network:Subscribe ( "Clans:Invite", self, self.InvitePlayer )
Network:Subscribe ( "Clans:Invitations", self, self.GetInvitations )
Network:Subscribe ( "Clans:AcceptInvite", self, self.AcceptInvite )
Network:Subscribe ( "Clans:GetClans", self, self.GetClans )
Network:Subscribe ( "Clans:JoinClan", self, self.JoinClan )
Network:Subscribe ( "Clans:Kick", self, self.KickPlayer )
Network:Subscribe ( "Clans:SetRank", self, self.SetPlayerRank )
Network:Subscribe ( "Clans:RequestSyncList", self, self.SendPlayerList )
Network:Subscribe ( "Clans:UpdateMOTD", self, self.UpdateMOTD )
Network:Subscribe ( "Clans:ClearLog", self, self.ClearLog )
Events:Subscribe ( "PlayerChat", self, self.FactionChat )
Events:Subscribe ( "PostTick", self, self.SyncPlayers )
Events:Subscribe ( "PlayerQuit", self, self.PlayerQuit )
SQL:Execute ( "CREATE TABLE IF NOT EXISTS clans ( name VARCHAR UNIQUE, creator VARCHAR, tag VARCHAR, colour VARCHAR, creationDate VARCHAR, bank INT, type VARCHAR, motd VARCHAR )" )
SQL:Execute ( "CREATE TABLE IF NOT EXISTS clan_members ( steamID VARCHAR UNIQUE, clan VARCHAR, name VARCHAR, rank VARCHAR, joinDate VARCHAR )" )
SQL:Execute ( "CREATE TABLE IF NOT EXISTS clan_messages ( clan VARCHAR, type VARCHAR, message VARCHAR, date VARCHAR )" )
local query = SQL:Query ( "SELECT * FROM clans" )
local result = query:Execute ( )
if ( #result > 0 ) then
for _, clan in ipairs ( result ) do
self.clans [ clan.name ] =
{
name = clan.name,
creator = clan.creator,
tag = clan.tag,
colour = clan.colour,
creationDate = clan.creationDate,
bank = clan.bank,
type = clan.type,
motd = clan.motd
}
self.clanMembers [ clan.name ] = { }
self.clanMessages [ clan.name ] = { }
end
end
print ( tostring ( #result ) .." faction(s) loaded!" )
local query = SQL:Query ( "SELECT * FROM clan_members" )
local result = query:Execute ( )
if ( #result > 0 ) then
for _, member in ipairs ( result ) do
if ( self.clanMembers [ member.clan ] ) then
table.insert (
self.clanMembers [ member.clan ],
{
steamID = member.steamID,
clan = member.clan,
name = member.name,
rank = member.rank,
joinDate = member.joinDate
}
)
self.playerClan [ member.steamID ] = { member.clan, #self.clanMembers [ member.clan ] }
end
end
end
print ( tostring ( #result ) .." faction member(s) loaded!" )
local query = SQL:Query ( "SELECT * FROM clan_messages" )
local result = query:Execute ( )
if ( #result > 0 ) then
for _, msg in ipairs ( result ) do
if ( self.clanMessages [ msg.clan ] ) then
table.insert (
self.clanMessages [ msg.clan ],
{
clan = msg.clan,
type = msg.type,
message = msg.message
}
)
end
end
end
print ( tostring ( #result ) .." faction message(s) loaded!" )
end
function ClanSystem:PlayerQuit ( args )
self.playerList [ args.player:GetId ( ) ] = nil
end
function ClanSystem:SendPlayerList ( player )
Network:Send ( player, "Clans:SyncPlayers", self.playerList )
end
function ClanSystem:SyncPlayers ( )
if ( Server:GetElapsedSeconds ( ) - self.LastTick >= 4 ) then
for player in Server:GetPlayers ( ) do
local clan = self:GetPlayerClan ( player )
self.playerList [ player:GetId ( ) ] = clan
end
self.LastTick = Server:GetElapsedSeconds ( )
end
end
function ClanSystem:AddClan ( args, player )
local clan = self:GetPlayerClan ( player )
if ( clan ) then
player:Message ( "Faction: You're already part of a faction.", "err" )
return false
end
if ( not self:Exists ( args.name ) ) then
local theDate = os.date ( "%c" )
local cmd = SQL:Command ( "INSERT INTO clans ( name, creator, tag, colour, creationDate, bank, type ) VALUES ( ?, ?, ?, ?, ?, ?, ? )" )
cmd:Bind ( 1, args.name )
cmd:Bind ( 2, player:GetSteamId ( ).id )
cmd:Bind ( 3, args.tag )
cmd:Bind ( 4, args.colour )
cmd:Bind ( 5, theDate )
cmd:Bind ( 6, 0 )
cmd:Bind ( 7, args.type )
cmd:Execute ( )
self.clans [ args.name ] =
{
name = args.name,
creator = player:GetSteamId ( ).id,
tag = args.tag,
colour = args.colour,
creationDate = theDate,
bank = 0,
type = args.type,
motd = ""
}
self.clanMembers [ args.name ] = { }
player:Message ( "Faction: You have created the faction ".. tostring ( args.name ) .."!", "info" )
self:AddMember (
{
player = player,
clan = args.name,
rank = "Founder"
}
)
else
player:Message ( "Faction: A faction with this name already exists!", "err" )
end
end
function ClanSystem:RemoveClan ( _, player )
local name = self:GetPlayerClan ( player )
if ( name ) then
if self:Exists ( name ) then
local cmd = SQL:Command ( "DELETE FROM clans WHERE name = ( ? )" )
cmd:Bind ( 1, name )
cmd:Execute ( )
local cmd = SQL:Command ( "DELETE FROM clan_members WHERE clan = ( ? )" )
cmd:Bind ( 1, name )
cmd:Execute ( )
self.clans [ name ] = nil
for _, member in ipairs ( self.clanMembers [ name ] ) do
self.playerClan [ member.steamID ] = nil
end
self.clanMembers [ name ] = nil
player:Message ( "Faction: You have removed the faction!", "warn" )
else
player:Message ( "Faction: The faction doesn't exist.", "err" )
end
else
player:Message ( "Faction: You ain't in a faction.", "err" )
end
end
function ClanSystem:AddMember ( args )
local theDate = os.date ( "%c" )
local cmd = SQL:Command ( "INSERT INTO clan_members ( steamID, clan, name, rank, joinDate ) VALUES ( ?, ?, ?, ?, ? )" )
cmd:Bind ( 1, args.player:GetSteamId ( ).id )
cmd:Bind ( 2, args.clan )
cmd:Bind ( 3, args.player:GetName ( ) )
cmd:Bind ( 4, args.rank )
cmd:Bind ( 5, theDate )
cmd:Execute ( )
table.insert (
self.clanMembers [ args.clan ],
{
steamID = args.player:GetSteamId ( ).id,
clan = args.clan,
name = args.player:GetName ( ),
rank = args.rank,
joinDate = theDate
}
)
self.playerClan [ args.player:GetSteamId ( ).id ] = { args.clan, #self.clanMembers [ args.clan ] }
args.player:Message ( "Faction: You have been added to ".. tostring ( args.clan ) .."!", "info" )
self:AddMessage ( args.clan, "log", args.player:GetName ( ) .." joined the faction." )
end
function ClanSystem:RemoveMember ( args )
local cmd = SQL:Command ( "DELETE FROM clan_members WHERE clan = ( ? ) AND steamID = ( ? )" )
cmd:Bind ( 1, args.clan )
cmd:Bind ( 2, args.steamID )
cmd:Execute ( )
local data = self.playerClan [ args.steamID ]
if ( data ) then
table.remove ( self.clanMembers [ args.clan ], data [ 2 ] )
end
self.playerClan [ args.steamID ] = nil
end
function ClanSystem:Exists ( name )
return ( self.clans [ name ] and true or false )
end
function ClanSystem:GetPlayerClan ( player )
if ( type ( player ) == "userdata" ) then
if ( self.playerClan [ player:GetSteamId ( ).id ] ) then
return self.playerClan [ player:GetSteamId ( ).id ] [ 1 ], self.playerClan [ player:GetSteamId ( ).id ] [ 2 ]
else
return false
end
else
return false
end
end
function ClanSystem:GetData ( _, player )
local clan = self:GetPlayerClan ( player )
if ( clan ) then
local args = { }
args.members = self.clanMembers [ clan ]
args.clanData = self.clans [ clan ]
args.messages = self.clanMessages [ clan ]
Network:Send ( player, "Clans:ReceiveData", args )
else
player:Message ( "Faction: You ain't in a faction.", "err" )
end
end
function ClanSystem:UpdateBank ( args, player )
local update = false
local clan = self:GetPlayerClan ( player )
if ( clan ) then
if ( args.action == "deposit" ) then
if ( player:GetMoney ( ) >= args.amount ) then
player:Message ( "Faction: You have deposited $".. convertNumberToString ( args.amount ) .."!", "info" )
player:SetMoney ( player:GetMoney ( ) - args.amount )
self:AddMessage ( clan, "log", player:GetName ( ) .." deposited $".. tostring ( convertNumberToString ( args.amount ) ) )
update = true
else
player:Message ( "Faction: You don't have $".. convertNumberToString ( args.amount ) .."!", "err" )
end
elseif ( args.action == "withdraw" ) then
if ( tonumber ( self:GetClanData ( clan, "bank" ) ) >= args.amount ) then
player:Message ( "Faction: You have withdrawn $".. convertNumberToString ( args.amount ) .."!", "info" )
player:SetMoney ( player:GetMoney ( ) + args.amount )
self:AddMessage ( clan, "log", player:GetName ( ) .." withdrawn $".. tostring ( convertNumberToString ( args.amount ) ) )
update = true
else
player:Message ( "Faction: The bank doesn't have $".. convertNumberToString ( args.amount ) .."!", "err" )
end
end
if ( update ) then
local amount = ( args.action == "deposit" and ( self:GetClanData ( clan, "bank" ) + args.amount ) or ( self:GetClanData ( clan, "bank" ) - args.amount ) )
local transaction = SQL:Transaction ( )
local query = SQL:Command ( "UPDATE clans SET bank = ? WHERE name = ?" )
query:Bind ( 1, amount )
query:Bind ( 2, clan )
query:Execute ( )
transaction:Commit ( )
self:SetClanData ( clan, "bank", amount )
Network:Send ( player, "Clans:UpdateBankLabel", amount )
end
end
end
function ClanSystem:LeaveClan ( _, player )
local clan, index = self:GetPlayerClan ( player )
if ( clan and index ) then
local steamID = player:GetSteamId ( ).id
local member = self.clanMembers [ clan ] [ index ]
if ( member ) then
if ( member.steamID == steamID ) then
if ( member.rank ~= "Founder" ) then
local args = { }
args.clan = clan
args.steamID = steamID
self:RemoveMember ( args )
player:Message ( "Faction: You have left the faction.", "warn" )
self:AddMessage ( clan, "log", player:GetName ( ) .." left the faction." )
else
player:Message ( "Faction: You can't leave the faction as you're the leader of it.", "err" )
end
else
player:Message ( "Faction: An error has occured, contact an admin.", "err" )
end
else
player:Message ( "Faction: An error has occured, contact an admin.", "err" )
end
else
player:Message ( "Faction: You ain't in a faction.", "err" )
end
end
function ClanSystem:InvitePlayer ( target, player )
local clan, index = self:GetPlayerClan ( player )
if ( clan and index ) then
if ( type ( target ) == "userdata" ) then
if self:IsPlayerAllowedTo ( { player = player, action = "invite" } ) then
local tClan = self:GetPlayerClan ( target )
if ( not tClan ) then
self:AddInvitation ( target, clan )
player:Message ( "Faction: You have invited ".. target:GetName ( ) .." to the faction.", "info" )
self:AddMessage ( clan, "log", player:GetName ( ) .." invited ".. tostring ( target:GetName ( ) ) .."." )
else
player:Message ( "Faction: This player is already in a faction.", "err" )
end
else
player:Message ( "Faction: You can't use this function.", "err" )
end
else
player:Message ( "Faction: Invalid player.", "err" )
end
else
player:Message ( "Faction: You ain't in a faction.", "err" )
end
end
function ClanSystem:GetClanData ( clan, data )
local clanData = self.clans [ clan ]
if ( type ( clanData ) == "table" ) then
return clanData [ data ]
end
return false
end
function ClanSystem:SetClanData ( clan, data, value )
local clanData = self.clans [ clan ]
if ( type ( clanData ) == "table" ) then
self.clans [ clan ] [ data ] = value
return true
end
return false
end
function ClanSystem:AddInvitation ( player, clan )
if ( type ( player ) == "userdata" ) then
if self:Exists ( clan ) then
if ( not self.invitations [ player:GetId ( ) ] ) then
self.invitations [ player:GetId ( ) ] = { }
end
player:Message ( "Faction: You have been invited to ".. tostring ( clan ) .."!", "info" )
table.insert ( self.invitations [ player:GetId ( ) ], clan )
end
end
end
function ClanSystem:GetInvitations ( _, player )
Network:Send ( player, "Clans:ReceiveInvitations", self.invitations [ player:GetId ( ) ] )
end
function ClanSystem:AcceptInvite ( args, player )
if self:Exists ( args.clan ) then
local clan = self:GetPlayerClan ( player )
if ( not clan ) then
self:AddMember (
{
player = player,
clan = args.clan,
rank = "Member"
}
)
table.remove ( self.invitations [ player:GetId ( ) ], args.index )
else
player:Message ( "Faction: You're already part of a faction.", "err" )
end
else
player:Message ( "Faction: The faction no longer exists.", "err" )
end
end
function ClanSystem:GetClans ( _, player )
Network:Send ( player, "Clans:ReceiveClans", self.clans )
end
function ClanSystem:JoinClan ( clan, player )
if self:Exists ( clan ) then
local pClan = self:GetPlayerClan ( player )
if ( not pClan ) then
if ( self.clans [ clan ].type == "Open" ) then
self:AddMember (
{
player = player,
clan = clan,
rank = "Member"
}
)
else
player:Message ( "Faction: This is an invite-only faction.", "err" )
end
else
player:Message ( "Faction: You're already part of a faction.", "err" )
end
else
player:Message ( "Faction: The faction no longer exists.", "err" )
end
end
function ClanSystem:KickPlayer ( args, player )
local clan = self:GetPlayerClan ( player )
if ( clan ) then
if self:IsPlayerAllowedTo ( { player = player, action = "kick" } ) then
local member = self.playerClan [ args.steamID ]
if ( member ) then
if ( args.rank ~= "Founder" ) then
local margs = { }
margs.clan = clan
margs.steamID = args.steamID
self:RemoveMember ( margs )
player:Message ( "Faction: You have kicked ".. tostring ( args.name ) .."!", "warn" )
self:GetData ( nil, player )
self:AddMessage ( clan, "log", player:GetName ( ) .." kicked ".. tostring ( args.name ) .."." )
else
player:Message ( "Faction: The founder of the faction cannot be kicked.", "err" )
end
else
player:Message ( "Faction: Member not found.", "err" )
end
else
player:Message ( "Faction: You can't use this function.", "err" )
end
else
player:Message ( "Faction: You ain't in a faction.", "err" )
end
end
function ClanSystem:SetPlayerRank ( args, player )
local clan = self:GetPlayerClan ( player )
if ( clan ) then
local myRank = self:GetMemberData ( { steamID = player:GetSteamId ( ).id, data = "rank" } )
if self:IsPlayerAllowedTo ( { player = player, action = "setRank" } ) then
local memberRank = self:GetMemberData ( { steamID = args.steamID, data = "rank" } )
if ( memberRank ) then
if ( memberRank ~= "Founder" ) then
if ( memberRank ~= myRank ) then
if ( memberRank ~= args.rank ) then
if self:SetMemberData ( { steamID = args.steamID, data = "rank", value = args.rank } ) then
self:GetData ( nil, player )
player:Message ( "Faction: You have set ".. tostring ( args.name ) .."'s rank to ".. tostring ( args.rank ) .."!", "info" )
self:AddMessage ( clan, "log", player:GetName ( ) .." changed ".. tostring ( args.name ) .."'s rank to ".. tostring ( args.rank ) .."." )
else
player:Message ( "Faction: Unable to set rank, contact an admin.", "err" )
end
else
player:Message ( "Faction: ".. tostring ( args.name ) .."'s rank is already ".. tostring ( args.rank ) .."!", "err" )
end
else
player:Message ( "Faction: You can't set the rank of a member of the same rank as yours.", "err" )
end
else
player:Message ( "Faction: You can't set the founder's rank.", "err" )
end
else
player:Message ( "Faction: Member not found.", "err" )
end
else
player:Message ( "Faction: You can't use this function.", "err" )
end
else
player:Message ( "Faction: You ain't in a faction.", "err" )
end
end
function ClanSystem:GetMemberData ( args )
local clan = self.playerClan [ args.steamID ]
if ( clan ) then
local clanName = clan [ 1 ]
local index = clan [ 2 ]
local members = self.clanMembers [ clanName ]
if ( members ) then
local member = members [ index ]
if ( type ( member ) == "table" ) then
return member [ args.data ]
else
return false
end
else
return false
end
else
return false
end
end
function ClanSystem:SetMemberData ( args )
local clan = self.playerClan [ args.steamID ]
if ( clan ) then
local clanName = clan [ 1 ]
local index = clan [ 2 ]
local members = self.clanMembers [ clanName ]
if ( members ) then
local member = members [ index ]
if ( type ( member ) == "table" ) then
self.clanMembers [ clanName ] [ index ] [ args.data ] = args.value
local transaction = SQL:Transaction ( )
local query = SQL:Command ( "UPDATE clan_members SET ".. tostring ( args.data ) .." = ? WHERE clan = ? and steamID = ?" )
query:Bind ( 1, args.value )
query:Bind ( 2, clanName )
query:Bind ( 3, args.steamID )
query:Execute ( )
transaction:Commit ( )
return true
else
return false
end
else
return false
end
else
return false
end
end
function ClanSystem:IsPlayerAllowedTo ( args )
local clan = self:GetPlayerClan ( args.player )
if ( clan ) then
local rank = self:GetMemberData ( { steamID = args.player:GetSteamId ( ).id, data = "rank" } )
if ( rank ) then
return self.permissions [ rank ] [ args.action ]
else
return false
end
else
return false
end
end
function Player:Message ( msg, color )
self:SendChatMessage ( msg, msgColors [ color ] )
end
function ClanSystem:AddMessage ( clan, type, msg )
if self:Exists ( clan ) then
local cmd = SQL:Command ( "INSERT INTO clan_messages ( clan, type, message, date ) VALUES ( ?, ?, ?, ? )" )
cmd:Bind ( 1, clan )
cmd:Bind ( 2, type )
cmd:Bind ( 3, msg )
cmd:Bind ( 4, os.date ( "%c" ) )
cmd:Execute ( )
if ( not self.clanMessages [ clan ] ) then
self.clanMessages [ clan ] = { }
end
table.insert (
self.clanMessages [ clan ],
{
clan = clan,
type = type,
message = msg
}
)
end
end
function ClanSystem:FactionChat ( args )
local msg = args.text
if ( msg:sub ( 1, 1 ) ~= "/" ) then
return true
end
local msg = msg:sub ( 2 )
local cmd_args = msg:split ( " " )
local cmd_name = cmd_args [ 1 ]:lower ( )
if ( cmd_name == "f" ) then
table.remove ( cmd_args, 1 )
local clan = self:GetPlayerClan ( args.player )
if ( clan ) then
local pName = args.player:GetName ( )
local colour = ( self.clans [ clan ].colour:split ( "," ) or { 255, 255, 255 } )
local r, g, b = table.unpack ( colour )
for player in Server:GetPlayers ( ) do
local pClan = self:GetPlayerClan ( player )
if ( pClan ) then
if ( pClan == clan ) then
player:SendChatMessage ( "(Faction Chat) ".. tostring ( pName ) ..": ".. tostring ( table.concat ( cmd_args, " ") ), Color ( tonumber ( r ), tonumber ( g ), tonumber ( b ) ) )
end
end
end
end
end
end
function ClanSystem:UpdateMOTD ( text, player )
local clan = self:GetPlayerClan ( player )
if ( clan ) then
if self:IsPlayerAllowedTo ( { player = player, action = "setMotd" } ) then
local transaction = SQL:Transaction ( )
local query = SQL:Command ( "UPDATE clans SET motd = ? WHERE name = ?" )
query:Bind ( 1, text )
query:Bind ( 2, clan )
query:Execute ( )
transaction:Commit ( )
self:SetClanData ( clan, "motd", text )
player:Message ( "Faction: MOTD successfully updated.", "info" )
self:AddMessage ( clan, "log", player:GetName ( ) .." updated the faction MOTD." )
else
player:Message ( "Faction: You can't use this function.", "err" )
end
else
player:Message ( "Faction: You ain't in a faction.", "err" )
end
end
function ClanSystem:ClearLog ( _, player )
local clan = self:GetPlayerClan ( player )
if ( clan ) then
if self:IsPlayerAllowedTo ( { player = player, action = "clearLog" } ) then
local cmd = SQL:Command ( "DELETE FROM clan_messages WHERE clan = ( ? )" )
cmd:Bind ( 1, clan )
cmd:Execute ( )
self.clanMessages [ clan ] = { }
player:Message ( "Faction: Log successfully cleared.", "info" )
self:AddMessage ( clan, "log", player:GetName ( ) .." cleared the faction log." )
else
player:Message ( "Faction: You can't use this function.", "err" )
end
else
player:Message ( "Faction: You ain't in a faction.", "err" )
end
end
clanSystem = ClanSystem ( )
function convertNumberToString ( value )
if ( value and tonumber ( value ) ) then
local value = tostring ( value )
if string.sub ( value, 1, 1 ) == "-" then
return "-".. setCommasInNumber ( string.sub ( value, 2, #value ) )
else
return setCommasInNumber ( value )
end
end
return false
end
function setCommasInNumber ( value )
if ( #value > 3 ) then
return setCommasInNumber ( string.sub ( value, 1, #value - 3 ) ) ..",".. string.sub ( value, #value - 2, #value )
else
return value
end
end
<file_sep>A GUI based faction system with several features, which you can read below.
*Private and public faction creation
*Player invitation
*Faction list
*SQL saved factions
*Faction management panel
*Rank system
*Faction bank
*Faction log
*Faction MOTD
Screenshot: http://i.imgur.com/SKWHCf7.png
Key to open faction menu: F7
|
40e98e57e854221079aec056af933a6b5c8cb485
|
[
"Markdown",
"Lua"
] | 3
|
Lua
|
Castillos15/factions
|
2432c2031af7221b6aa624fc263902a15a83f1e0
|
cfbd896a5e44874bdb9b2d76c3d5090b799b8dfd
|
refs/heads/master
|
<file_sep>/*
GAME RULES:
- The game has 2 players, playing in rounds
- In each turn, a player rolls a dice as many times as he whishes. Each result get added to his ROUND score
- BUT, if the player rolls a 1, all his ROUND score gets lost. After that, it's the next player's turn
- The player can choose to 'Hold', which means that his ROUND score gets added to his GLBAL score. After that, it's the next player's turn
- The first player to reach 100 points on GLOBAL score wins the game
*/
const PlayerCtrl = (function() {
const data = {
scores: [0, 0],
roundScore: 0,
activePlayer: 0,
gamePlaying: true
};
return {
init: () => {
data.gamePlaying = true;
data.scores = [0, 0];
data.roundScore = 0;
data.activePlayer = 0;
},
getScore: activePlayer => data.scores[activePlayer],
getRoudScore: () => data.roundScore,
getActivePlayer: () => data.activePlayer,
getGamePlaying: () => data.gamePlaying,
addRoundScore: dice => (data.roundScore += dice),
addScore: (score, activePlayer) => (data.scores[activePlayer] += score),
updateGamePlaying: bool => (data.gamePlaying = bool),
nextPlayer: () => {
data.activePlayer === 0
? (data.activePlayer = 1)
: (data.activePlayer = 0);
data.roundScore = 0;
}
};
})();
const UICtrl = (function() {
const UISelectors = {
dice: ".dice",
btnHold: ".btn-hold",
btnRoll: ".btn-roll",
newBtn: ".btn-new",
currentScore: ".player-current-score",
playerPanel: ".player-panel",
playerScore: ".player-score",
playerName: ".player-name"
};
const UIDoms = {
diceDOM: document.querySelector(UISelectors.dice),
scoreAllDOM: document.querySelectorAll(UISelectors.playerScore),
currentAllDOM: document.querySelectorAll(UISelectors.currentScore),
nameAllDOM: document.querySelectorAll(UISelectors.playerName),
panelAllDOM: document.querySelectorAll(UISelectors.playerPanel)
};
return {
init: () => {
UIDoms.diceDOM.style.display = "none";
UIDoms.scoreAllDOM.forEach(scoreDOM => (scoreDOM.textContent = "0"));
UIDoms.currentAllDOM.forEach(currDOM => (currDOM.textContent = "0"));
UIDoms.nameAllDOM.forEach(
(nameDOM, index) => (nameDOM.textContent = `Player ${index + 1}`)
);
UIDoms.panelAllDOM.forEach(panelDOM => {
panelDOM.classList.remove("winner");
panelDOM.classList.remove("active");
});
UIDoms.panelAllDOM.forEach((panelDOM, index) => {
if (index === 0) panelDOM.classList.add("active");
});
},
getSelectors: () => UISelectors,
displayDice: dice => {
UIDoms.diceDOM.style.display = "block";
UIDoms.diceDOM.src = `dice-${dice}.png`;
},
displayCurrentScore: (score, activePlayer) =>
(UIDoms.currentAllDOM[activePlayer].textContent = score),
displayScore: (scores, activePlayer) =>
(UIDoms.scoreAllDOM[activePlayer].textContent = scores),
displayWonPlayer: activePlayer => {
UIDoms.nameAllDOM[activePlayer].textContent = "Winner!";
UIDoms.diceDOM.style.display = "none";
UIDoms.panelAllDOM[activePlayer].classList.add("winner");
UIDoms.panelAllDOM[activePlayer].classList.remove("active");
},
nextPlayer: () => {
UIDoms.currentAllDOM.forEach(currDOM => (currDOM.textContent = "0"));
UIDoms.panelAllDOM.forEach(panelDOM =>
panelDOM.classList.toggle("active")
);
UIDoms.diceDOM.style.display = "none";
}
};
})();
const App = (function(PlayerCtrl, UICtrl) {
const loadEventListeners = () => {
const UISelectors = UICtrl.getSelectors();
// roll dice event
document
.querySelector(UISelectors.btnRoll)
.addEventListener("click", rollDice);
// hold score event
document
.querySelector(UISelectors.btnHold)
.addEventListener("click", holdScore);
// new game event
document.querySelector(UISelectors.newBtn).addEventListener("click", init);
};
const rollDice = () => {
if (PlayerCtrl.getGamePlaying()) {
// Random number(1 ~ 6)
let dice = Math.floor(Math.random() * 6) + 1;
// Display the result
UICtrl.displayDice(dice);
// Update the round score if the rolled number was not a 1
if (dice !== 1) {
// Add score
const roundScore = PlayerCtrl.addRoundScore(dice);
UICtrl.displayCurrentScore(roundScore, PlayerCtrl.getActivePlayer());
} else {
// Next player
PlayerCtrl.nextPlayer();
UICtrl.nextPlayer();
}
}
};
const holdScore = () => {
const activePlayer = PlayerCtrl.getActivePlayer();
if (PlayerCtrl.getGamePlaying()) {
// Add current score to global score
PlayerCtrl.addScore(PlayerCtrl.getRoudScore(), activePlayer);
const playerScore = PlayerCtrl.getScore(activePlayer);
// update the UI
UICtrl.displayScore(playerScore, activePlayer);
// check if player won the game
if (playerScore >= 20) {
UICtrl.displayWonPlayer(activePlayer);
PlayerCtrl.updateGamePlaying(false);
} else {
// Next player
PlayerCtrl.nextPlayer();
UICtrl.nextPlayer();
}
}
};
const init = () => {
PlayerCtrl.init();
UICtrl.init();
};
return {
init: () => {
loadEventListeners();
init();
}
};
})(PlayerCtrl, UICtrl);
App.init();
|
abd4844c0d038c318ffeb6ba43f2fd85140b3c00
|
[
"JavaScript"
] | 1
|
JavaScript
|
kino0104/js-pig-game
|
6acd7e93ee4a4c009e2da33ebd4605b450ff8f79
|
f0a2cf47aed9fb39235fc84f8fa06b15805daa22
|
refs/heads/master
|
<file_sep>from fractions import Fraction
class Matrix(object):
@classmethod
def identity_matrix(cls, dim: int):
im = cls(dim)
for i in range(dim):
im[i, i] = 1
return im
def __init__(self, dim: int, fill=0):
if dim < 1:
raise Exception('Dimension cannot be <1')
self.dim = dim
self.A = [[Fraction(fill)] * self.dim for _ in range(self.dim)]
def __getitem__(self, indexes):
if isinstance(indexes, tuple):
return self.A[indexes[0]][indexes[1]]
else:
return self.A[indexes]
def __setitem__(self, key, value):
if isinstance(key, tuple):
self.A[key[0]][key[1]] = Fraction(value)
else:
self.A[key] = value
def __repr__(self):
represent = ""
for i in range(len(self.A)):
represent += ', '.join(map(lambda x: '{}/{}'.format(x.numerator, x.denominator), self.A[i])) + "\n"
return represent
def __str__(self):
return self.__repr__()
def _non_matrix_op(self, other, op):
func = {'add': lambda x, y: x + y,
'mul': lambda x, y: x * y}[op]
result = Matrix(self.dim)
if isinstance(other, Matrix):
if other.dim == self.dim and other.dim == self.dim:
for i in range(result.dim):
for j in range(result.dim):
result[i, j] = func(self[i, j], other[i, j])
else:
raise Exception('Trying to operate ({s}, {s}) matrix with ({o}, {o}) matrix'
.format(s=self.dim, o=other.dim))
elif isinstance(other, int) or isinstance(other, float):
for i in range(result.dim):
for j in range(result.dim):
result[i, j] = func(self[i, j], other)
else:
raise Exception('Type mismatch. Matrix cannot be operated to {}'.format(type(other)))
return result
def __add__(self, other):
return self._non_matrix_op(other, 'add')
def __radd__(self, other):
return self.__add__(other)
def __mul__(self, other):
return self._non_matrix_op(other, 'mul')
def __rmul__(self, other):
return self.__mul__(other)
def __matmul__(self, other):
if isinstance(other, Matrix):
if self.dim == other.dim:
result = Matrix(self.dim)
for i in range(self.dim):
for j in range(self.dim):
acc = 0
for k in range(self.dim):
acc += self[i, k] * other[k, j]
result[i, j] = acc
else:
raise Exception('Dimension mismatch. Trying to multiple ({s}, {s}) matrix with ({o}, {o})'
.format(s=self.dim, o=other.dim))
else:
raise Exception('Cannot MatMul Matrix with non-matrix object. Try standard multiplication')
return result
def transpose(self):
for i in range(self.dim):
for j in range(i, self.dim):
tmp = self[i, j]
self[i, j] = self[j, i]
self[j, i] = tmp
return self
def _change_zero(self, start_index):
check = False
for i in range(start_index + 1, self.dim):
if self[i, start_index] != 0:
tmp = self[i]
self[i] = self[start_index]
self[start_index] = tmp
check = True
break
if not check:
raise Exception("Inverse matrix does not exist")
return self
def copy(self):
result = Matrix(dim=self.dim)
for i in range(result.dim):
for j in range(result.dim):
result[i, j] = self[i, j]
return result
def inverse(self):
self_copy = self.copy()
ident_mat = Matrix.identity_matrix(self.dim)
if self_copy[0, 0] == 0:
self_copy._change_zero(0)
mult = self_copy[0, 0]
for j in range(0, self_copy.dim):
ident_mat[0, j] = ident_mat[0, j] / mult
self_copy[0, j] = self_copy[0, j] / mult
for k in range(0, self_copy.dim):
for i in range(0, self_copy.dim):
if k != i:
mult = self_copy[i, k] / self_copy[k, k]
for j in range(0, self_copy.dim):
ident_mat[i, j] -= ident_mat[k, j] * mult
self_copy[i, j] -= self_copy[k, j] * mult
if self_copy[i, i] == 0:
self_copy._change_zero(i)
ii = self_copy[i, i]
for j in range(0, self_copy.dim):
ident_mat[i, j] /= ii
self_copy[i, j] /= ii
return ident_mat
def determinant(self):
pass
<file_sep>from matrix import Matrix
if __name__ == '__main__':
a = Matrix(3)
for i in range(0, a.dim):
for j in range(0, a.dim):
a[i, j] = j + i*3
a[0, 0] = 7
print(a)
print(a.transpose())
b = a.inverse()
print(b)
print((a @ b) * 2)
|
24f9125c4551d280ab2a5eb7a335b49c5fcd0058
|
[
"Python"
] | 2
|
Python
|
Marqueeze/COURSES_lab2
|
a0517d5e7c5eb1cc42740c6431c9a94961e7cf5e
|
5ac08fdd5c3365a35af560c8b13c703ea018f642
|
refs/heads/master
|
<file_sep># CS572MWA_Day8
CS572MWA_Day8
<file_sep>var express = require('express');
var router = express.Router();
const mongoClient = require('mongodb').MongoClient;
router.get('/read/:name', function (request, response, next) {
mongoClient.connect('mongodb://127.0.0.1:27017/lab8', (err, client) => {
if (err) throw err;
const db = client.db('lab8');
db.collection('Location').findOne({ 'name': request.params.name }, (err, doc) => {
if (err) throw err;
response.send(doc);
});
});
});
const getAll = function (response) {
mongoClient.connect('mongodb://127.0.0.1:27017/lab8', (err, client) => {
if (err) throw err;
const db = client.db('lab8');
let docs = [];
let cursor = db.collection('Location').find({});
cursor.each((err, doc) => {
if (err) throw err;
if (doc) {
console.log(doc);
docs.push(doc);
} else {
response.send(docs);
}
});
});
}
router.get('/read', function (request, response, next) {
getAll(response);
});
router.post('/create', function (request, response, next) {
mongoClient.connect('mongodb://127.0.0.1:27017/lab8', (err, client) => {
if (err) throw err;
const db = client.db('lab8');
db.collection('Location').insertOne(request.body, function (err, res) {
if (err) throw err;
console.log("1 document inserted");
getAll(response);
});
});
});
router.put('/update/:name', function (request, response, next) {
mongoClient.connect('mongodb://127.0.0.1:27017/lab8', (err, client) => {
if (err) throw err;
const db = client.db('lab8');
const query = { name: request.params.name };
db.collection('Location').updateOne(query, request.body, function (err, res) {
if (err) throw err;
console.log("1 document updated");
getAll(response);
});
});
});
router.delete('/delete/:name', function (request, response, next) {
mongoClient.connect('mongodb://127.0.0.1:27017/lab8', (err, client) => {
if (err) throw err;
const db = client.db('lab8');
const query = { name: request.params.name };
db.collection('Location').deleteOne(query, request.body, function (err, res) {
if (err) throw err;
console.log("1 document deleted");
getAll(response);
});
});
});
router.get('/nearest', function (request, response, next) {
mongoClient.connect('mongodb://127.0.0.1:27017/lab8', (err, client) => {
if (err) throw err;
const db = client.db('lab8');
let docs = [];
let cursor = db.collection('Location').find({ location: { '$near': [-91.9673635, 41.0177226] } }).limit(3);
cursor.each((err, doc) => {
if (err) throw err;
if (doc) {
console.log(doc);
docs.push(doc);
} else {
response.send(docs);
}
});
});
});
module.exports = router;
|
1ccd632b9c92178ea7e39cc9889a783065eb8223
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
AymanElakhwas/CS572MWA_Day8
|
915b4c88378870f41ca77a9140413f3bffa32ad1
|
012a7c0547ba237b4c542057ffc070c1afa49112
|
refs/heads/master
|
<file_sep># jsf-udemy-cd
## Bean Scope
@ApplicationScoped: Bean is created only one time and shared with all users
@SessionScoped: Bean is created once for each user and is unique for this user
@RequestScoped: A new Bean is created for every request (Default Scope)
<file_sep>package bean;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
@ManagedBean
@ApplicationScoped
public class StudentDataUtil {
private List<Student> students;
public StudentDataUtil() {
loadSampleData();
}
public void loadSampleData() {
students = new ArrayList<>();
students.add(new Student("<NAME>", "<NAME>", "<EMAIL>"));
students.add(new Student("<NAME>", "<NAME>", "<EMAIL>"));
students.add(new Student("<NAME>", "<NAME>", "<EMAIL>"));
}
public List<Student> getStudents() {
return students;
}
}
<file_sep>package hello;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class StudentFive {
private String firstName;
private String lastName;
private String favoriteLanguage;
// Programming Languages
List<String> programmingLanguageOptions;
// no-args constructor
public StudentFive() {
programmingLanguageOptions = new ArrayList<>();
programmingLanguageOptions.add("Java");
programmingLanguageOptions.add("C#");
programmingLanguageOptions.add("PHP");
programmingLanguageOptions.add("Ruby");
// pre-populate the bean
firstName = "Apollo";
lastName = "Pissuti";
favoriteLanguage = "Ruby";
}
// getters/setters
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 getFavoriteLanguage() {
return favoriteLanguage;
}
public void setFavoriteLanguage(String favoriteLanguage) {
this.favoriteLanguage = favoriteLanguage;
}
public List<String> getProgrammingLanguageOptions() {
return programmingLanguageOptions;
}
public void setProgrammingLanguageOptions(List<String> programmingLanguageOptions) {
this.programmingLanguageOptions = programmingLanguageOptions;
}
}
|
739002e5193b79f48f34a2a021a72752285e17e1
|
[
"Markdown",
"Java"
] | 3
|
Markdown
|
nathipg/jsf-udemy-cd
|
59fe31e0c00b9030fd265c88bf9a520a72062c4a
|
ecb2bb9122731f241bbc7b62a083db5eb6546e3e
|
refs/heads/master
|
<repo_name>mayank-pq2q4/search<file_sep>/pa2.c
#include <stdio.h>
int recursive_binary_index(int key ,int arr[], int low,int high){
//printf("%d\n",high );
int btw = ((high + low)/2);
printf("...\n" );
printf("...\n" );
printf("%d\n",btw);
if (key>arr[btw]) {
return recursive_binary_index(key,arr,btw+1,high);
/*printf("%d\n",btw );*/
}
else if (key<arr[btw]) {
return recursive_binary_index(key,arr,0,btw-1);
/*printf("%d\n",btw );*/
}
else if (key==arr[btw]) {
/*printf("%d\n",btw );*/
return (btw);
}
else{
printf("number not in array\n" );
return 0;
}
// for (int i = 0; i < high; i++) {
// printf("%d
//printf("\
}
}
int main(int argc, char const *argv[]) {
int size;
int key;
int b[15];
printf("enter key\n" );
scanf("%d", &key);
printf("enter yo size man\n" );
scanf("%d",&size);
for (int i = 0; i < size; i++) {
if (i==0) {
printf("enter num\n" );
scanf("%d", &b[i]);
}
if (i!=0) {
printf("enter next num\n" );
scanf("%d", &b[i]);
}
}
printf("%d",size);
printf("the index is: arr[%d]\n", recursive_binary_index(key,b,0,size-1));
return 0;
}
<file_sep>/README.md
# search
The following codes can be implemented for binary search:
>Linear,
>Binary,
>Ternary
#lab2 (search)
<file_sep>/pa1.c
#include <stdio.h>
int main(int argc, char const *argv[]) {
float a[5];
printf("enter the search number:\n" );
float b;
scanf("%f", &(b) );
for (int i = 0; i < 5; i++) {
printf("enter the numba man\n" );
scanf("%f", &a[i] );
}
for (int j = 0; j < 5; j++) {
if (a[j]== b) {
printf("The num is at %dth index.\n", j);
}
}
return 0;
}
|
14243279d45ab181f8ea1454f1d7854d14f509a5
|
[
"Markdown",
"C"
] | 3
|
C
|
mayank-pq2q4/search
|
dfb164bde608c8f2795466b758faa557af317e62
|
9f4ebf4b6bea3ed86c0cc6dcc1ffc57d9db64aa1
|
refs/heads/master
|
<file_sep>package driod.dicex;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.afree.chart.AFreeChart;
import org.afree.chart.ChartFactory;
import org.afree.chart.axis.NumberAxis;
import org.afree.chart.plot.CategoryPlot;
import org.afree.chart.plot.PlotOrientation;
import org.afree.data.category.DefaultCategoryDataset;
import org.afree.graphics.geom.RectShape;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
/**
* DriodDiceXChartView
* @author yasupong
*/
public class DriodDiceXChartView extends View {
/** ログリスト */
private List<DriodDiceXScoreEntity> logList = null;
private String chart_name = null;
private String chart_x_label = null;
private String chart_y_label = null;
private String chart_plot = null;
/**
* コンストラクター
* @param context
* @param attrs
* @param defStyle
*/
public DriodDiceXChartView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* コンストラクター
* @param context
* @param attrs
*/
public DriodDiceXChartView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* コンストラクター
* @param context
*/
public DriodDiceXChartView(Context context) {
super(context);
}
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
RectShape chartArea = new RectShape(0,0,canvas.getWidth(),400);
DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
if (logList != null && logList.size() > 0) {
List<String> wkList = new ArrayList<String>();
List<String> wkDateList = new ArrayList<String>();
for (Iterator<DriodDiceXScoreEntity> iterator = logList.iterator(); iterator.hasNext();) {
DriodDiceXScoreEntity data = (DriodDiceXScoreEntity) iterator.next();
wkList.add(data.getScore());
wkDateList.add(data.getScoredate().substring(5, 16));
}
for (int i = 0; i < wkList.size(); i++) {
dataSet.addValue(Double.parseDouble(wkList.get(i)), chart_plot, wkDateList.get(i));
}
}
AFreeChart chart = ChartFactory.createBarChart(chart_name,chart_x_label,chart_y_label,dataSet,PlotOrientation.VERTICAL,true,false,false);
// 整数だけにする
CategoryPlot plot = chart.getCategoryPlot();
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
chart.draw(canvas, chartArea);
}
/**
* ログリスト取得
* @param logList
*/
public void setLogList(List<DriodDiceXScoreEntity> logList) {
this.logList = logList;
}
/**
* @param chart_name the chart_name to set
*/
public void setChart_name(String chart_name) {
this.chart_name = chart_name;
}
/**
* @param chart_x_label the chart_x_label to set
*/
public void setChart_x_label(String chart_x_label) {
this.chart_x_label = chart_x_label;
}
/**
* @param chart_y_label the chart_y_label to set
*/
public void setChart_y_label(String chart_y_label) {
this.chart_y_label = chart_y_label;
}
/**
* @param chart_plot the chart_plot to set
*/
public void setChart_plot(String chart_plot) {
this.chart_plot = chart_plot;
}
}
|
58a337c88b5cc057f58bc88e73f3323db19daa2e
|
[
"Java"
] | 1
|
Java
|
yasupong/droid_dicex
|
6078b294d294644142ba94b706ab4beeaee72327
|
3207cb501e587e30398b4266fdabd0da03de9bcb
|
refs/heads/master
|
<file_sep>import os
import unittest
from diskspace import bytes_to_readable, print_tree, subprocess_check_output, show_space_list
class TestDiskSpace(unittest.TestCase):
def test_subprocess_check_output(self):
func = subprocess_check_output('pwd')
cwd = os.getcwd()+'\n'
self.assertEquals(cwd, func)
def test_subprocess_check_output_error(self):
with self.assertRaises(OSError): subprocess_check_output('not')
def test_bytes_to_readable_B(self):
func = bytes_to_readable(1)
self.assertEquals('512.00B', func)
def test_bytes_to_readable_Kb(self):
func = bytes_to_readable(1024)
self.assertEquals('512.00Kb', func)
def test_bytes_to_readable_Mb(self):
func = bytes_to_readable(1048576)
self.assertEquals('512.00Mb', func)
def test_bytes_to_readable_Gb(self):
func = bytes_to_readable(1073750000)
self.assertEquals('512.00Gb', func)
def test_bytes_to_readable_Tb(self):
func = bytes_to_readable(1099504999000)
self.assertEquals('512.00Tb', func)
def test_bytes_to_readable_error(self):
with self.assertRaises(TypeError): bytes_to_readable('test')
if __name__ == '__main__':
unittest.main()
|
4699614ee2ce1d9d249278abe7fc05b910e7bc64
|
[
"Python"
] | 1
|
Python
|
TecProg-20181/05--Hiroshi18
|
76289704dd2633c5324a04c7a8e6b16596b1411d
|
ac804b0057fab74ca4c1f96a3b8db9379db4cb56
|
refs/heads/main
|
<repo_name>hasibahmad1995/Course-Understanding-and-Visualizing-Data-with-Python-Week1-<file_sep>/libraries_data_management.py
#!/usr/bin/env python
# coding: utf-8
# # Python Libraries
#
# Python, like other programming languages, has an abundance of additional modules or libraries that augument the base framework and functionality of the language.
#
# Think of a library as a collection of functions that can be accessed to complete certain programming tasks without having to write your own algorithm.
#
# For this course, we will focus primarily on the following libraries:
#
# * **Numpy** is a library for working with arrays of data.
#
# * **Pandas** provides high-performance, easy-to-use data structures and data analysis tools.
#
# * **Scipy** is a library of techniques for numerical and scientific computing.
#
# * **Matplotlib** is a library for making graphs.
#
# * **Seaborn** is a higher-level interface to Matplotlib that can be used to simplify many graphing tasks.
#
# * **Statsmodels** is a library that implements many statistical techniques.
# ### Utilizing Library Functions
#
# After importing a library, its functions can then be called from your code by prepending the library name to the function name. For example, to use the '`dot`' function from the '`numpy`' library, you would enter '`numpy.dot`'. To avoid repeatedly having to type the libary name in your scripts, it is conventional to define a two or three letter abbreviation for each library, e.g. '`numpy`' is usually abbreviated as '`np`'. This allows us to use '`np.dot`' instead of '`numpy.dot`'. Similarly, the Pandas library is typically abbreviated as '`pd`'.
# In[7]:
import numpy as np
# In[3]:
import pandas as pd
# In[8]:
# array saved in a variable
variable = np.array([0,1,2,3,4,5,6,7,8,9,10])
# In[9]:
np.mean(variable)
# We have used the mean() function within the numpy library to calculate the mean of the numpy 1-dimensional array.
# # Data Management
#
# Data management is a crucial component to statistical analysis and data science work. The following code will show how to import data via the pandas library, view your data, and transform your data.
#
# The main data structure that Pandas works with is called a **Data Frame**. This is a two-dimensional table of data in which the rows typically represent cases (e.g. Cartwheel Contest Participants), and the columns represent variables. Pandas also has a one-dimensional data structure called a **Series** that we will encounter when accesing a single column of a Data Frame.
#
# Pandas has a variety of functions named '`read_xxx`' for reading data in different formats. Right now we will focus on reading '`csv`' files, which stands for comma-separated values. However the other file formats include excel, json, and sql just to name a few.
# ### Importing Data
# In[13]:
# Store the url string that hosts our .csv file
url = "Cartwheeldata.csv"
# Read the .csv file and store it as a pandas Data Frame
df = pd.read_csv(url)
# Output object type
type(df)
# **The previous cell may raise an error if the file is not uploaded to the working directory or the directory is not mentioned inside the function**
# ### Viewing Data
# In[14]:
# We can view our Data Frame by calling the head() function
df.head()
# The head() function simply shows the first 5 rows of our Data Frame. If we wanted to show the entire Data Frame we would simply write the following:
# In[16]:
# Output entire Data Frame
df
# As it can be seen above, we have a 2-Dimensional object where each row is an independent observation of our cartwheel data.
#
# To gather more information regarding the data, we can view the column names and data types of each column with the following functions:
# In[17]:
df.columns
# Lets say we would like to splice our data frame and select only specific portions of our data. There are three different ways of doing so.
#
# 1. .loc()
# 2. .iloc()
# 3. .ix()
#
# We will cover the .loc() and .iloc() splicing functions.
#
# ### .loc()
# .loc() takes two single/list/range operator separated by ','. The first one indicates the row and the second one indicates columns.
# In[18]:
# Return all observations of CWDistance
df.loc[:,"CWDistance"]
# In[19]:
# Select all rows for multiple columns, ["CWDistance", "Height", "Wingspan"]
df.loc[:,["CWDistance", "Height", "Wingspan"]]
# In[20]:
# Select few rows(0-9) for multiple columns, ["CWDistance", "Height", "Wingspan"]
df.loc[:9, ["CWDistance", "Height", "Wingspan"]]
# In[21]:
# Select range of rows for all columns
df.loc[10:15]
# In[22]:
df.loc[10:15, ["CWDistance", "Height", "Wingspan"]]
# The .loc() function requires to arguments, the indices of the rows and the column names you wish to observe.
#
# In the above case **:** specifies all rows, and our column is **CWDistance**. df.loc[**:**,**"CWDistance"**]
# Now, let's say we only want to return the first 10 observations:
# In[23]:
df.loc[:9, "CWDistance"]
# ### .iloc()
# .iloc() is integer based slicing, whereas .loc() used labels/column names. Here are some examples:
# In[24]:
df.iloc[:4]
# In[25]:
df.iloc[1:5, 2:4]
# In[26]:
df.iloc[1:5, ["Gender", "GenderGroup"]]
# We can view the data types of our data frame columns with by calling .dtypes on our data frame:
# In[27]:
df.dtypes
# The output indicates we have integers, floats, and objects with our Data Frame.
#
# We may also want to observe the different unique values within a specific column, lets do this for Gender:
# In[28]:
# List unique values in the df['Gender'] column
df.Gender.unique()
# In[29]:
# Lets explore df["GenderGroup] as well
df.GenderGroup.unique()
# It seems that these fields may serve the same purpose, which is to specify male vs. female. Lets check this quickly by observing only these two columns:
# In[30]:
# Use .loc() to specify a list of mulitple column names
df.loc[:,["Gender", "GenderGroup"]]
# From eyeballing the output, it seems to check out. We can streamline this by utilizing the groupby() and size() functions.
# In[31]:
df.groupby(['Gender','GenderGroup']).size()
# This output indicates that we have two types of combinations.
#
# * Case 1: Gender = F & Gender Group = 1
# * Case 2: Gender = M & GenderGroup = 2.
#
# This validates our initial assumption that these two fields essentially portray the same information.
<file_sep>/README.md
# Course-Understanding-and-Visualizing-Data-with-Python-Week1-
This repo consists of jupyter notebooks and other files from week 1 of the course: Understanding and Visualizing Data with Python(Coursera)
|
c06b1eee9e61b3b99fe08e41c9185800d3fd9160
|
[
"Markdown",
"Python"
] | 2
|
Python
|
hasibahmad1995/Course-Understanding-and-Visualizing-Data-with-Python-Week1-
|
f48f84ac23b5758bb19993d615c2f339c52863e8
|
a43caba0f2b207d5abb256d2f46ed4e9c4279e5e
|
refs/heads/master
|
<file_sep>package com.zhiyou100.ServiceImpl;
import com.zhiyou100.Service.BaseService;
import com.zhiyou100.model.User;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月13日 上午9:31:21
* 类说明
*/
public class BaseServiceImpl<T> implements BaseService<T>{
public void save(T user) {
// TODO Auto-generated method stub
}
public void delete(T user) {
// TODO Auto-generated method stub
}
public void update(T user) {
// TODO Auto-generated method stub
}
public User get(T id) {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>package com.zhiyou100.ServiceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhiyou100.Dao.RoleDao;
import com.zhiyou100.Service.RoleService;
import com.zhiyou100.model.Role;
import com.zhiyou100.model.User;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月13日 上午9:36:16
* 类说明
*/
@Service
public class RoleServiceImpl implements RoleService{
@Autowired
private RoleDao roleDao;
public void save(Role role) {
roleDao.save(role);
}
public void delete(Role role) {
roleDao.delete(role);
}
public void update(Role role) {
roleDao.update(role);
}
public Role get(int id) {
Role role = roleDao.get(id);
return role;
}
public List<Role> list() {
List<Role> list = roleDao.list();
return list;
}
}
<file_sep>package com.zhiyou100.Service;
import com.zhiyou100.model.User;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月13日 上午9:29:38
* 类说明
*/
public interface BaseService<T> {
void save(T user);
void delete(T user);
void update(T user);
User get(T id);
}
<file_sep>package com.zhiyou100.Dao.Impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.zhiyou100.Dao.DepatmentDao;
import com.zhiyou100.model.Depatment;
import com.zhiyou100.model.Role;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月13日 下午2:12:41
* 类说明
*/
@Repository
public class DepatmentDaoImpl extends BaseDaoImpl<Depatment> implements DepatmentDao{
@Autowired
private SessionFactory sessionFactory;
public Depatment get(int id) {
System.out.println("进入DepatmentGET方法");
Session session = sessionFactory.openSession();
session.beginTransaction();
Depatment depatment = session.get(Depatment.class, id);
session.getTransaction().commit();
session.close();
return depatment;
}
public List<Depatment> list() {
System.out.println("进入Depatment方法");
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createQuery("from Depatment");
List<Depatment> list = query.list();
session.getTransaction().commit();
session.close();
return list;
}
}
<file_sep>package com.zhiyou100.ServiceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhiyou100.Dao.DepatmentDao;
import com.zhiyou100.Service.DepatmentService;
import com.zhiyou100.model.Depatment;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月13日 下午2:11:06
* 类说明
*/
@Service
public class DepatmentServicxeImpl implements DepatmentService{
@Autowired
private DepatmentDao depatmentDao;
public void save(Depatment d) {
depatmentDao.save(d);
}
public void delete(Depatment d) {
depatmentDao.delete(d);
}
public void update(Depatment d) {
depatmentDao.update(d);
}
public Depatment get(int id) {
Depatment depatment = depatmentDao.get(id);
return depatment;
}
public List<Depatment> list() {
List<Depatment> list = depatmentDao.list();
return list;
}
}
<file_sep>package com.zhiyou100.ServiceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhiyou100.Dao.NoticeDao;
import com.zhiyou100.Service.NoticeService;
import com.zhiyou100.model.Notice;
import com.zhiyou100.model.User;
import com.zhoyou100.util.PageShow;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月13日 下午3:36:05
* 类说明
*/
@Service
public class NoticeServiceImpl implements NoticeService{
@Autowired
private NoticeDao noticeDao;
public void save(Notice notice) {
noticeDao.save(notice);
}
public void delete(Notice notice) {
noticeDao.delete(notice);
}
public void update(Notice notice) {
noticeDao.update(notice);
}
public Notice get(int id) {
Notice notice = noticeDao.get(id);
return notice;
}
public List<Notice> list() {
List<Notice> list = noticeDao.list();
return list;
}
public List<User> likeSelectNotice(String keyword, String field) {
List<User> list = noticeDao.likeSelectNotice(keyword, field);
return list;
}
//分页
public PageShow queryForPage(int pageSize, int page) {
String hql = "select count(*) from Notice";
Long allRow = noticeDao.getAllRowCount(hql);// 总条数
long totalPage = PageShow.countTotalPage(pageSize, allRow);//总页数
final int offset = PageShow.countOffset(pageSize, page);//当前页开始记录
final int length = pageSize;//每页记录数
final int currentPage = PageShow.countCurrentPage(page);
List<User> list = noticeDao.queryForPage("from Notice",offset, length);//"一页"的记录
//把分页信息保存到Bean中
PageShow pageBean = new PageShow();
pageBean.setPageSize(pageSize);
pageBean.setCurrentPage(currentPage);
pageBean.setAllRow(allRow);
pageBean.setTotalPage(totalPage);
pageBean.setList(list);
pageBean.init();
return pageBean;
}
}
<file_sep>package com.zhiyou100.Dao;
import java.util.List;
import org.springframework.stereotype.Service;
import com.zhiyou100.model.Role;
import com.zhiyou100.model.User;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月7日 上午10:28:56
* 类说明
*/
public interface RoleDao extends BaseDao<Role>{
void save(Role user);
void delete(Role user);
void update(Role user);
Role get(int id);
List<Role> list();
}
<file_sep>package com.zhiyou100.Service;
import java.util.List;
import com.zhiyou100.model.Depatment;
import com.zhiyou100.model.Role;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月13日 下午2:08:48
* 类说明
*/
public interface DepatmentService {
void save(Depatment d);
void delete(Depatment d);
void update(Depatment d);
Depatment get(int id);
List<Depatment> list();
}
<file_sep>package com.zhiyou100.Action;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.zhiyou100.Service.NoticeService;
import com.zhiyou100.model.Notice;
import com.zhiyou100.model.User;
import com.zhoyou100.util.PageShow;
import lombok.Getter;
import lombok.Setter;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月13日 下午3:30:41
* 类说明
*/
@Controller("noticeAction")
public class NoticeAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String DateTime = null;
@Setter
@Getter
private Notice notice = new Notice();
@Setter
private int page;//第几页
@Setter
@Getter
private PageShow pageBean;//包含分布信息的bean
@Setter
private String keyword;
@Setter
private String field;
@Autowired
private NoticeService noticeService;
public String selectNotice() throws Exception {
System.out.println("进入selectNotice");
this.pageBean= noticeService.queryForPage(8, page);
return SUCCESS;
}
//模糊查询
public String likeSelectNotice() throws Exception {
System.out.println("进入 likeSelectNotice方法");
System.out.println(keyword);
System.out.println(field);
List<User> list = noticeService.likeSelectNotice(keyword, field);
ActionContext.getContext().put("notice", list);
return SUCCESS;
}
//跳转到添加部门页面
public String skipInsertNotice() throws Exception{
System.out.println("进入skipInsertNotice");
return SUCCESS;
}
//发布公告
public String insertNotice() throws Exception{
System.out.println("进入insertNotice");
HttpServletRequest request = ServletActionContext.getRequest();
String pub_time = request.getParameter("pub_time");
String expire_time = request.getParameter("expire_time");
System.out.println("string"+pub_time);
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
Date pub = format1.parse(pub_time);
Date expire = format1.parse(expire_time);
String subject = request.getParameter("subject");
Integer receive_id = Integer.valueOf(request.getParameter("receive_id"));
String text = request.getParameter("text");
notice.setPub_time(pub);
notice.setExpire_time(expire);
notice.setSubject(subject);
notice.setReceive_id(receive_id);
notice.setText(text);
notice.setCreate_time(new Date());
System.out.println(notice);
noticeService.save(notice);
return "text_redirect";
}
//跳转到更新公告
public String skipUpdateNotice()throws Exception {
System.out.println("进入 skipUpdateNotice方法");
HttpServletRequest request = ServletActionContext.getRequest();
Integer notice_id = Integer.valueOf(request.getParameter("notice_id"));
System.out.println(notice_id);
Notice notice2 = noticeService.get(notice_id);
System.out.println(notice2);
ActionContext.getContext().put("notice2", notice2);
return SUCCESS;
}
//更改公告
public String updateNotice() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
String pub_time = request.getParameter("pub_time");
String expire_time = request.getParameter("expire_time");
System.out.println("string"+pub_time);
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
Date pub = format1.parse(pub_time); //转换为util.date
Date expire = format1.parse(expire_time);
String subject = request.getParameter("subject");
Integer receive_id = Integer.valueOf(request.getParameter("receive_id"));
String text = request.getParameter("text");
Integer notice_id = Integer.valueOf(request.getParameter("notice_id"));
notice.setNotice_id(notice_id);
notice.setPub_time(pub);
notice.setExpire_time(expire);
notice.setSubject(subject);
notice.setReceive_id(receive_id);
notice.setText(text);
notice.setUpdate_time(new Date());
System.out.println(notice);
noticeService.update(notice);
return "text_redirect";
}
//删除公告
public String deleteNotice()throws Exception {
System.out.println("进入deleteNotice方法");
HttpServletRequest request = ServletActionContext.getRequest();
Integer notice_id = Integer.valueOf(request.getParameter("notice_id"));
notice.setNotice_id(notice_id);
System.out.println(notice);
noticeService.delete(notice);
return "text_redirect";
}
}
<file_sep>package com.zhiyou100.Dao.Impl;
import java.util.List;
import org.apache.commons.lang3.ObjectUtils.Null;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import com.zhiyou100.Dao.UserDao;
import com.zhiyou100.model.User;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月7日 上午10:29:32
* 类说明 Dao实现类
*/
@Repository
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao{
@Autowired
private SessionFactory sessionFactory;
public User getUserByuserName(User user) {
Session session = sessionFactory.openSession();
session.beginTransaction();
String sql =" from User U where U.username = :username and U.password = :<PASSWORD>";
Query query = session.createQuery(sql);
String username = user.getUsername();
String password = user.getPassword();
query.setString("username", username);
query.setString("password", password);
/*List<User> list = query.list();
for (User user2 : list) {
System.out.println(user2);
}*/
//uniqueResult 数据库中根据你的查询条件只会返回唯一结果,
//就可以用uniqueResult这个方法!否则就用list();其返回类型为Object
User user2 = (User) query.uniqueResult();
session.getTransaction().commit();
session.close();
return user2;
}
/*public void save(User user) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
public void delete(User user) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.delete(user);
session.getTransaction().commit();
session.close();
}
public void update(User user) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.update(user);
session.getTransaction().commit();
session.close();
}*/
public User get(int id) {
Session session = sessionFactory.openSession();
session.beginTransaction();
User user = session.get(User.class, id);
session.getTransaction().commit();
session.close();
return user;
}
public List<User> list() {
System.out.println("进入list方法");
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createQuery("from User");
query.setFirstResult(0);//从什么位置开始查找
query.setMaxResults(3);//每次查找显示多少条
String hql2= "SELECT count(U) from User U";
Query query2 = session.createQuery(hql2);
Long sum = (Long) query2.uniqueResult();
System.out.println("总条数为:"+sum);
session.getTransaction().commit();
List<User> list = query.list();
session.close();
return list;
}
public List<User> likeSelectUser(String keyword, String field) {
System.out.println("进入likeSelectUser方法");
Session session = sessionFactory.openSession();
session.beginTransaction();
if (field.equals("username")) {
Query query = session.createQuery("from User where username like :key");
query.setString("key", "%"+keyword+"%");
List<User> list = query.list();
System.out.println(list);
return list;
}else if (field.equals("dept")) {
Query query = session.createQuery("from User where dept like :key");
query.setString("key", "%"+keyword+"%");
List<User> list = query.list();
System.out.println(list);
return list;
}else if (field.equals("role")) {
Query query = session.createQuery("from User where role like :key");
query.setString("key", "%"+keyword+"%");
List<User> list = query.list();
System.out.println(list);
return list;
}else if (field.equals("mobile")) {
Query query = session.createQuery("from User where mobile like :key");
query.setString("key", "%"+keyword+"%");
List<User> list = query.list();
System.out.println(list);
return list;
}else if (field.equals("email")) {
Query query = session.createQuery("from User where email like :key");
query.setString("key", "%"+keyword+"%");
List<User> list = query.list();
System.out.println(list);
return list;
}else if (field.equals("update_time")) {
Query query = session.createQuery("from User where update_time like :key");
query.setString("key", "%"+keyword+"%");
List<User> list = query.list();
System.out.println(list);
return list;
}
return null;
}
public List queryForPage(String hql, int offset, int length) {
System.out.println("进入queryForPage方法");
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createQuery(hql);
query.setFirstResult(offset);//从什么位置开始查找
query.setMaxResults(length);//每次查找显示多少条
List<User> list = query.list();
session.getTransaction().commit();
session.close();
return list;
}
public Long getAllRowCount(String hql) {
System.out.println("进入getAllRowCount方法");
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query2 = session.createQuery(hql);
Long sum = (Long) query2.uniqueResult();
session.getTransaction().commit();
session.close();
return sum;
}
}
<file_sep>package com.zhiyou100.Dao;
import java.util.List;
import com.zhiyou100.model.Notice;
import com.zhiyou100.model.User;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月13日 上午9:34:43
* 类说明
*/
public interface NoticeDao extends BaseDao<Notice>{
void save(Notice role);
void delete(Notice role);
void update(Notice role);
Notice get(int id);
List<Notice> list();
List<User> likeSelectNotice(String keyword,String field);
public List queryForPage(final String hql,final int offset,final int length);
public Long getAllRowCount(String hql);
}
<file_sep>package com.zhiyou100.Action;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.zhiyou100.Service.RoleService;
import com.zhiyou100.model.Role;
import lombok.Getter;
import lombok.Setter;
/**
* @author 作者 E-mail:
* @version 创建时间:2018年12月13日 上午8:55:59
* 类说明
*/
@Controller("RoleAction")
public class RoleAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
@Setter
@Getter
private Role role = new Role();
@Setter
private String remark;
@Setter
private String role_name;
@Autowired
private RoleService roleService;
@Override
public String execute() throws Exception {
System.out.println("进入role");
return NONE;
}
//查询角色
public String selectRole() throws Exception{
System.out.println("进入selectRole");
List<Role> list = roleService.list();
System.out.println(list);
ActionContext.getContext().put("role", list);
return SUCCESS;
}
//跳转到添加角色界面
public String skipInsertRole() throws Exception{
System.out.println("进入skipInsertRole");
return SUCCESS;
}
//添加角色
public String insertRole() throws Exception{
System.out.println("进入insertRole");
role.setRole_name(role_name);
role.setRemark(remark);
role.setCreate_time(new Date());
roleService.save(role);
return "text_redirect";
}
//跳转到修改角色页面
public String skipUpdateRole()throws Exception {
System.out.println("进入 skipUpdateRole方法");
HttpServletRequest request = ServletActionContext.getRequest();
Integer role_id = Integer.valueOf(request.getParameter("role_id"));
System.out.println(role_id);
Role role2 = roleService.get(role_id);
System.out.println(role2);
ActionContext.getContext().put("role2", role2);
return SUCCESS;
}
//修改角色
public String updateRole() throws Exception{
System.out.println("进入updateRole");
role.setRole_name(role_name);
role.setRemark(remark);
role.setUpdate_time(new Date());
roleService.update(role);
return "text_redirect";
}
//删除角色
public String deleteRole()throws Exception {
System.out.println("进入deleteRole方法");
HttpServletRequest request = ServletActionContext.getRequest();
Integer role_id = Integer.valueOf(request.getParameter("role_id"));
role.setRole_id(role_id);
roleService.delete(role);
return "text_redirect";
}
}
|
100e29f2a19f3edc719ab8d134268a6850d9aa6b
|
[
"Java"
] | 12
|
Java
|
chrnyuan/crm
|
aa3dc2949617fbf07390b18508cf8b46397fe43b
|
f6fe93b8251761672703050bcd804d5a0ac28d0b
|
refs/heads/master
|
<file_sep>CREATE DATABASE `phone_book` DEFAULT CHARACTER SET utf8 ;<file_sep>package com.mizrobov.phonebook.service;
import com.mizrobov.phonebook.entity.Person;
import com.mizrobov.phonebook.entity.Phone;
import java.util.List;
public interface ContactService {
public List<Person> getContacts();
public Person findOne(Long id);
public Person save(Person person);
public Person update(Person person);
public void delete(Long id);
public List<Phone> getContactPhones(Long contactId);
public Phone getPone(Long personId,Long phoneId);
public Phone savePhone(Phone phone);
public Phone updatePhone(Long personId,Phone person);
public void deletePhone(Long personId,Long id);
public List<Person> searchFullText(String query);
}
<file_sep>= Phone Book Spring REST Docs
This is an example output for a service running at http://localhost:8080:
== Get all contacts
.request
include::{snippets}/testGetContacts/http-request.adoc[]
.response
include::{snippets}/testGetContacts/http-response.adoc[]
== Get contact by identify
.request
include::{snippets}/testGetContact/http-request.adoc[]
.response
include::{snippets}/testGetContact/http-response.adoc[]
== Create new Contact
.request
include::{snippets}/testSaveContact/http-request.adoc[]
.response
include::{snippets}/testSaveContact/http-response.adoc[]
== Update contact
.request
include::{snippets}/testUpdateContact/http-request.adoc[]
.response
include::{snippets}/testUpdateContact/http-response.adoc[]
== Delete contact
.request
include::{snippets}/testDeleteContact/http-request.adoc[]
.response
include::{snippets}/testDeleteContact/http-response.adoc[]
== Search by name or number phone
.request
include::{snippets}/testSearchContact/http-request.adoc[]
.response
include::{snippets}/testSearchContact/http-response.adoc[]
<file_sep>package com.mizrobov.phonebook.dao;
import com.mizrobov.phonebook.entity.Person;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface PersonRepository extends CrudRepository<Person,Long> {
@Query(nativeQuery = true, value = "select distinct * from persons p left join phones pn on (p.id=pn.person_id) where concat(p.first_name,' ',p.last_name) like %?1% or pn.number like %?1%")
public List<Person> searchFullText(String keyWord);
}
<file_sep># phone-book
Сделано REST API для данной приложении
1) Создано миграции с помощью Liquibase
2) REST API написано на Spring
3) Сделано интеграционные тесты
4) Создано документация для REST API с использованием REST DOC
Перед запуска проекта создайте схему phone_book.
Поcле clone repository запускайте mvn clean package и в target в папке genarated-docs генерируется документация.
В папке проекта есть Collections для POSTMAN, для проверки.
<file_sep>package com.mizrobov.phonebook.dao;
import com.mizrobov.phonebook.entity.Person;
import com.mizrobov.phonebook.entity.Phone;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface PhoneRepository extends CrudRepository<Phone,Long> {
public List<Phone> getAllByPersonId(Long personeId);
public Phone findByIdAndPersonId(Long id, Long personId);
public void deletePhoneByIdAndPersonId(Long phoneId, Long personId);
}
<file_sep>package com.mizrobov.phonebook.entity;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity(name = "Person")
@Table(name = "persons")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name")
private String fistName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
@Column(name = "job_title")
private String jobTitle;
@Column(name = "company")
private String compamy;
@JsonManagedReference
@OneToMany (mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Phone> phones = new ArrayList<>();
public Person() {
}
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public Person(String fistName, String lastName, String email, String jobTitle, String compamy) {
this.fistName = fistName;
this.lastName = lastName;
this.email = email;
this.jobTitle = jobTitle;
this.compamy = compamy;
}
public Person(Long id, String fistName, String lastName, String email, String jobTitle, String compamy) {
this.id = id;
this.fistName = fistName;
this.lastName = lastName;
this.email = email;
this.jobTitle = jobTitle;
this.compamy = compamy;
}
public void addPhone(Phone phone) {
phones.add( phone );
phone.setPerson( this );
}
public void removePhone(Phone phone) {
phones.remove( phone );
phone.setPerson( null );
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFistName() {
return fistName;
}
public void setFistName(String fistName) {
this.fistName = fistName;
}
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 List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()){
return false;
}
Person person = (Person) o;
return Objects.equals(id, person.id) &&
Objects.equals(fistName, person.fistName) &&
Objects.equals(lastName, person.lastName) &&
Objects.equals(email, person.email);
}
@Override
public int hashCode() {
return Objects.hash(id, fistName, lastName, email);
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getCompamy() {
return compamy;
}
public void setCompamy(String compamy) {
this.compamy = compamy;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", fistName='" + fistName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", jobTitle='" + jobTitle + '\'' +
", compamy='" + compamy + '\'' +
'}';
}
}
|
a5bf588b3f4a0e15bc2d06f265c4f968051f19ac
|
[
"Java",
"SQL",
"Markdown",
"AsciiDoc"
] | 7
|
SQL
|
dilshodmizrobov/phone-book
|
031c630897800adc3927f41b089304f356e2607c
|
62f1d0009b70fed0b0d0eddf2f326a169ab15fc6
|
refs/heads/master
|
<repo_name>KaroliShp/coursework-tester<file_sep>/README.md
# Coursework tester for MIPS and C
Basic shell script for executing MIPS and C code and comparing their outputs. So you can compare your results which should be the same.
## Setup
1. Place it in the same folder as your other files, Mars and ```input_all.txt```
2. Compile your C code and keep the names of .s and executables of C code the same
4. In ```input_all.txt``` put every test case into a new line. Script will write these test cases line by line to ```input.txt```, running your code each time.
## Usage
Run the following commands in your terminal (might be different for Windows):
```
chmod u+x cw_tester.sh
./cw_tester.sh 0 tokenizer Mars4_5.jar
```
• The first argument is either 0 (false) or 1 (true) and it displays the output of each individual code if true. Last new line characters of the output may not be read for some reason (possible fix in the future)
• Second argument is the name of your task (name is the same for executable and .s files)
• Third argument is the name of your Mars file
<file_sep>/cw_tester.sh
#!/bin/sh
# 0 - false, > 1 - true
OUTPUT_INDIVIDUAL_RESULTS="$1"
# Name of the task
TASK_NAME="$2"
# Mars name
MARS_NAME="$3"
# Counter for inputs
COUNTER=0
# Color codes for output
RED='\033[0;31m' # Error
NC='\033[0m' # No color
LIGHT_GREEN='\033[1;32m' # Success
PURPLE='\033[0;35m' # MIPS
LIGHT_GRAY='\033[0;37m' # C
WHITE='\033[1;37m' # Script output
printf "\n${WHITE}${TASK_NAME} tester started${NC}\n"
while IFS="" read -r p || [ -n "$p" ]
do
# Print the test line to the console
printf "\n${WHITE}Test input ${COUNTER}:${NC} ${p}\n"
# Write the line to input.txt file
echo "$p" > "input.txt"
# Execute both commands
COMMAND1="$(java -jar ${MARS_NAME} nc me sm ${TASK_NAME}.s 2>/dev/null)"
COMMAND2="$(./${TASK_NAME})"
if [ "${COMMAND1}" = "${COMMAND2}" ]; then
printf "${LIGHT_GREEN}SUCCESS: MIPS equal to C${NC}"
else
printf "${RED}ERROR: MIPS not equal to C${NC}"
fi
# If invididual output is required
if [ "$OUTPUT_INDIVIDUAL_RESULTS" -ge 1 ];
then
# Execute mips code
printf "\n\n${PURPLE}MIPS output start${NC}\n"
echo "${COMMAND1}"
printf "${PURPLE}MIPS output end${NC}\n\n"
# Execute C code
printf "${LIGHT_GRAY}C output start${NC}\n"
echo "${COMMAND2}"
printf "${LIGHT_GRAY}C output end${NC}\n"
fi
# Increase counter by one
COUNTER=$(( COUNTER + 1))
done < input_all.txt
printf "\n\n${WHITE}${TASK_NAME} tester ended${NC}\n\n"
|
79f6fbd533a12e6c422d36a0c7a62e9ac8a4bf26
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
KaroliShp/coursework-tester
|
46ebb5fe3d574367cb6898e66afdc215a4888122
|
45fcc151a24175cf6eec3b43c3d1de845d56980b
|
refs/heads/master
|
<file_sep>=====================
Tournament Results
=====================
Tournament Results is a simple Python app that uses PostgreSQL database to store player and matches data.
It also includes functionality to rank the players acording to their standings and pair them up in matches in a tournament.
Quick start
-----------
1. Database and table definitions are stored in the tournament.sql file.
2. The following Python functions are stored in tournament.py file:
registerPlayer(name) - adds a player to the tournament by putting an entry in the database,
countPlayers() - returns the number of currently registered players,
deletePlayers() - clears out all the player records from the database,
reportMatch(winner, loser) - stores the outcome of a single match between two players in the database,
deleteMatches() - clears out all the match records from the database,
playerStandings() - returns a list of (id, name, wins, matches) for each player, sorted by the number of wins each player has,
swissPairings() - given the existing set of registered players and the matches they have played, generates and returns a list of pairings according to the Swiss system. Each pairing is a tuple (id1, name1, id2, name2), giving the ID and name of the paired players.
3. In order to run the Tournament Results application follow the below steps:
start vagrant vitrual machine by using 'vagrant up' command
start vagrant shell using 'vagrant ssh' command
connect to the PostgreSQL database using psql this will connect you to the default vagrant db
import tournament.sql file using \i tournament.sql file - this will create your tournament database, connect to the tournament db and create required tables
exit the database using \q command
to connect back to the tournament db from command line use 'psql tournament' command
from the ssh command line execute the test suite included in the tournament_test.py file - this can be accomplished by using 'python tournament_test.py'command.
4. Expected output:
1. Old matches can be deleted.
2. Player records can be deleted.
3. After deleting, countPlayers() returns zero.
4. After registering a player, countPlayers() returns 1.
5. Players can be registered and deleted.
6. Newly registered players appear in the standings with no matches.
7. After a match, players have updated standings.
8. After one match, players with one win are paired.
Success! All tests pass!
<file_sep>-- Table definitions for the tournament project.
--
-- Put your SQL 'create table' statements in this file; also 'create view'
-- statements if you choose to use it.
--
-- You can write comments in this file by starting them with two dashes, like
-- these lines here.
--First create database tournament to hold Players and Matches table.
create database tournament;
\c tournament
--Create table players to hold Player data including id and name. Primary key is player_id.
create table Players (
player_id serial primary key,
player_name text NOT NULL);
--Create table matches to hold Match data including players' ids and the winner's player_id.
--Primay key is match_id. For data integrity this table references players table on player ids.
create table Matches (
match_id serial primary key,
winner_id INTEGER REFERENCES Players,
loser_id INTEGER REFERENCES Players);
|
cd756c9c6792f876fc228ad17273b6a8171a15e9
|
[
"SQL",
"Text"
] | 2
|
Text
|
ms5626/Tournament-Results
|
6a0f68c652f3f1d3af94995ac83338a3308bf331
|
d407747c59b27e1b203cf3f22a42a8d60ac883ee
|
refs/heads/master
|
<repo_name>jiaojiao085/myapp<file_sep>/app.js
var express = require('express');
var app = express();
var routes=require('./lib/routes/auto-router')(app);
//app.use(express.static(__dirname + '/public'));
app.use('/static', express.static('public'));
/*app.get('/', function (req, res) {
res.send('i am serious this time!');
});*/
app.listen(8066);<file_sep>/fis-conf.js
var fs = require('fs');
var path = require('path');
var del = require('del');
// 这里修改了fis3-command-release,除掉了validate验证
var argv = require('minimist')(process.argv.slice(2));
var exec = require('child_process').exec;
// 这里是模拟生产上的环境
var qarelease = (argv.testing && argv.testingmakdir) ? '/m' : '';
console.log(qarelease)
console.log("i am serious this time");
console.log(process.env);
// 根据每个项目文件中的config.json自动替换请求路径
var repleceRequestUrl = function(file) {
var realpath = file.realpath;
var pathObj = fis.util.ext(realpath);
var contentStr = file.getContent();
if(realpath.indexOf('views') != -1 && pathObj.ext == '.js' || pathObj.ext == '.html') {
var dirname = pathObj.dirname;
var configPath = path.join(dirname, 'config.json');
if(fis.util.isFile(configPath)) {
var configObj = fis.util.readJSON(configPath);
var config = {};
var replaceRegExp = new RegExp("[\\\"\\\']+(\\{([A-Z]+)\\})[\\\"\\\']+", 'ig');
var replaceArr = [];
var replaceName = '';
if(argv.production) {
config = configObj.production;
} else if(argv.testing) {
config = configObj.testing;
} else {
config = configObj.development;
}
while(replaceArr = replaceRegExp.exec(contentStr)){
var replaceArrLth = replaceArr.length ? replaceArr.length : 0;
if(replaceArrLth) {
var replacePlace = replaceArr[1];
var replaceName = replaceArr[2];
contentStr = contentStr.replace(replacePlace, config[replaceName]);
file.setContent(contentStr);
}
}
}
}
};
// FIS3 会读取全部项目目录下的资源,如果有些资源不想被构建,通过以下方式排除。
fis.set('project.ignore', [
'fis-conf.js',
'output/**',
'node_modules/**',
'.git/**',
'.bowerrc',
'.idea',
'bower.json',
'.gitignore',
'.editorconfig',
'package.json',
'*.tar',
'views/**/README.md',
'bin/**',
'views/**/config.json',
'/statics/js/public/jweixin.js',
'/views/appdown/tg/**',
//'/views/original-prepay/**',
//'/views/original-changecard/{test.html}',
//'/views/original-changecard/{fill-change-card.html,fill-change-card.js,change-card.html,change-card.js}',
//'/views/original-changecard/{change-card-success.hbs,change-card.hbs,change-card.html,change-card.js,change-card.less,change-success.html,change-success.less,common.js,common.less,entrance.html,entrance.less,fill-change-card.html,fill-change-card.js,login.html,login.less,ntneed-change.html,ntneed-change.less,test.html}',
//'/views/original-bkcredit/**',
// '/views/tenderdown/**',
//'views/original-jointventure/**',
// 'views/original-protocols/**',
// 'views/original-protocols/pbc/**',
'README.md'
// 'views/original-direct/**',
// 'views/original-direct/direct.html'
]);
fis.set('project.fileType.text', 'hbs');
fis.set('roadmap.ext.hbs', 'js');
// 这个编译插件只是对编译工具做一下扩展,支持前端模块化框架中的组件与组件之间依赖的函数,以及入口函数来标记生成到静态资源映射表中;另外一个功能是针对某些前端模块化框架的特性自动添加 define。
fis.hook('commonjs');
// 第三方插件处理
var plugins = {
'jquery': [
'/bower_components/jquery/dist/(jquery.js)',
'/bower_components/jquery-qrcode/(jquery.qrcode.min.js)',
'/bower_components/jquery.cookie/(jquery.cookie.js)',
],
'fastclick': [
'/bower_components/fastclick/lib/(fastclick.js)'
],
'slip': [
'/bower_components/binnng/slip.js/src/(slip.js)'
],
'detect': [
'/bower_components/mobile-detect/(mobile-detect.js)',
'/bower_components/Detect.js/(detect.js)'
],
'fullpage': [
'/bower_components/fullpage.js/(jquery.fullPage.js)',
'/bower_components/fullpage.js/(jquery.fullPage.css)'
],
'handlebars': [
'/bower_components/handlebars/(handlebars.runtime.js)'
],
'hbshelps': [
'/bower_components/handlebars-helpers/src/(helpers.js)'
]
};
fis.match('/bower_components/**/*', {
release: false
});
for(var i in plugins) {
var srcs = plugins[i];
for(var k = 0, lth = srcs.length; k < lth; k++) {
var pluginsPath = '/statics/tem/js/bower_components/' + i + '/$1'
if(/\.css\)$/i.test(srcs[k])) {
pluginsPath = '/statics/tem/css/bower_components/' + i + '/$1'
}
fis.match(srcs[k], {
release: pluginsPath
});
}
}
fis
.match('**/*.hbs', {
// 编译hbs文件http://handlebarsjs.com/
// 修改解析插件content = content.replace(/\"/gi,"'").replace(/\\'/gi, '"');js里面html加\"或是'都会自动转为"
rExt: '.js', // from .handlebars to .js 虽然源文件不需要编译,但是还是要转换为 .js 后缀
parser: fis.plugin('handlebars-4.x', {
//fis-parser-handlebars-4.x option
}),
release: false
})
.match('/statics/js/plugins/**', {
// 组件化js
isMod: false
})
.match('statics/js/public/(**)', {
isMod: true,
release: '/statics/tem/js/public/$1'
})
.match('statics/js/widget/(**)', {
isMod: true,
})
.match('/statics/js/public/{jweixin,validator,form-submit,notification}.js', {
isMod: false
})
.match('/**/_*/*.less', {
// 编译所有后缀为 less 的文件为 css
release: false
})
.match(/\/statics\/css\/((?!_cssprivate).*?$)/i, {
rExt: '.css', // from .less to .css
parser: fis.plugin('less-2.x'),
release: '/statics/css/$1'
})
.match(/^\/statics\/css\/(.+\.png)$/i, {
// 图片合并时重定向发布路径
// 有用到媒体查询的不要使用图片压缩
release: '/statics/images/$1'
})
.match('/views/(**/*.less)', {
rExt: '.css', // from .less to .css
parser: fis.plugin('less-2.x'),
release: '/statics/css/$1'
})
.match('/views/original-(**)/(*.less)', {
release: '/statics/css/$1/$2'
})
.match(/^\/views\/(.+\.(?:jpg|png|webp))$/i, {
// 图片合并时重定向发布路径
// 有用到媒体查询的不要使用图片压缩
release: '/statics/images/$1'
})
.match(/^\/views\/original-(.*)\/(.+\.(?:jpg|png|webp))$/i, {
release: '/statics/images/$1/$2'
})
.match(/^\/views\/(.*)\/images\/((?!_csssprites).*)/i, {
// 重定向views里的图片路径
release: '/statics/images/$1/$2'
})
.match(/^\/views\/original-(.*)\/(.*\/)?images\/((?!_csssprites).*)/i, {
release: '/statics/images/$1/$2$3'
})
.match(/^\/views\/(.*)\/images\/_csssprites\/(.+\.(?:jpg|png|webp))$/i, {
// 雪碧图临时文件
release: '/statics/tem/images/$1/$2'
})
.match(/^\/views\/original-(.*)\/images\/_csssprites\/(.+\.(?:jpg|png|webp))$/i, {
release: '/statics/tem/images/$1/$2'
})
.match('/views/(**/*.js)', {
// 重定向views里的js路径
release: '/statics/tem/js/$1',
isMod: true
})
.match(/^\/views\/original-(.*)\/(.+\.js)$/i, {
release: '/statics/tem/js/$1/$2',
isMod: true
})
.match(/^\/views\/.*\/(.+\.html)$/i, {
// html发布路径
release: '/$1'
})
.match(/^\/views\/original-(.*)\/(.+\.html)$/i, {
// html发布路径根据文件夹内容带有多级目录
release: '/$1/$2'
})
.match('/views/appdown/**.js', {
// 为了隐藏真实地址所以不用define
isMod: false
})
.match('/views/_public/*.*', {
// 不用release
release: false,
loaderLang: false
})
.match('/views/**/_public/*.*', {
release: false,
loaderLang: false
})
.match('/views/**/*.json', {
// json数据不用发布
release: false
})
.match('::package', {// 启用打包插件,必须匹配 ::package
prepackager: function(ret, conf, settings, opt) {
var files = ret.src;
Object.keys(files).forEach(function(subpath) {
var file = files[subpath];
repleceRequestUrl(file);
});
},
// 分析 __RESOURCE_MAP__ 结构,来解决资源加载问题
// 其是一种基于构建工具的加载组件的方法,构建出的 html 已经包含了其使用到的组件以及依赖资源的引用。
postpackager: fis.plugin('loader', {
resourceType: 'mod',
allInOne: false,
obtainScript: true,
obtainStyle: true,
useInlineMap: true, // 资源映射表内嵌
include: [ //防止require.async加载找不到依赖
]
})
}).match('*', {
deploy: [
// 清空发布目录
function(options, modified, total, next) {
var i = modified.length;
if(i) {
while(i--) {
var filepath = modified[i].getHashRelease();
(function(i) {
del('./output/' + filepath).then(function(paths){
// console.log('Deleted files and folders: ', paths.join('\n'));
if(i == 0) {
next();
}
});
})(i);
}
} else {
next();
}
},
fis.plugin('local-deliver', {
to: process.cwd() + '/output'
})
]
});
/****************************************** 测试、生产发布 ****************************************************/
// 全局公用js打包
var publicPkgJs = [
'/statics/js/plugins/mod.js',
'/bower_components/fastclick/lib/fastclick.js',
'/bower_components/jquery/dist/jquery.js',
'/bower_components/mobile-detect/mobile-detect.js',
'/bower_components/Detect.js/detect.js',
'/statics/js/public/base.js',
'/statics/js/public/bdtrack.js'
];
for(var i = 0, lth = publicPkgJs.length; i < lth; i++) {
var js = publicPkgJs[i];
fis.media('qa').match(js, {
packTo: '/statics/js/pkg/public.js',
packOrder: i // 值越小越在前面
})
}
var musicReg = new RegExp('\\/views\\/(.*\\.(?:mp3|ogg)$)', 'i');
fis.media('qa')
.match('/statics/js/pkg/public.js', {
release: qarelease + '/statics/js/pkg/public.js',
url: '/m/statics/js/pkg/public.js'
})
.match('/statics/js/plugins/(**)', {
release: qarelease + '/statics/js/plugins/$1',
url: '/m/statics/js/plugins/$1'
})
.match(/\/statics\/css\/((?!_cssprivate).*?$)/i, {
release: qarelease + '/statics/css/$1',
url: '/m/statics/css/$1'
})
.match(/^\/statics\/css\/(.+\.png)$/i, {
release: qarelease + '/statics/images/$1',
url: '/m/statics/images/$1'
})
.match('/views/(**/*.less)', {
release: qarelease + '/statics/css/$1',
url: '/m/statics/css/$1'
})
.match('/views/original-(**)/(*.less)', {
release: qarelease + '/statics/css/$1/$2',
url: '/m/statics/css/$1/$2'
})
.match(/^\/views\/(.+\.(?:jpg|png|webp))$/i, {
release: qarelease + '/statics/images/$1',
url: '/m/statics/images/$1'
})
.match(/^\/views\/(.*)\/images\/((?!_csssprites).*)/i, {
release: qarelease + '/statics/images/$1/$2',
url: '/m/statics/images/$1/$2'
})
.match(/^\/views\/original-(.*)\/(.+\.(?:jpg|png|webp))$/i, {
release: qarelease + '/statics/images/$1/$2',
url: '/m/statics/images/$1/$2'
})
.match(/^\/views\/original-(.*)\/(.*\/)?images\/((?!_csssprites).*)/i, {
release: qarelease + '/statics/images/$1/$2/$3',
url: '/m/statics/images/$1/$2/$3'
})
.match(musicReg, {
release: qarelease + '/statics/musics/$1',
url: '/m/statics/musics/$1'
});
// 替换文件名配置
var appDownConfig = {
'ntg': {
name: '97ED234E4BBC8ED2',
apps: {
'ntg-ctcf': '87ED234E4BBC8ED2'
}
},
'tg': {
name: 'EHJFDF88SFOFISFU',
apps: {
'tg-bbs-51cred': '527D23B7C57B05FA',
'tg-bbs-u51': 'D6756A8394C3104F',
'tg-qq-hd': 'CE183970129A96C1',
'tg-qq-zf': '789BFD5A3764FAE0',
'tg-wx': 'E8D2A98EFC798602',
'tg_001': '79C95F8238683FF2',
'tg_002': '338496D10FBB57F9',
'tg_003': '158DDA725E4AA2AB',
'tg_004': 'D60D929F87808DF0',
'tg_005': '7DC5E2BEB03B960B'
}
}
};
// 替换html文件名
for(var i in appDownConfig) {
var apps = appDownConfig[i]['apps'];
var name = appDownConfig[i]['name'];
// 公用替换
var cssCommonReg = new RegExp('\\/views\\/appdown\\/' + i + '\\/[a-zA-Z0-9-]+\\.(?:less)$', 'i');
var jsCommonReg = new RegExp('\\/views\\/appdown\\/' + i + '\\/[a-zA-Z0-9-]+\\.(?:js)$', 'i');
var imageCommonReg = new RegExp('\\/views\\/appdown\\/' + i + '\\/images\\/((?!_csssprites).*)', 'i');
fis.media('qa')
.match(cssCommonReg, {
release: qarelease + '/statics/css/appdown/' + name + '.css',
url: '/m/statics/css/appdown/' + name + '.css'
})
.match(jsCommonReg, {
release: qarelease + '/statics/js/appdown/' + name + '.js',
url: '/m/statics/css/appdown/' + name + '.js',
isMod: false
})
.match(imageCommonReg, {
release: qarelease + '/statics/images/appdown/' + name + '/$1',
url: '/m/statics/images/appdown/' + name + '/$1'
});
// 单个替换
for(var k in apps) {
var reg = new RegExp('(' + k + ')' + '.html$', 'i');
var appName = apps[k];
var cssAppReg = new RegExp('\\/views\\/appdown\\/.*\\/' + k + '\\.(?:less)$', 'i');
var jsAppReg = new RegExp('\\/views\\/appdown\\/.*\\/' + k + '\\.(?:js)$', 'i');
var imageAppReg = new RegExp('\\/views\\/appdown\\/.*\\/' + k + '\\/images\\/((?!_csssprites).*)', 'i');
var musicAppReg = new RegExp('\\/views\\/appdown\\/.*\\/' + k + '\\/(.*\\.(?:mp3|ogg)$)', 'i');
fis.media('qa')
.match(reg, {
release: '/' + appName + '.html'
})
.match(cssAppReg, {
release: qarelease + '/statics/css/appdown/' + appName + '.css',
url: '/m/statics/css/appdown/' + appName + '.css'
})
.match(jsAppReg, {
release: qarelease + '/statics/js/appdown/' + appName + '.js',
url: '/m/statics/css/appdown/' + appName + '.js',
isMod: false
})
.match(imageAppReg, {
release: qarelease + '/statics/images/appdown/' + appName + '/$1',
url: '/m/statics/images/appdown/' + appName + '/$1'
})
.match(musicAppReg, {
release: qarelease + '/statics/musics/appdown/' + appName + '/$1',
url: '/m/statics/musics/appdown/' + appName + '/$1'
});
}
}
// 糖罐计划替换合并后的js/css文件名
for(var i in appDownConfig) {
var apps = appDownConfig[i]['apps'];
for(var k in apps) {
var appName = apps[k];
var reg = new RegExp('\\/pkg\\/views\\/(.*)\\/' + k + '\\.html_aio\\.((?:js|css))$', 'i');
fis.media('qa')
.match(reg, {
release: qarelease + '/statics/$2/appdown/pkg/' + appName + '.$2',
url: '/m/statics/$2/appdown/pkg/' + appName + '.$2'
});
}
}
// 发布到测试机
fis.media('qa')
.match('::package', {
prepackager: function(ret, conf, settings, opt) {
var files = ret.src;
Object.keys(files).forEach(function(subpath) {
var file = files[subpath];
repleceRequestUrl(file);
});
},
// 启用打包插件,必须匹配 ::package
// 分析 __RESOURCE_MAP__ 结构,来解决资源加载问题
// 其是一种基于构建工具的加载组件的方法,构建出的 html 已经包含了其使用到的组件以及依赖资源的引用。
// 参考https://github.com/fex-team/fis3-postpackager-loader
postpackager: [
fis.plugin('loader', {
resourceType: 'mod',
allInOne: {
ignore: [
'/statics/css/public/base.less'
]
},
obtainScript: true,
obtainStyle: true,
useInlineMap: false, // 资源映射表内嵌
include: [ //防止require.async加载找不到依赖
]
})
],
spriter: fis.plugin('csssprites')
})
.match(/\/pkg\/views\/(.*\/.+((?:js|css)))/i, {
release: qarelease + '/statics/$2/$1',
url: '/m/statics/$2/$1'
})
.match(new RegExp('\\/pkg\\/views\\/original-(.*)\\/(.+\\.html_aio\\.((?:js|css)))$', 'i'), {
release: qarelease + '/statics/$3/$1/$2',
url: '/m/statics/$3/$1/$2'
})
.match(/\/views\/(?!_public|.*\/images|.*\.(?:js|less|hbs|json)).*?$/i, {
optimizer: fis.plugin('html-minifier', {
removeComments: true,
ignoreCustomComments: [
/^RESOURCEMAP_PLACEHOLDER$/i,
/^SCRIPT_PLACEHOLDER$/i,
/^ignore$/i,
/^STYLE_PLACEHOLDER$/i
],
collapseWhitespace: true,
minifyCSS: true,
minifyJS: true
})
})
.match('*.js', {
optimizer: fis.plugin('uglify-js', {
mangle: {
expect: ['exports, module, require, define'] //export, module, require不压缩变量名
},
compress : {
drop_console: true //自动去除console.log等调试信息
}
})
})
.match('*.{less,css}', {
optimizer: fis.plugin('clean-css', {
'keepBreaks': false //保持一个规则一个换行
}),
useSprite: true // 对 CSS 进行图片合并,给匹配到的文件分配属性 `useSprite`
})
.match('*.png', {
// fis-optimizer-png-compressor 插件进行压缩,已内置
optimizer: fis.plugin('png-compressor')
})
.match('*.{js,less,css,png,jpg,gif,webp}', {
useHash: true
})
.match('tr.gif', {
useHash: false
})
.match('touch-icon-*.png',{
useHash: false
})
.match('/statics/images/public/bank-logos/*.png',{
useHash: false
})
.match('/statics/images/public/loading.gif',{
useHash: false
})
.match('*', {
deploy: [
function(options, modified, total, next) {
// 排除不需要发布的文件
var opts = {
exclude: [
'map.json',
'tem/**',
'direct/direct.html',
'appdown/' + appDownConfig['tg']['name'] + '_*.{css,js}',
'appdown/' + appDownConfig['tg']['apps']['tg_002'] + '_*.js',
'appdown/' + appDownConfig['ntg']['apps']['ntg-ctcf'] + '_*.js'
]
};
var modifiedLth = modified.length;
var i = modifiedLth;
while(i--) {
if (!fis.util.filter(modified[i].getHashRelease(), opts.include, opts.exclude)) {
modified.splice(i, 1);
}
}
// 除掉注释
total.forEach(function(data){
if(data.ext == '.js' || data.ext == '.css' || data.ext == '.less') {
var content = data.getContent().replace(/\/\*\![\s]*.*[\s]*\*\/[\n]*/ig, '');
data.setContent(content);
}
});
next();
},
function(options, modified, total, next) {
del('./output').then(function(paths){
next();
});
},
function(options, modified, total, next) {
// 为了使后台引用资源不变这里得多复制出一个没有版本号的文件
var copyOpts = {
include: [
'statics/css/public/**',
'statics/js/pkg/**',
'statics/css/direct/direct_*.css',
'statics/js/direct/direct*.js',
'statics/css/fansred/**',
'statics/js/fansred/**',
'statics/js/plugins/flexible_*.js',
'statics/css/changecard/login_*.css',
'statics/js/changecard/login*.js'
]
};
var k = modified.length;
while(k--) {
if (fis.util.filter(modified[k].getHashRelease(), copyOpts.include, copyOpts.exclude)) {
var copyRoot = fis.util(process.cwd() + '/output');
var copyFilePath = modified[k].getHashRelease().replace('_' + modified[k].getHash(), '');
var copyOutput = path.join(copyRoot + '', copyFilePath + '');
// console.log(copyOutput);
fis.util.write(copyOutput, modified[k].getContent());
}
}
next();
},
fis.plugin('local-deliver', {
to: process.cwd() + '/output'
})
]
});
<file_sep>/statics/js/plugins/music.js
/**
* 音符漂浮插件
*********************************************************************************************
* 这是别人写的东西,我只是重复利用,微调了下--努力努力 ^-^||
*
* -----------保持队形------------------
* <div id='coffee'></div>
*********************************************************************************************/
// 音符的漂浮的插件制作--zpeto扩展
;(function($, undefined){
var prefix = '',
eventPrefix,
endEventName,
endAnimationName,
vendors = { Webkit: 'webkit', Moz: '', O: 'o' },
document = window.document,
testEl = document.createElement('div'),
supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,
transform,
transitionProperty,
transitionDuration,
transitionTiming,
transitionDelay,
animationName,
animationDuration,
animationTiming,
animationDelay,
cssReset = {};
function dasherize(str) {
return str.replace(/([a-z])([A-Z])/, '$1-$2').toLowerCase();
}
function normalizeEvent(name) {
return eventPrefix ? eventPrefix + name : name.toLowerCase();
}
$.each(vendors, function(vendor, event){
if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
prefix = '-' + vendor.toLowerCase() + '-';
eventPrefix = event;
return false;
}
});
transform = prefix + 'transform';
cssReset[transitionProperty = prefix + 'transition-property'] =
cssReset[transitionDuration = prefix + 'transition-duration'] =
cssReset[transitionDelay = prefix + 'transition-delay'] =
cssReset[transitionTiming = prefix + 'transition-timing-function'] =
cssReset[animationName = prefix + 'animation-name'] =
cssReset[animationDuration = prefix + 'animation-duration'] =
cssReset[animationDelay = prefix + 'animation-delay'] =
cssReset[animationTiming = prefix + 'animation-timing-function'] = '';
$.newfx = {
off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined),
speeds: { _default: 400, fast: 200, slow: 600 },
cssPrefix: prefix,
transitionEnd: normalizeEvent('TransitionEnd'),
animationEnd: normalizeEvent('AnimationEnd')
};
$.fn.newanimate = function(properties, duration, ease, callback, delay){
if($.isFunction(duration)) {
callback = duration;
ease = undefined;
duration = undefined;
}
if($.isFunction(ease)) {
callback = ease,
ease = undefined;
}
if($.isPlainObject(duration)) {
ease = duration.easing;
callback = duration.complete;
delay = duration.delay;
duration = duration.duration;
}
if(duration) {
duration = (typeof duration == 'number' ? duration : ($.newfx.speeds[duration] || $.newfx.speeds._default)) / 1000;
}
if(delay) {
delay = parseFloat(delay) / 1000;
}
return this.anim(properties, duration, ease, callback, delay);
}
$.fn.anim = function(properties, duration, ease, callback, delay) {
var key,
cssValues = {},
cssProperties,
transforms = '',
that = this,
wrappedCallback,
endEvent = $.newfx.transitionEnd,
fired = false
if(duration === undefined) {
duration = $.newfx.speeds._default / 1000;
}
if(delay === undefined) {
delay = 0;
}
if($.newfx.off) {
duration = 0;
}
if(typeof properties == 'string') {
// keyframe animation
cssValues[animationName] = properties;
cssValues[animationDuration] = duration + 's';
cssValues[animationDelay] = delay + 's';
cssValues[animationTiming] = (ease || 'linear');
endEvent = $.newfx.animationEnd;
} else {
cssProperties = [];
// CSS transitions
for (key in properties) {
if(supportedTransforms.test(key)) {
transforms += key + '(' + properties[key] + ') ';
} else {
cssValues[key] = properties[key];
cssProperties.push(dasherize(key));
}
}
if(transforms) {
cssValues[transform] = transforms;
cssProperties.push(transform);
}
if(duration > 0 && typeof properties === 'object') {
cssValues[transitionProperty] = cssProperties.join(', ');
cssValues[transitionDuration] = duration + 's';
cssValues[transitionDelay] = delay + 's';
cssValues[transitionTiming] = (ease || 'linear');
}
}
wrappedCallback = function(event) {
if(typeof event !== 'undefined') {
if (event.target !== event.currentTarget) {
return; // makes sure the event didn't bubble from "below"
}
$(event.target).unbind(endEvent, wrappedCallback);
} else {
$(this).unbind(endEvent, wrappedCallback); // triggered by setTimeout
}
fired = true;
$(this).css(cssReset);
callback && callback.call(this);
}
if(duration > 0) {
this.bind(endEvent, wrappedCallback);
// transitionEnd is not always firing on older Android phones
// so make sure it gets fired
setTimeout(function() {
if (fired) {
return;
}
wrappedCallback.call(that);
}, (duration * 1000) + 25);
}
// trigger page reflow so new elements can animate
this.size() && this.get(0).clientLeft
this.css(cssValues)
if (duration <= 0) {
setTimeout(function() {
that.each(function(){
wrappedCallback.call(this);
});
}, 0)
}
return this;
}
testEl = null;
})(window.$);
;(function($){
// 利用zpeto的animate的动画-css3的动画-easing为了css3的easing(zpeto没有提供easing的扩展)
$.fn.coffee = function(option){
var FONTSIZE = 124.2;
// 动画定时器
var __time_val=null;
var __time_wind=null;
var __flyFastSlow = 'cubic-bezier(.09,.64,.16,.94)';
// 初始化函数体,生成对应的DOM节点
var $coffee = $(this);
var opts = $.extend({}, $.fn.coffee.defaults, option); // 继承传入的值
opts.steamWidth = opts.steamWidth / FONTSIZE;
opts.steamHeight = opts.steamHeight / FONTSIZE;
opts.steamMaxSize = opts.steamMaxSize / FONTSIZE;
// 漂浮的DOM
var coffeeSteamBoxWidth = opts.steamWidth;
var $coffeeSteamBox = $('<div class="coffee-steam-box"></div>').css({
'height' : opts.steamHeight + 'rem',
'width' : opts.steamWidth + 'rem',
'left' : 0 + 'rem',
'top' : (-opts.steamHeight / 2 - opts.steamHeight / 4) + 'rem',
'position' : 'absolute',
'overflow' : 'hidden',
'z-index' : 0
}).appendTo($coffee);
// 动画停止函数处理
$.fn.coffee.stop = function(){
clearInterval(__time_val);
clearInterval(__time_wind);
};
// 动画开始函数处理
$.fn.coffee.start = function(){
__time_val = setInterval(function() {
steam();
}, rand( opts.steamInterval / 2 , opts.steamInterval * 2 ));
__time_wind = setInterval(function() {
wind();
}, rand(100 , 1000 )+ rand(1000 , 3000));
};
return $coffee;
// 生成漂浮物
function steam() {
// 设置飞行体的样式
if($coffeeSteamBox.find('.coffee-steam').length > 10) {
return;
}
var fontSize = rand(8, opts.steamMaxSize * FONTSIZE); // 字体大小
var steamsFontFamily = randoms(1, opts.steamsFontFamily); // 字体类型
// var color = '#' + randoms(6 , '0123456789ABCDEF' ); // 字体颜色
var color = '#fff'; // 字体颜色
var position = rand(0, 20); // 起初位置
var rotate = rand(-90, 89); // 旋转角度
var scale = rand02(0.4, 1); // 大小缩放
var transform = $.newfx.cssPrefix + 'transform'; // 设置音符的旋转角度和大小
transform = transform + ':rotate(' + rotate + 'deg) scale(' + scale + ');'
// 生成fly飞行体
var $fly = $('<span class="coffee-steam">' + randoms(1, opts.steams) + '</span>');
var left = rand(0, -fontSize);
if(left > position) {
left = rand(0, position);
}
$fly
.css({
'position' : 'absolute',
'left' : position / FONTSIZE + 'rem',
'top' : opts.steamHeight + 'rem',
'font-size' : fontSize / FONTSIZE + 'rem',
'color' : color,
'font-family' : steamsFontFamily,
'display' : 'block',
'opacity' : 1
})
.attr('style', $fly.attr('style') + transform)
.appendTo($coffeeSteamBox)
.newanimate({
top : rand((opts.steamHeight * FONTSIZE) / 2, 0) / FONTSIZE,
left : left / FONTSIZE,
opacity : 0
}, rand(opts.steamFlyTime / 2 , opts.steamFlyTime * 1.2 ), __flyFastSlow, function() {
$fly.remove();
$fly = null;
});
};
// 风行,可以让漂浮体,左右浮动
function wind() {
// 左右浮动的范围值
var left = rand(-10, 10) / FONTSIZE;
var maxLeft = 40 / FONTSIZE;
var minLeft = 30 / FONTSIZE;
if($coffeeSteamBox.find('.coffee-steam').length > 10) {
return;
}
left += lib.flexible.px2rem(parseInt($coffeeSteamBox.css('left')));
if(left >= maxLeft) {
left = maxLeft;
} else if(left <= minLeft) {
left = minLeft;
}
// 移动的函数
$coffeeSteamBox.newanimate({
left: left + 'rem'
} , rand(1000, 3000), __flyFastSlow);
};
// 随即一个值
// 可以传入一个数组和一个字符串
// 传入数组的话,随即获取一个数组的元素
// 传入字符串的话,随即获取其中的length的字符
function randoms( length , chars ) {
length = length || 1 ;
var hash = ''; //
var maxNum = chars.length - 1; // last-one
var num = 0; // fisrt-one
for( i = 0; i < length; i++ ) {
num = rand(0 , maxNum - 1 );
hash += chars.slice(num , num + 1 );
}
return hash;
};
// 随即一个数值的范围中的值--整数
function rand(mi, ma){
var range = ma - mi;
var out = mi + Math.round( Math.random() * range) ;
return parseInt(out);
};
// 随即一个数值的范围中的值--浮点
function rand02(mi, ma){
var range = ma - mi;
var out = mi + Math.random() * range;
return parseFloat(out);
};
};
$.fn.coffee.defaults = {
steams: ['♪', '♪', '♪', '♪'], /*漂浮物的类型,种类*/
steamsFontFamily: ['Verdana','Geneva','Comic Sans MS','MS Serif','Lucida Sans Unicode','Times New Roman','Trebuchet MS','Arial','Courier New','Georgia'], /*漂浮物的字体类型*/
steamFlyTime: 5000 , /*Steam飞行的时间,单位 ms 。(决定steam飞行速度的快慢)*/
steamInterval: 500 , /*制造Steam时间间隔,单位 ms.*/
steamMaxSize: 70, /*随即获取漂浮物的字体大小*/
steamHeight: 200, /*飞行体的高度*/
steamWidth: 100 /*飞行体的宽度*/
};
$.fn.coffee.version = '2.0.0'; // 更新为音符的悬浮---重构的代码
})(window.$);
<file_sep>/statics/js/public/bdtrack.js
/*
百度统计行为跟踪
*/
(function($) {
_hmt = _hmt || [];
var track = function(lbs, type) {
var _lbs = lbs.slice(0);
_lbs[1] += '-' + type;
_lbs.unshift('_trackEvent');
_hmt.push(_lbs);
},
factory = function(type, lbs) {
if(!eventType[type]) {
this.bind(type + '.gaevent', function() {
track(lbs, type);
});
} else if(type != 'factory') {
eventType[type].call(this, lbs, track);
}
},
eventType = {
click: function(lbs) {
var lbs2 = lbs[2];
this.bind('click.gaevent', function() {
var href = this.href;
if(this.tagName.toLowerCase() == 'a' && href && !/^#|javascript:/i.test(href)) {
lbs[2] = lbs2 + ':' + href;
}
track(lbs, 'click');
});
},
change: function(lbs) {
var lbs2 = lbs[2];
this.bind('change.gaevent', function() {
var v = $(this).val();
if(v && v != '-1') {
lbs[2] = lbs2 + ':' + $(this).val();
track(lbs, 'change');
}
});
}
},
setLabelSetting = function(lbs) {
lbs[0] = lbs[0] || '';
lbs[1] = lbs[1] || '';
lbs[2] = lbs[2] || '';
if(lbs[3] != undefined) {
lbs[3] = parseInt(lbs[3]);
}
if(lbs[4] != undefined) {
if(lbs[4] == 'true' || lbs[4] == '1') {
lbs[4] = true;
} else {
lbs[4] = false;
}
}
return lbs.slice(0);
};
$.fn.gaevent = function(autoTrigger) {
return this.each(function() {
var $t = $(this),
ga = $t.attr('data-gaevent'),
gas = ga ? ga.split('|') : [],
evs = gas[0] && gas[0].indexOf(',') === -1 ? [gas[0]] : gas[0].split(','),
lbs = gas[1] ? gas[1].split('/') : [],
i;
for(i in evs) {
factory.call($t, evs[i], setLabelSetting(lbs));
}
if(!!autoTrigger) {
$t.triggerHandler('.gaevent');
}
});
};
$.gaeventType = $.extend(eventType, $.gaeventType);
$('[data-gaevent]').gaevent();
})(jQuery);
|
2df5be89eb0e69c8f9442ac8047bb183262db66f
|
[
"JavaScript"
] | 4
|
JavaScript
|
jiaojiao085/myapp
|
9acc940e0a7ecc3134d60b13cb6c2792005f3eb4
|
26967e4f44ea676bcc5a9065aaa38da81857b0b0
|
refs/heads/main
|
<repo_name>ShaneUP1/LAB-13-TODO-FE<file_sep>/README.old.md
# LAB-13-TODO-FE<file_sep>/src/Home.js
import React, { Component } from 'react'
export default class Home extends Component {
render() {
return (
<div className="homepage">
<h1>Welcome to your TODO portal!</h1>
<p>Are you sure you want to be here?</p>
<br></br>You're just going to be told lots of things you need to do.
</div>
)
}
}
|
76210c0450f800b51a119054a72b6e6a98178a43
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
ShaneUP1/LAB-13-TODO-FE
|
4537d0019caa91ebd2e72b257e79e7ef825301a7
|
7a95964a115149d134e33dbbac00c02bd9423a41
|
refs/heads/master
|
<file_sep>[](https://travis-ci.org/AchillesKal/url-extractor)
Extracts urls from given strings<file_sep><?php
namespace AchillesKal\UrlExtractor;
class UrlExtractor
{
private $url;
public function __construct($url)
{
$this->url = $url;
}
public function getUrl()
{
return $this->url;
}
public function extractUrl()
{
$this->removeScheme();
$this->removeSubdomain();
return $this->url;
}
public function removeScheme()
{
$this->url = preg_replace("(^https?://)", "", $this->url );
return $this;
}
public function removeSubdomain()
{
$parts = explode(".", $this->url);
$host1 = $parts[count($parts)-2];
$host2 = $parts[count($parts)-1];
$this->url = $host1 . '.' . $host2;
return $this;
}
}<file_sep><?php
namespace AchillesKal\UrlExtractorTests;
use AchillesKal\UrlExtractor\UrlExtractor;
use PHPUnit\Framework\TestCase;
class UrlExtractorTest extends TestCase
{
public function testExtractUrl()
{
$urls = [
'https://achilleskal.com',
'http://achilleskal.com',
'https://www.achilleskal.com',
'http://www.achilleskal.com',
];
foreach($urls as $url){
$extractor = new UrlExtractor($url);
$result = $extractor->extractUrl();
$this->assertEquals('achilleskal.com', $result);
}
}
public function testRemoveScheme()
{
$urls = [
'https://achilleskal.com',
'http://achilleskal.com',
];
foreach($urls as $url){
$extractor = new UrlExtractor($url);
$result = $extractor->removeScheme();
$this->assertEquals('achilleskal.com', $result->getUrl());
}
}
public function testRemoveSubdomain()
{
$urls = [
'https://www.achilleskal.com',
'https://web.achilleskal.com',
'http://test.real.achilleskal.com',
'http://wuba.test.real.achilleskal.com',
];
foreach($urls as $url){
$extractor = new UrlExtractor($url);
$result = $extractor->removeSubdomain();
$this->assertEquals('achilleskal.com', $result->getUrl());
}
}
}
|
f1136f6f68f34a96a15d2b82f07585e4259395d6
|
[
"Markdown",
"PHP"
] | 3
|
Markdown
|
AchillesKal/url-extractor
|
acef639465d12b64650ac3c20fde3673982fd950
|
a9a6e0472a30d14869194bc346b53824f06156ff
|
refs/heads/master
|
<repo_name>zapu/SublimeText-Eval<file_sep>/Evals.py
'''
Fork of NodeEval
now evaluates some other stuff too
'''
import sublime, sublime_plugin, os, time, threading
from functools import partial
from subprocess import Popen, PIPE, STDOUT
settingsFilename = "Evals.sublime-settings"
#
# Globals
#
g_lastCwd = None
#
# Create a new output, insert the message and show it
#
def panel(view, message, region, syntax):
s = sublime.load_settings(settingsFilename)
window = view.window()
# Should we set the clipboard?
clipboard = s.get('copy_to_clipboard')
if clipboard: sublime.set_clipboard( message )
# determine the output format
output = s.get('output')
clear = s.get('overwrite_output')
# Output to a Console (panel) view
if output == 'console':
p = window.get_output_panel('nodeeval_panel')
p_edit = p.begin_edit()
p.insert(p_edit, p.size(), message)
p.end_edit(p_edit)
p.show(p.size())
window.run_command("show_panel", {"panel": "output.nodeeval_panel"})
return False
# Output to a new file
if output == 'new':
active = False
for tab in window.views():
if 'Eval::Output' == tab.name(): active = tab
if active:
_output_to_view(view, active, message, clear=clear)
window.focus_view(active)
else:
active = scratch(view, message, "Eval::Output", clear=clear)
if syntax:
active.settings().set('syntax', syntax)
return False
# Output to the current view/selection (work performed in the calling method)
if output == 'replace':
edit = view.begin_edit()
view.replace(edit, region, message)
view.end_edit(edit)
return False
if output == 'clipboard':
sublime.set_clipboard( message )
return False
return False
#
# Helper to output views
#
def _output_to_view(v, output_file, output, clear=True):
edit = output_file.begin_edit()
if clear:
region = sublime.Region(0, output_file.size())
output_file.erase(edit, region)
output_file.insert(edit, 0, output)
output_file.end_edit(edit)
#
# Helper to output a new Scratch (temp) file
#
def scratch(v, output, title=False, **kwargs):
scratch_file = v.window().new_file()
if title:
scratch_file.set_name(title)
scratch_file.set_scratch(True)
_output_to_view(v, scratch_file, output, **kwargs)
scratch_file.set_read_only(False)
return scratch_file
#
# Eval the "data" (message) with basically: `node -p -e data`
#
def eval(view, data, region, print_compile):
global g_lastCwd
# get the current working dir, if one exists...
cwd = view.file_name()
if cwd != None:
cwd = os.path.dirname(cwd)
g_lastCwd = cwd
else:
cwd = g_lastCwd
plugin_settings = sublime.load_settings(settingsFilename)
current_syntax = view.settings().get('syntax')
file_engine = None
for engine_name in plugin_settings.get('evals'):
print engine_name
engine = plugin_settings.get('evals').get(engine_name)
if engine.get('syntax') in current_syntax:
file_engine = engine
break
if file_engine == None:
panel(view, "Cannot evaluate syntax %s." % current_syntax, False)
return False
command = [file_engine.get('command')] + file_engine.get('args')
print "evaling syntax %s using %s in %s" % (current_syntax, ' '.join(command), cwd)
try:
# node = Popen([node_command, "-p", data.encode("utf-8")], stdout=PIPE, stderr=PIPE)
if os.name == 'nt':
node = Popen(command, cwd=cwd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
else:
node = Popen(command, cwd=cwd, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
node.stdin.write( data.encode("utf-8") )
result, error = node.communicate()
except OSError,e:
error_message = """
Please check that the absolute path to the node binary is correct:
Attempting to execute: %s
Error:
""" % (command)
print e
panel(view, error_message, False)
return False
syntax = file_engine.get('outputSyntax')
print syntax
message = error if error else result
panel(view, message, region, syntax)
#
# Get the selected text regions (or the whole document) and process it
#
class EvalEvalCommand(sublime_plugin.TextCommand):
def run(self, edit):
# save the document size
view_size = self.view.size()
# get selections
regions = self.view.sel()
n_regions = list(regions)
num = len(regions)
x = len(self.view.substr(regions[0]))
print_compile = False
# select the whole document if there is no user selection
if num <= 1 and x == 0:
regions.clear()
regions.add( sublime.Region(0, view_size) )
print_compile = True
# get current document encoding or set sane defaults
encoding = self.view.encoding()
if encoding == 'Undefined':
encoding = 'utf-8'
elif encoding == 'Western (Windows 1252)':
encoding = 'windows-1252'
# eval selections
for region in regions:
data = self.view.substr(region)
eval(self.view, data, region, print_compile)
regions.clear()
regions.add(n_regions[0])
<file_sep>/Readme.md
Eval Sublime Text 2 Package
===============================
Fork of NodeEval, with hacked on support for CoffeeScript and F#. Adding other languages should be relatively easy - as long as their compilers/interpreters support running from stdin.
Install
-------
To install, clone the repo to Packages folder of Sublime Text 2.
Go to:
on Windows:
%APPDATA%\Sublime Text 2\Packages
on Ubuntu (and other others? no idea):
~/.config/sublime-text-2/Packages
and then:
git clone https://github.com/zapu/SublimeText-Evals.git Evals
Usage
-----
After installation, create your settings file (Preferences > Package Settings > Evals > Settings - User). Just copy everything from default settings file and change paths.
Then, when editing JavaScript, CoffeeScript or F#, press `ctrl+shift+l` to evaluate and display results. Files do not have to be saved, but their syntax has to be set properly. Use `ctrl+p` and `Set Syntax: ...`.
By default, CoffeeScript is set to compile to JavaScript, rather than to evaluate the code. My workflow is to use `ctrl+shift+l` twice when I need to run CoffeeScript code.
- Pressed the first time, it will output the JavaScript.
- Pressed the second time, it will run that JavaScript.
Unsure if this works with ST3, probably not.
Patches are welcome. You can, for example, pull the new threading code from upstream.
Author & Contributors
----------------------
[<NAME>](http://twitter.com/derekanderson)
[<NAME>](github.com/zapu)
License
-------
MIT License
|
a6d6f53b954e8d257c7098536e8464dfde3a7539
|
[
"Markdown",
"Python"
] | 2
|
Python
|
zapu/SublimeText-Eval
|
3447b19040513c5d8e766a4137c90445d0e87059
|
a1a8c3cf978524b69ccd5fa7c29cb8d2848abd6d
|
refs/heads/master
|
<file_sep>if [ $# != "3" ]
then
echo "Poll Voter v1"
echo "Author: @DotNetRussell"
echo
echo "Poll voter works great against polls that validate based on cookie or ip."
echo "The only requirement is curl being installed."
echo
echo "NOTES:"
echo "This produces a SHIT load of traffic. Don't use it for illegal purposes or face the music on your own."
echo
echo "Example:"
echo "./Pollvoter.sh <proxy list path/file> <POST data string> <Target Url>"
echo
echo
else
PROXYLIST=$1
DATA=$2
TARGET=$3
for proxy in $(cat $PROXYLIST | sort -R | sed -e 's/^[[:space:]]*//');
do
curl -j --verbose --connect-timeout 5 --max-time 8 -x $proxy -d $DATA $TARGET&
done
fi
|
bc8c30c1ea153d480d636ec1ab8ddba01770284d
|
[
"Shell"
] | 1
|
Shell
|
DotNetRussell/PollVoter
|
3c3ef39564095009c898efc5f524d37d031ab63e
|
a8aae77db6874843001e4343d57c5bba1d39eddc
|
refs/heads/main
|
<repo_name>gearsix/sunnyt<file_sep>/README.md
sunnyt
======
Generates a set of coordinates and makes requests to
[sunrise-sunset.org](https://sunrise-sunset.org/) to
fetch data about those coordinates sunrise and sunset
times and find out which one has the earliest sunrise.
<img alt="preview" src="./preview.png" height="300" />
Usage
-----
- `npm install` - install dependencies
- `npm start` - build & run the tool
Configuration
-------------
The tool is configured through a _./config.json_ file.
This file is required to run the tool.
- **datasetSize** = The number of coordinates to generate and fetch
data for
- **requestLimit** = The maximum number of requests to make to
sunrise-sunset.org
**Important:** Setting the _requestLimit_ too high might cause
sunrise-sunset.org to temporarily block your IP as a method to prevent
bots from flooding their servers. Any future requests after this will
recieve a ECONNREFUSED response. If this happens, you'll have to wait
for a period or proxy through another IP to make future requests.
Notes
-----
- Generally with the datasetSize set to 100 it returns at least one set
of coordinates that point to somewhere in east Russia, which has a
sunrise at 5-6pm (Greenwich Mean Time)
- **Sunrise in 1970?** - This happens when generated coordinates are
not in one of the countries
[supported by SunriseSunset](https://sunrise-sunset.org/explore). When
this happens their API returns epoch, such dates are ignored by sunnyt.
- This was my first project using Typescript, let me know if I'm doing
anything weird.
<img alt="xkcd Coordinate Precision" height="500"
src=https://imgs.xkcd.com/comics/coordinate_precision.png />
Future
------
- [ ] _should_ allow user to set coordinates and date parameters for requests
- [ ] _could_ Implement reverse geocoding to get the name of the location for the coordinates generated:
[Google Reverse Geocoding](https://developers.google.com/maps/documentation/javascript/geocoding#ReverseGeocoding)
- [ ] _could_ Make the webpage interactive
- Add an interactive map to allow users to select coordinates
- [x] _could_ Output useful data in a tidy .html file using a templating language like [mustache](https://mustache.github.io/)
Authors
-------
- <NAME> (<EMAIL>)
<file_sep>/src/index.ts
// nodejs
import { stdout } from 'process'
import { createServer } from 'http'
import { readFile, writeFile } from 'fs'
// npm
import { render } from 'mustache'
// internal
import { Config, SunriseSunset } from './sunnyt'
const cfg: Config = require('./config.json')
const outfile: string = './sunnyt.html'
const template: string = './output.mst'
/**
* main runtime, call `renderTemplate` and create a HTTP server on
* port 8000 serving the HTML output
**/
let emptyDataset = initDataset(cfg.datasetSize)
requestData(emptyDataset, cfg.requestLimit).then(async (dataset: SunriseSunset[]) => {
try {
if (dataset.length === 0)
throw(new Error('empty dataset'))
let templateString = await new Promise<string>((resolve) => {
readFile(template, async (err, templateBuffer) => {
if (err) throw err
resolve(templateBuffer.toString())
})
})
const html = await renderTemplate(templateString, dataset)
const server = createServer(async (request, response) => {
response.writeHead(200, { "Content-Type": "text/html" })
response.write(html)
response.end()
})
console.log('Serving content on http://localhost:8080/')
server.listen(8000)
} catch (err) {
console.error(err.message)
}
})
/**
* Generate a dataset (using `initDataset()` and `requestData()`).
* Then format that data to be used with `render` against the `template` file.
**/
function renderTemplate(template: string, dataset: SunriseSunset[]): Promise<string> {
const earliestIndex = findEarliestSunrise(dataset)
const templateData = {
data: dataset.map((data, index) => formatData(data, index)),
datasize: dataset.length,
earliest: formatData(dataset[earliestIndex], earliestIndex)
}
return render(template, templateData)
}
/**
* Find the index of the item in `dataset` with the earliest `.data.sunrise`.
**/
function findEarliestSunrise(dataset: SunriseSunset[]): number {
let earliestIndex: number = 0
dataset.forEach((item, index) => {
if (index === 0 || item.data === undefined)
return
if (item.data.sunrise > dataset[earliestIndex].data.sunrise)
earliestIndex = index
})
return earliestIndex
}
/**
* Format a `SunriseSunset` into an object to be parsed by the output template
**/
function formatData(item: SunriseSunset, id: number): Object {
return {
id: id+1, // 1-n instead of 0-n
lat: item.lat,
lng: item.lng,
sunrise: (item.data === undefined) ? 'no data' : item.data.sunrise.toUTCString(),
daylen: (item.data === undefined) ? 'no data' : item.data.dayLength.toTimeString()
}
}
/**
* initDataset initialsies a `SunriseSunset[]` of size `cfg.datasetSize`.
* All constructor values of the generates datas are left blank and
* get generated by the class constructor (see #SunriseSunset).
**/
function initDataset(size: number): SunriseSunset[] {
let ds: SunriseSunset[] = []
for (let i = 0; i < size; i++)
ds.push(new SunriseSunset())
return ds
}
/**
* requestData calls the `.requestData()` of all items in `dataset`.
* The number of concurrent requests made is limited by `cfg.requestLimit`,
* these requests are made in batches - the next batch is requested after
* all responses from the previous batch have been recieved.
* The returned `SunriseSunset[]` of the returned `Promise` will be `dataset`
* with it's `.data` variable updated (using `.requestData()`).
**/
function requestData(dataset: SunriseSunset[], requestLimit: number): Promise<SunriseSunset[]> {
return new Promise<SunriseSunset[]>(async(resolve) => {
const datasetSize = dataset.length
for (let index = 0; index < datasetSize; index += requestLimit) {
let numReqs = (index + requestLimit > datasetSize)
? dataset.length : index + requestLimit
let reqs: Promise<void>[] = []
for (let r = index; r < numReqs; r++)
reqs.push(dataset[r].requestData().catch(console.error))
console.log(`${numReqs} / ${dataset.length} requests...\r`)
await Promise.all(reqs)
}
dataset = dataset.filter(item => (
item.data !== undefined && item.data.sunrise.getFullYear() !== 1970
))
if (dataset.length < datasetSize) {
let numMissingData = datasetSize - dataset.length
console.log(`found ${numMissingData} items with invalid or missing data`)
dataset = dataset.concat(await requestData(initDataset(numMissingData), requestLimit))
}
resolve(dataset)
})
}
<file_sep>/src/sunnyt.ts
import { get } from 'http'
const maxLat: number = 90
const minLat: number = -90
const maxLng: number = 180
const minLng: number = -180
/**
* Generate a number inbetween `min` & `max`. If `min` or `max` are
* undefined, then `minLat` and `maxLat` will be used respectively.
**/
function generateLatitude(min? :number, max? :number): number {
if (!min) min = minLat
if (!max) max = maxLat
let rngLat = max - min
return parseFloat(((Math.random() * rngLat) - maxLat).toPrecision(8))
}
/**
* Generate a number inbetween `min` & `max`. If `min` or `max` are
* undefined, then `minLng` and `maxLng` will be used respectively.
**/
function generateLongitude(min? :number, max? :number): number {
if (!min) min = minLng
if (!max) max = maxLng
let rngLng = max - min
return parseFloat(((Math.random() * rngLng) - maxLng).toPrecision(8))
}
/**
* Available options in this tools configuration.
**/
export interface Config {
datasetSize: number
requestLimit: number
}
/**
* SunriseSunsetData contains all results data returned by sunrise-sunset.org.
* See sunrise-sunset.org/api for details.
**/
export interface SunriseSunsetData {
sunrise : Date,
sunset : Date,
solarNoon : Date,
dayLength : Date,
civilTwilightBegin : Date,
civilTwilightEnd : Date,
nauticalTwilightBegin : Date,
nauticalTwilightEnd : Date,
astronomicalTwilightBegin : Date,
astronomicalTwilightEnd : Date
}
/**
* SunriseSunset is the main class for this tool. It contians the request method
* and all the data required to make a request to sunrise-sunset.org.
**/
export class SunriseSunset {
readonly lat: number
readonly lng: number
readonly date: Date
data: SunriseSunsetData
constructor(lat? :number, lng? :number, date? :Date) {
this.lat = (!lat) ? generateLatitude() : lat
this.lng = (!lng) ? generateLongitude() : lng
this.date = (!date) ? new Date() : date
this.data = undefined
}
/**
* requestData returns the `Promise` of a `get` (from NodeJS' `http`). This request will be to
* `api.sunrise-sunset.org/...` and it's returned will be parsed and written to `this.data` for
* later access.
* WARNING: This will overwrite any currently existing data in `this.data`.
**/
requestData(): Promise<void> {
let dateFmt = `${this.date.getFullYear()}-${this.date.getMonth()+1}-${this.date.getDate()}`
const url = `http://api.sunrise-sunset.org/json?lat=${this.lat}&lng=${this.lng}&date=${dateFmt}&formatted=0`
const handleResponse = new Promise<void>((resolve, reject) => {
get(url, (response) => {
if (response.statusCode !== 200)
reject(new Error(`invalid response ${response.statusCode} from ${url}`))
let responseData = []
response.on('data', (chunk) => { responseData.push(chunk) })
response.on('error', (err) => { reject(err) })
response.on('end', () => {
try { // JSON.parse might throw if data is malformed
let data = JSON.parse(Buffer.concat(responseData).toString())
if (data.status !== "OK")
reject(new Error(`invalid status ${data.status} from ${url}`))
this.data = {
sunrise : new Date(data.results.sunrise),
sunset : new Date(data.results.sunset),
solarNoon : new Date(data.results.solar_noon),
dayLength : new Date(data.results.day_length),
civilTwilightBegin : new Date(data.results.civil_twilight_begin),
civilTwilightEnd : new Date(data.results.civil_twilight_end),
nauticalTwilightBegin : new Date(data.results.nautical_twilight_begin),
nauticalTwilightEnd : new Date(data.results.nautical_twilight_end),
astronomicalTwilightBegin : new Date(data.results.astronomical_twilight_begin),
astronomicalTwilightEnd : new Date(data.results.astronomical_twilight_end)
}
resolve()
} catch(err) {
reject(err)
}
})
}).on('error', (err) => reject(err))
})
return handleResponse
}
}
|
1edfd68e44436ceb17541fd7c56ef83171b8848c
|
[
"Markdown",
"TypeScript"
] | 3
|
Markdown
|
gearsix/sunnyt
|
69aca9844e12d1e4f3f8248324bf168df4fd9a54
|
ed1cfe84ecbe377837abf33347fe01cd314f38b2
|
refs/heads/main
|
<repo_name>adnayan/tweetscrap<file_sep>/README.md
"# tweetscrap"
<file_sep>/main.py
import pandas as pd
import datetime as dt
import time
import tweepy
consumer_key = "your consumer key"
consumer_secret = "your consumer secret"
access_token = "your access token"
access_token_secret = "yout access token secret"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
"""
Parameters to check for the tweets
parameter_name: from_date, type: datetime
parameter_name: to_date, type: datetime
parameter_name: username, type: string
"""
from_date = dt.datetime(2019, 8, 1, 0, 0, 0)
to_date = dt.datetime(2019, 9, 1, 0, 0, 0)
username = "a_tweeter_user"
"""
Columns name: Column value in twitter status
text: status.full_text
created_at: status.created_at
tweet_id: status.id_str
retweet_count: status.retweet_count
favorite_count: status.favorite_count
user_name: status.user.name
user_screen_name: status.user.screen_name
user_description: status.user.description
"""
# Comparing if tweet date is between the threshold date
def compare_date(created_date, from_date, to_date):
return created_date >= from_date and created_date <= to_date
# handeling the rate limit
def limit(cursor):
while True:
try:
yield cursor.next()
except Exception as e:
print()
print(str(e))
print()
time.sleep(15 * 60)
tweets_list = []
itcount = 1
for i, status in enumerate(limit(tweepy.Cursor(api.user_timeline, screen_name=username, tweet_mode="extended").items())):
if(status.created_at < from_date):
break
if(compare_date(created_date=status.created_at, from_date=from_date, to_date=to_date)):
tweet_id_str = "\"" + status.id_str + "\""
tweet_list_item = [
status.full_text,
status.created_at,
tweet_id_str,
status.retweet_count,
status.favorite_count,
status.user.name,
status.user.screen_name,
status.user.description
]
print(tweet_list_item)
print()
tweets_list.append(tweet_list_item)
itcount = itcount + 1
columns_name = ["text", "created_at", "tweet_id", "retweet_count", "favorite_count", "user_name", "user_screen_name", "user_description"]
tweet_df = pd.DataFrame( tweets_list, columns=columns_name)
tweet_df.to_csv("./export.csv")
|
4e51c3db5aaeeaa7731f5f3c5340b0cd8d28b9e8
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
adnayan/tweetscrap
|
82a7c5cf4fd44fbf618f5d9b688d46a417b07d4a
|
5a42965ce9597e14e54af2ac44d488ba694ec89b
|
refs/heads/master
|
<repo_name>firedevbr/formulario-mpdf<file_sep>/www/processa.php
<?php
use League\Csv\Reader;
require_once 'vendor/autoload.php';
define('RECORDS_PER_COLUMN', 10);
define('MAX_FILES_PER_REQUEST', 50);
$tmpUploadedFile = $_FILES['csv']['tmp_name'];
$splFile = new \SplFileObject($tmpUploadedFile);
$delimiter = detectDelimiter($tmpUploadedFile);
$csv = Reader::createFromFileObject($splFile);
$csv->setHeaderOffset(0);
$csv->setDelimiter($delimiter);
$total = $csv->count();
if ($total > MAX_FILES_PER_REQUEST) {
die('envie no máximo 50 linhas por vez');
}
$records = $csv->getRecords(); //returns all the CSV records as an Iterator object
$titulo = $_POST['titulo'];
$baseTemplate = file_get_contents('formulario.html');
$baseTemplate = str_replace('#TITULO#', $titulo, $baseTemplate);
$filesCreated = [];
$tarName = __DIR__ . '/tmp/' . uniqid('arquivos_') . '.tar';
$tarFile = new \PharData($tarName);
$srcImagem = 'face_ficha_clinica.png';
$imgPath = '';
if (isset($_FILES['imagem'])) {
$srcImagem = 'tmp/img/' . $_FILES['imagem']['name'];
$imgPath = __DIR__ . '/tmp/img/' . $_FILES['imagem']['name'];
move_uploaded_file($_FILES['imagem']['tmp_name'], $imgPath);
}
foreach ($records as $record) {
$totalFields = count($record);
$totalColumns = ceil($totalFields / RECORDS_PER_COLUMN);
$keys = array_keys($record);
$columns = '';
for ($i = 0; $i < $totalColumns; $i++) {
$columns .= "<div id=\"dadosDoCliente\" style=\"float: left; width: 30%; padding-right: 10px\">";
$currentField = $i * RECORDS_PER_COLUMN;
for ($j = $currentField; $j < RECORDS_PER_COLUMN * ($i + 1); $j++) {
if ($j >= $totalFields) {
break;
}
$field = $keys[$j];
$value = $record[$field];
$columns .= "<b>{$field}</b>: <i>{$value}</i><br><br>";
}
$columns .= "</div>";
}
$baseTemplate = str_replace('#DIVSDADOS#', $columns, $baseTemplate);
$baseTemplate = str_replace('#SRC_IMAGEM#', $srcImagem, $baseTemplate);
$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
$mpdf->WriteHTML($baseTemplate);
$tmpfname = __DIR__ . "/tmp/pdfs/" . uniqid("report") . '.pdf';
$attachment = $mpdf->Output('', 'S');
$handle = fopen($tmpfname, "w");
fwrite($handle, $attachment);
fclose($handle);
$filesCreated[] = $tmpfname;
}
$tarFile->buildFromDirectory(__DIR__ . '/tmp/pdfs');
$tarFile->compress(\Phar::GZ);
foreach ($filesCreated as $file) {
unlink($file);
}
unlink($tarName);
$fullTarName = $tarName . '.gz';
$size = filesize($fullTarName);
header('Content-Type: application/tar+gzip');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . sprintf('"%s"', addcslashes(basename($fullTarName), '"\\')));
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
ob_clean();
flush();
readfile($fullTarName);
unlink($fullTarName);
if (file_exists($imgPath)) {
unlink($imgPath);
}
function detectDelimiter($csvFile): string
{
$delimiters = [
';' => 0,
',' => 0,
'\t' => 0,
'|' => 0
];
$handle = fopen($csvFile, "r");
$firstLine = fgets($handle);
fclose($handle);
foreach ($delimiters as $delimiter => &$count) {
$count = count(str_getcsv($firstLine, $delimiter));
}
return array_search(max($delimiters), $delimiters);
}
|
acd6d09825b82fdd000084d52c736bf42bbaa011
|
[
"PHP"
] | 1
|
PHP
|
firedevbr/formulario-mpdf
|
77edb73a36ffbb7b658baff227fbccbf5e8001f4
|
15f5f4200c7dab8fff293213a510022637566c8a
|
refs/heads/master
|
<repo_name>vermisean/BattleTanks<file_sep>/Source/BattleTanks/Public/TankTrack.h
// Copyright 2018 <NAME>
#pragma once
#include "CoreMinimal.h"
#include "Components/StaticMeshComponent.h"
#include "TankTrack.generated.h"
/**
* Sets maximum driving force and used to apply forces to the tank
*/
UCLASS(meta = (BlueprintSpawnableComponent))
class BATTLETANKS_API UTankTrack : public UStaticMeshComponent
{
GENERATED_BODY()
public:
// Called to drive tank
UFUNCTION(BlueprintCallable, Category = "Movement")
void SetThrottle(float Throttle);
// Max force per track in Newtons
UPROPERTY(EditDefaultsOnly)
float MaxDrivingForce = 40000000.0f; // Assume 40 tonne tank with 1g acceleration
private:
UTankTrack();
TArray<class ASprungWheel*> GetWheels() const;
void DriveTrack(float CurrentThrottle);
};
<file_sep>/Source/BattleTanks/Private/Tank.cpp
// Copyright 2018 <NAME>
#include "Tank.h"
#include "BattleTanks.h"
ATank::ATank()
{
PrimaryActorTick.bCanEverTick = false;
}
void ATank::BeginPlay()
{
Super::BeginPlay();
CurrentHealth = StartingHealth;
}
float ATank::TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{
int32 DamagePoints = FPlatformMath::RoundToInt(Damage);
int32 DamageToApply = FMath::Clamp(DamagePoints, 0, CurrentHealth);
CurrentHealth -= DamageToApply;
if (CurrentHealth <= 0)
{
OnDeath.Broadcast();
}
return DamageToApply;
}
float ATank::GetHealthPercent() const
{
return (float)CurrentHealth / (float)StartingHealth;
}
<file_sep>/Source/BattleTanks/Public/TankTurret.h
// Copyright 2018 <NAME>
#pragma once
#include "CoreMinimal.h"
#include "Components/StaticMeshComponent.h"
#include "TankTurret.generated.h"
/**
* Rotates the turret for aiming
*/
UCLASS(meta = (BlueprintSpawnableComponent))
class BATTLETANKS_API UTankTurret : public UStaticMeshComponent
{
GENERATED_BODY()
public:
// -1 max left, +1 max right rotation
void Rotate(float RelativeSpeed);
private:
UPROPERTY(EditDefaultsOnly, Category = "Setup")
float MaxDegreesPerSecond = 25.0f;
};
<file_sep>/Source/BattleTanks/Private/TankMovementComponent.cpp
// Copyright 2018 <NAME>
#include "TankMovementComponent.h"
#include "TankTrack.h"
#include "BattleTanks.h"
void UTankMovementComponent::Initialize(UTankTrack* LeftTrackToSet, UTankTrack* RightTrackToSet)
{
LeftTrack = LeftTrackToSet;
RightTrack = RightTrackToSet;
}
void UTankMovementComponent::IntendMoveForward(float Throw)
{
if (!ensure(LeftTrack) || !ensure(RightTrack)) { return; }
LeftTrack->SetThrottle(Throw);
RightTrack->SetThrottle(Throw);
}
void UTankMovementComponent::IntendTurnRight(float Throw)
{
if (!ensure(LeftTrack) || !ensure(RightTrack)) { return; }
LeftTrack->SetThrottle(Throw);
RightTrack->SetThrottle(-Throw);
}
void UTankMovementComponent::RequestDirectMove(const FVector& MoveVelocity, bool bForceMaxSpeed)
{
// No Super as we are replacing the base functionality - We are intercepting this method for the velocity only
// Gets the AI's forward move velocity normal
FVector AIForwardIntention = MoveVelocity.GetSafeNormal();
// Get AI's forward vector normal
FVector TankForward = GetOwner()->GetActorForwardVector().GetSafeNormal();
// Get dot product
float ForwardThrow = FVector::DotProduct(AIForwardIntention, TankForward);
// Move forward or backward based on dot product
this->IntendMoveForward(ForwardThrow);
// Get cross product
float RightThrow = FVector::CrossProduct(TankForward, AIForwardIntention).Z;
// Move right or left based on cross product
this->IntendTurnRight(RightThrow);
}
<file_sep>/Source/BattleTanks/Public/TankAIController.h
// Copyright 2018 <NAME>
#pragma once
#include "CoreMinimal.h"
#include "AIController.h"
#include "TankAIController.generated.h"
// Depends on movement via pathfinding
/**
* Handles death of tank AI
*/
UCLASS()
class BATTLETANKS_API ATankAIController : public AAIController
{
GENERATED_BODY()
protected:
// How close the AI tank can get to the player
UPROPERTY(EditDefaultsOnly, Category = "AI Setup")
float AcceptanceRadius = 80000.0f;
private:
virtual void BeginPlay() override;
virtual void Tick( float DeltaTime ) override;
virtual void SetPawn(APawn* InPawn) override;
// Delegate
UFUNCTION()
void OnPossessedTankDeath();
};
<file_sep>/Source/BattleTanks/Private/SpawnPoint.cpp
// Copyright 2018 <NAME>
#include "SpawnPoint.h"
#include "Runtime/Engine/Classes/Engine/World.h"
#include "Runtime/Engine/Classes/Kismet/GameplayStatics.h"
USpawnPoint::USpawnPoint()
{
PrimaryComponentTick.bCanEverTick = true;
}
void USpawnPoint::BeginPlay()
{
Super::BeginPlay();
SpawnedActor = GetWorld()->SpawnActorDeferred<AActor>(SpawnClass, GetComponentTransform());
if (!SpawnedActor) return;
SpawnedActor->AttachToComponent(this, FAttachmentTransformRules::KeepWorldTransform);
UGameplayStatics::FinishSpawningActor(SpawnedActor, GetComponentTransform());
}
void USpawnPoint::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
<file_sep>/Source/BattleTanks/Private/TankAIController.cpp
// Copyright 2018 <NAME>
#include "TankAIController.h"
#include "TankAimingComponent.h"
#include "Tank.h"
#include "BattleTanks.h"
void ATankAIController::BeginPlay()
{
Super::BeginPlay();
}
void ATankAIController::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
APawn* PlayerTank = GetWorld()->GetFirstPlayerController()->GetPawn();
APawn* ControlledTank = GetPawn();
// Ensure there is a player available
if (!(PlayerTank && ControlledTank)) { return; }
// Move towards player
MoveToActor(PlayerTank, AcceptanceRadius);
// Aim towards player
UTankAimingComponent* AimingComponent = ControlledTank->FindComponentByClass<UTankAimingComponent>();
AimingComponent->AimAt(PlayerTank->GetActorLocation());
if(AimingComponent->GetFiringState() == EFiringState::Locked)
{
AimingComponent->Fire();
}
}
void ATankAIController::SetPawn(APawn* InPawn)
{
// Using this so that we can ensure we have setpawn called
Super::SetPawn(InPawn);
if (InPawn)
{
ATank* PossessedTank = Cast<ATank>(InPawn);
if (!PossessedTank) { return; }
// Subscribe our local method to tank's death event
PossessedTank->OnDeath.AddUniqueDynamic(this, &ATankAIController::OnPossessedTankDeath);
}
}
void ATankAIController::OnPossessedTankDeath()
{
if (!GetPawn()) { return; }
// Destroys AI Controller when tank is dead
GetPawn()->DetachFromControllerPendingDestroy();
//UE_LOG(LogTemp, Warning, TEXT("Received!"));
}
<file_sep>/Source/BattleTanks/Private/TankTurret.cpp
// Copyright 2018 <NAME>
#include "TankTurret.h"
#include "BattleTanks.h"
void UTankTurret::Rotate(float RelativeSpeed)
{
// Ensure relative speed is clamped between -1 and 1
RelativeSpeed = FMath::Clamp<float>(RelativeSpeed, -1, +1);
// Move turret right amount this frame, given max Rotation speed and frame time, clamp within reasonable bounds
float RotationChange = RelativeSpeed * MaxDegreesPerSecond * GetWorld()->DeltaTimeSeconds;
float NewRotation = RelativeRotation.Yaw + RotationChange;
// Set relative location
SetRelativeRotation(FRotator(0.0f, NewRotation, 0.0f));
}
<file_sep>/Source/BattleTanks/Private/TankBarrel.cpp
// Copyright 2018 <NAME>
#include "TankBarrel.h"
#include "BattleTanks.h"
void UTankBarrel::Elevate(float RelativeSpeed)
{
// Ensure relative speed is clamped between -1 and 1
RelativeSpeed = FMath::Clamp<float>(RelativeSpeed, -1, +1);
// Move barrel right amount this frame, given max elevation speed and frame time, clamp within reasonable bounds
float ElevationChange = RelativeSpeed * MaxDegreesPerSecond * GetWorld()->DeltaTimeSeconds;
float RawNewElevation = RelativeRotation.Pitch + ElevationChange;
float Elevation = FMath::Clamp<float>(RawNewElevation, MinElevationDegrees, MaxElevationDegrees);
// Set relative location
SetRelativeRotation(FRotator(Elevation, 0.0f, 0.0f));
}
<file_sep>/Source/BattleTanks/Private/TankTrack.cpp
// Copyright 2018 <NAME>
#include "TankTrack.h"
#include "SprungWheel.h"
#include "SpawnPoint.h"
#include "BattleTanks.h"
UTankTrack::UTankTrack()
{
PrimaryComponentTick.bCanEverTick = true;
}
// Set throttle between -2 and 2
void UTankTrack::SetThrottle(float Throttle)
{
float CurrentThrottle = FMath::Clamp<float>(Throttle, -2, +2);
DriveTrack(CurrentThrottle);
}
void UTankTrack::DriveTrack(float CurrentThrottle)
{
// Apply appropriate force through throttle
float ForceApplied = CurrentThrottle * MaxDrivingForce;
// Get wheels and get force per wheel
TArray<ASprungWheel*> Wheels = GetWheels();
float ForcePerWheel = ForceApplied / Wheels.Num();
// Run through each wheel, apply correct force
for (ASprungWheel* Wheel : Wheels)
{
Wheel->AddDrivingForce(ForcePerWheel);
}
}
TArray<class ASprungWheel*> UTankTrack::GetWheels() const
{
TArray<ASprungWheel*> ResultArray;
TArray<USceneComponent*> Children;
// Need to iterate over child components
GetChildrenComponents(true, Children);
for (USceneComponent* Child : Children)
{
USpawnPoint* SpawnPointChild = Cast<USpawnPoint>(Child);
if (!SpawnPointChild) { continue; }
AActor* SpawnedChild = SpawnPointChild->GetSpawnedActor();
ASprungWheel* SprungWheel = Cast<ASprungWheel>(SpawnedChild);
if (!SprungWheel) { continue; }
ResultArray.Add(SprungWheel);
}
return ResultArray;
}
<file_sep>/Source/BattleTanks/TankPlayerController.cpp
// Copyright 2018 <NAME>
#include "TankPlayerController.h"
#include "TankAimingComponent.h"
#include "Tank.h"
#include "BattleTanks.h"
void ATankPlayerController::BeginPlay()
{
Super::BeginPlay();
if (!GetPawn()) { return; }
// Event delegate
UTankAimingComponent* AimingComponent = GetPawn()->FindComponentByClass<UTankAimingComponent>();
if (!ensure(AimingComponent)) { return; }
FoundAimingComponent(AimingComponent);
}
void ATankPlayerController::Tick(float DeltaTime)
{
Super::Tick( DeltaTime );
AimTowardsCrosshair();
}
void ATankPlayerController::AimTowardsCrosshair()
{
if (!GetPawn()) { return; } // If not possessing a tank
UTankAimingComponent* AimingComponent = GetPawn()->FindComponentByClass<UTankAimingComponent>();
if (!ensure(AimingComponent)) { return; }
FVector HitLocation; // Out parameter
bool bGotHitLocation = GetSightRayHitLocation(HitLocation);
// For line tracing
if (bGotHitLocation)
{
AimingComponent->AimAt(HitLocation);
}
}
// Gets world location of line trace through crosshair, true if it hits landscape
bool ATankPlayerController::GetSightRayHitLocation(FVector &HitLocation) const
{
// Find crosshair position in pixel coordinates
int32 ViewportSizeX, ViewportSizeY;
GetViewportSize(ViewportSizeX, ViewportSizeY);
FVector2D ScreenLocation = FVector2D(ViewportSizeX * CrosshairXLocation, ViewportSizeY * CrosshairYLocation);
// Deproject screen position of crosshair to world direction
FVector LookDirection;
if (GetLookDirection(ScreenLocation, LookDirection))
{
// Line trace along the look direction, see what was hit (up to max range)
return GetLookVectorHitLocation(LookDirection, HitLocation);
}
return false;
}
// Deprojects the screen position to the world position
bool ATankPlayerController::GetLookDirection(FVector2D ScreenLocation, FVector& LookDirection) const
{
FVector CameraWorldLocation;
return DeprojectScreenPositionToWorld(ScreenLocation.X, ScreenLocation.Y, CameraWorldLocation, LookDirection);
}
bool ATankPlayerController::GetLookVectorHitLocation(FVector LookDirection, FVector& HitLocation) const
{
FHitResult HitResult;
FVector StartLocation = PlayerCameraManager->GetCameraLocation();
FVector EndLocation = StartLocation + (LookDirection * LineTraceRange);
if(GetWorld()->LineTraceSingleByChannel(HitResult, StartLocation, EndLocation, ECollisionChannel::ECC_Camera))
{
HitLocation = HitResult.Location;
return true;
}
HitLocation = FVector(0.0f);
return false;
}
void ATankPlayerController::SetPawn(APawn* InPawn)
{
// Using this so that we can ensure we have setpawn called
Super::SetPawn(InPawn);
if (InPawn)
{
ATank* PossessedTank = Cast<ATank>(InPawn);
if (!ensure(PossessedTank)) { return; }
// Subscribe our local method to tank's death event
PossessedTank->OnDeath.AddUniqueDynamic(this, &ATankPlayerController::OnControlledTankDeath);
}
}
void ATankPlayerController::OnControlledTankDeath()
{
StartSpectatingOnly();
}
|
9b4451caff0453309133e60d430827b1a0b2c34f
|
[
"C++"
] | 11
|
C++
|
vermisean/BattleTanks
|
0350f71d9d07a9a757c6e2fe0fcdaf8c2419bda6
|
f3f1364f32dd37dfa3b78d310414312f9c8fc4cf
|
refs/heads/master
|
<repo_name>YutaYANAGITYAYA/AnimeFace_Detector<file_sep>/AnimeFace_Detector.py
from PIL import ImageGrab
import cv2
import numpy as np
path = "lbpcascade_animeface.xml"
cascade = cv2.CascadeClassifier(path)
while (cv2.waitKey(1) != 27):
img = ImageGrab.grab()
img = np.asarray(img)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)
faces = cascade.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (100, 100))
if len(faces) > 0:
for (x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w,y+h), (255,255,255), 2)
img = cv2.resize(img, (img.shape[1]/2,img.shape[0]/2))
cv2.imshow("res", img)
cv2.destroyAllWindows()
<file_sep>/README.md
# AnimeFace_Detector

Screen capture and Anime face detect
### Credits
[nagadomi](https://github.com/nagadomi/lbpcascade_animeface) for face detector
|
59bdfb09f7ff1e0fa1599432f863064dcbdb3a97
|
[
"Markdown",
"Python"
] | 2
|
Python
|
YutaYANAGITYAYA/AnimeFace_Detector
|
8279c09a386dd6bd2ff309045a16dedf0aba7bf9
|
7a1f271c24ccfb3ad6953083939bb2f7c6b00e46
|
refs/heads/master
|
<file_sep>var gesture = new Gesture(),
events;
function onDragging(event) {
var $target = $(event.currentTarget),
transform = getTransform($target),
regExp = /(.*)(px)(,)(.*)(px)/ig,
result = regExp.exec(transform.translate),
top = result && result[4] ? Number(result[4]) : 0,
left = result && result[1] ? Number(result[1]) : 0;
transform.translate = (left + event.deltaX) + 'px,' + (top + event.deltaY) + 'px';
setTransform($target, transform);
}
function onDrag(event) {
var $target = $(event.currentTarget),
offset = $target.offset();
}
function onHold(event) {
var $target = $(event.currentTarget);
$target.addClass('holding');
}
function onPinching(event) {
var $target = $(event.currentTarget),
transform = getTransform($target),
scale = event.scale,
originScale = $target.data('scale') || 1;
transform.scale = originScale * scale;console.log(transform.scale);
setTransform($target, transform);
}
function onPinch(event) {
var $target = $(event.currentTarget),
transform = getTransform($target),
scale = transform.scale;
$target.data('scale', scale);
}
function onRotating(event) {
var $target = $(event.currentTarget),
transform = getTransform($target),
delta = event.delta,
angle = extractDegree(transform.rotate);
transform.rotate = (angle + delta) + 'deg';
setTransform($target, transform);
}
function onRotate(event) {
var $target = $(event.currentTarget),
transform = getTransform($target),
rotate = transform.rotate;
$target.data('rotate', rotate);
}
function extractDegree(rotate) {
if (rotate.indexOf('deg')) {
return Number(rotate.replace('deg', ''));
}
return 0;
}
function getTransform(target) {
var $target = $(target),
transformString = $target.css('-webkit-transform'),
transformArray = transformString.split(')'),
transform = {
translate: '0,0',
scale: 1,
rotate: 0
},
result, prop, value;
if (transformString === 'none') {
return transform;
}
for (var i = 0; i < transformArray.length; i++) {
result = transformArray[i].split('(');
prop = result[0].trim();
value = result[1];
if (prop) {
transform[prop] = value;
}
}
return transform;
}
function setTransform(target, transform) {
var $target = $(target),
transformString = '';
for (var name in transform) {
transformString += name + '(' + transform[name] + ')';
}
$target.css('-webkit-transform', transformString);
return transformString;
}
events = {
'dragging .photo': onDragging,
'drag .photo': onDrag,
'hold .photo': onHold,
'pinching .photo': onPinching,
'pinch .photo': onPinch,
'rotating .photo': onRotating,
'rotate .photo': onRotate
};
gesture.on(events);<file_sep>/**
* Created by JetBrains WebStorm.
* User: tjk && sankyu
* Date: 12-5-24
* Time: 上午11:58
* To change this template use File | Settings | File Templates.
*/
(function(window,document){
//连续震动,UCWEB默认支持最大10秒
var v1 = 10000,
//间隔震动
v2 = 500,
//间隔震动时的循环间隔
timeout = null,
//计时
i = 0,
//原图和手机屏幕间的长宽比例
ratioWidth = 0,ratioHeight = 0,
//按钮移动位置的偏移量
offset = 18,
//当前震动状态 -1为停止,1为间隔震动,2为连续震动
status = -1;
//图片源
var imagesSource = [
{id:'bg',src:'img/bg.png'},
{id:'bg_red',src:'img/red_bg.png'},
{id:'bg_blue',src:'img/blue_bg.png'},
{id:'btn',src:'img/btn.png'}
],
//图片数量
imagesLen = imagesSource.length,
//图片缓存
images = [],
imagesInit = 0,
//
imagesTimeout;
var btnPosStartHeight = 0,
btnPosStartWidth = 0,
btnPosEndWidth = 0,
btnPosEndHeight = 0,
currentBgImage = null;
function $(id){
return document.getElementById(id);
}
function once(){
navigator.vibrate(200);
}
function v1Fun(){
navigator.vibrate(v1);
}
function v2Fun(){
navigator.vibrate(v2);
}
function stop(){
window.clearTimeout(timeout);
window.clearInterval(timeout);
navigator.vibrate(0);
}
window.count = function(){}
window.onload = function(){
//统计时间
window.setInterval(count,1000);
init();
currentBgImage = getImageById('bg');
$('canvas').addEventListener('touchstart',function(e){
vibrate(e);
});
};
function initImages(){
for(var i=0;i<imagesLen;i++){
var tmp = new Image();
tmp.id = imagesSource[i].id;
tmp.src = imagesSource[i].src;
tmp.onload = function(){
imagesInit++;
}
images.push(tmp);
}
}
function imagesInitLoop(){
if(imagesInit == imagesLen){
window.clearTimeout(imagesTimeout);
setCanvasWH();
paint();
return;
}
imagesTimeout = window.setTimeout(imagesInitLoop,33);
}
function init(){
initImages()
imagesInitLoop();
}
function getImageById(id){
for(var i=0;i<imagesLen;i++){
if(images[i].id == id){
return images[i];
}
}
return null;
}
function paint(){
var canvas = $("canvas");
var ctx = canvas.getContext('2d');
ctx.save();
//画背景
ctx.drawImage(currentBgImage,0,0,canvas.width,canvas.height);
var btnImage = getImageById('btn');
var btnWH = resetBtnImageWH(btnImage,canvas);
btnPosStartHeight = Math.round(canvas.height - btnWH[1]) + offset;
btnPosStartWidth = Math.round(canvas.width / 2 - btnWH[0] / 2) + 2;
btnPosEndWidth = btnPosStartWidth + btnWH[0];
btnPosEndHeight = btnPosStartHeight + btnWH[1];
ctx.translate(btnPosStartWidth,btnPosStartHeight);
ctx.drawImage(btnImage,0,0,btnWH[0],btnWH[1]);
ctx.restore();
}
function setCanvasWH(){
var canvas = $('canvas');
if (canvas.width != window.outerWidth ||
canvas.height != window.outerHeight){
canvas.width = window.outerWidth;
canvas.height = window.outerHeight;
}
}
//重置按钮宽高
function resetBtnImageWH(btnImage,canvas){
var width = 0,height = 0,
canvas = $('canvas');
ratioWidth = canvas.width / getImageById('bg').width;
ratioHeight = canvas.height / getImageById('bg').height;
width = Math.round(btnImage.width * ratioWidth);
height = Math.round(btnImage.height * ratioHeight);
return [width,height];
}
function vibrate(e){
var canvas = $("canvas"),
screenX = e.touches[0].screenX,
screenY = e.touches[0].screenY;
//控制在按钮区域内。
if(screenX > btnPosStartWidth && screenY > btnPosStartHeight
&& screenX < btnPosEndWidth && screenY < btnPosEndHeight){
//修改按钮位置、当前震动状态以及
switch(status){
case -1 :
status = 1;
offset = 0;
currentBgImage = getImageById('bg_blue');
stop();
timeout = window.setInterval(v2Fun,1000);
break;
case 1 :
status = 2;
offset = -18;
currentBgImage = getImageById('bg_red');
stop();
v1Fun();
break;
case 2 :
status = -1;
offset = 18;
currentBgImage = getImageById('bg');
stop();
break;
default:
status = -1;
offset = 18;
currentBgImage = getImageById('bg');
stop();
break;
}
//重画效果图
paint();
}
}
})(this,document);<file_sep>/**
* Created by JetBrains WebStorm.
* User: tjk && sankyu
* Date: 12-9-3
* Time: 下午5:48
* To change this template use File | Settings | File Templates.
*/
(function(){
function Note(){
this.id = 0;
this.title = "";
this.text = "";
this.time = "";
this.toJson = function(){
return {
"id" : this.id,
"title" : this.title,
"text" : this.text,
"time" : this.time
}
}
}
//var maxId = 1;
var h5note = {
maxId : 1,
bindEditContent:function(){
var editArea = document.querySelectorAll("#editContent");
editArea.addEventListener("change",function(){
alert("change event");
$(".title").text("change event");
});
editArea.addEventListener("DOMCharacterDataModified",function(){
alert("DOMCharacterDataModified event");
$(".title").text("DOMCharacterDataModified event");
});
editArea.addEventListener("focus",function(){
alert("focus event");
$(".title").text("focus event");
});
},
//切换
tiggler:function(event){
var $article = $(".page");
if($article.hasClass("showMenu")){
$article.removeClass("showMenu");
}else{
$article.addClass("showMenu");
}
},
updateLocalMaxId:function(){
var temp = localStorage.getItem("maxId");
if(temp != null){
h5note.maxId = parseInt(temp);
}else{
h5note.maxId = 1;
}
},
plugMaxId:function(){
var temp = localStorage.getItem("maxId");
if(temp != null){
h5note.maxId = parseInt(temp) + 1;
}
localStorage.setItem("maxId",h5note.maxId);
},
//初始化
init:function(){
$("#main").width(window.outerWidth);
$("#main").height(window.outerHeight);
$("#main #menu section").height(window.outerHeight - 46);
var headerH = $(".page header").height();
$("#editContent").height($("#main").height() - headerH);
h5note.updateLocalMaxId();
h5note.getNotes();
$("#tiggler").on("click",function(){
h5note.tiggler();
h5note.getNotes();
});
$("#save").on("click",function(){
if($(this).text() == "新建"){
$(this).text("保存");
$("#editContent").html("");
$("#editContent").attr("data-id","");
$("#editContent").focus();
}else{
console.log("开始保存笔记!");
h5note.addNote();
$(this).text("新增");
console.log("笔记保存成功!");
}
});
$("#clear").on("click",function(){
localStorage.clear();
h5note.getNotes();
});
setTimeout(function(){window.scrollTo(0,0)},100);
},
//读取所有本地存储的数据
getNotes:function(){
var length = localStorage.length;
var list = new Array();
var temphtml = "",n;
for(var i=0;i<length;i++){
var key = localStorage.key(i);
if(!isNaN(key)){
console.log(key);
n = JSON.parse(localStorage.getItem(key));
temphtml += "<article data-id='" + n.id + "'>" + n.title +"</article>";
}
}
document.getElementById("noteNav").innerHTML = temphtml;
$("#noteNav article").on("click",function(){
h5note.showNote($(this).attr("data-id"));
var $article = $(".page");
if($article.hasClass("showMenu")){
$article.removeClass("showMenu");
}else{
$article.addClass("showMenu");
}
$("#save").text("保存");
});
},
//创建一条笔记到本地存储
addNote:function(){
var n = new Note();
text = document.getElementById("editContent").innerHTML;
text2 = document.getElementById("editContent").innerText;
n.text = text;
n.title = text2.substring(0,15);
n.time = new Date().toString();
var dataid = $("#editContent").attr("data-id");
if(dataid != ""){
n.id = dataid;
localStorage.setItem(dataid,JSON.stringify(n.toJson()));
}else{
h5note.plugMaxId();
n.id = h5note.maxId;
localStorage.setItem(h5note.maxId,JSON.stringify(n.toJson()));
}
},
//读取单条笔记
getNote:function(id){
var object = JSON.parse(localStorage.getItem(id));
return object;
},
showNote:function(id){
var n = h5note.getNote(id);
$("#editContent").html(n.text);
$("#editContent").attr("data-id",id);
}
};
h5note.init();
})();
|
5cdc429090c9457c6fb0c0292f1d93cb5a3d3ce1
|
[
"JavaScript"
] | 3
|
JavaScript
|
uclabs/uclabs.github.com
|
e41e9ee53bd8f8ab7b9b943be59e7e8994f198ad
|
6950f410be90024274bb22e24252cb2d63085ede
|
refs/heads/master
|
<file_sep>package com.app.sg.mall.util;
import com.app.sg.mall.dto.Items;
public class AppUtil {
private static final String COMMA = ",";
public static Items convertStringToItems(Items item, String line) {
String[] p = line.split(COMMA);
if (isNotNull(p[0]) && isNotNull(p[1]) && isNotNull(p[2]) && isNotNull(p[3])) {
item.setId(Integer.parseInt(p[0]));
item.setBrand(p[1]);
item.setCategory(p[2]);
item.setPrice(Float.parseFloat(p[3]));
}
return item;
}
public static Items convertStringToItems(String line) {
Items item = new Items();
return convertStringToItems(item, line);
}
public static boolean isNotNull(String value) {
if (value != null && value.trim().length() > 0) {
return true;
}
return false;
}
}
<file_sep>package com.app.sg.mall.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.app.sg.mall.dto.Items;
public class AppDiscountProcess {
private Map<String, Integer> discountCategory = new HashMap<>();
private Map<String, Integer> discountBrand = new HashMap<>();
private List<Items> item = new ArrayList<>();
private Map<Integer, Float> discount = new HashMap<>();
public void getDiscountProcessed() {
this.getDiscountInitalize();
float discnt = 0;
for (Items itm : item) {
if (itm != null) {
discnt = itm.getPrice()- (itm.getPrice() * getMaxDiscount(itm.getBrand(),itm.getCategory())/100);
discount.put(itm.getId(), discnt);
}
}
}
int getMaxDiscount(String brand, String category){
brand = brand.trim();
category=category.trim();
int brnd=(this.getDiscountBrand().get(brand)==null)?0:this.getDiscountBrand().get(brand);
int cat = this.getDiscountCategory().get(category)==null?0:this.getDiscountCategory().get(category);
return Math.max(brnd, cat);
}
public void getProcessOrder(List<String> order) {
int sum;
System.out.println("Output : ");
for (String odr : order) {
sum = 0;
int[] arr = Arrays.stream(odr.split(",")).map(String::trim).mapToInt(Integer::parseInt).toArray();
for (int i = 0; i < arr.length; i++) {
sum += discount.get(arr[i]);
}
System.out.println(sum);
}
}
public Map<String, Integer> getDiscountCategory() {
return discountCategory;
}
public void setDiscountCategory(Map<String, Integer> discountCategory) {
this.discountCategory = discountCategory;
}
public Map<String, Integer> getDiscountBrand() {
return discountBrand;
}
public void setDiscountBrand(Map<String, Integer> discountBrand) {
this.discountBrand = discountBrand;
}
public List<Items> getItems() {
return item;
}
public void setItems(List<Items> item) {
this.item = item;
}
public Map<Integer, Float> getDiscount() {
return discount;
}
public void setDiscount(Map<Integer, Float> discount) {
this.discount = discount;
}
/**
* Initalize Category and Brand
*/
public void getDiscountInitalize(){
Map <String,Integer> discountcat = new HashMap<>();
discountcat.put("Casuals", 30);
discountcat.put("Jeans", 20);
discountcat.put("Dresses", 50);
discountcat.put("Footwear", 50);
setDiscountCategory(discountcat);
Map <String,Integer> discountbd = new HashMap<>();
discountbd.put("Wrangler", 10);
discountbd.put("Arrow", 20);
discountbd.put("Vero Moda", 60);
discountbd.put("Adidas", 5);
discountbd.put("Provogue", 20);
setDiscountBrand(discountbd);
}
}
<file_sep>package com.app.sg.mall.util;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.app.sg.mall.dto.Items;
public class AppUtilTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testConvertStringToItems() {
Items item = new Items();
String line = "1,Arrow,Shirts,800";
item=AppUtil.convertStringToItems(item, line);
assertEquals(item.getId(),1);
assertEquals(item.getBrand(),"Arrow");
assertEquals(item.getCategory(),"Shirts");
assertEquals(item.getPrice(),800,1.0);
}
@Test
public void testConvertStringToItemsNeg() {
Items item = new Items();
String line = "1,,Shirts,800";
item=AppUtil.convertStringToItems(item, line);
assertEquals(item.getId(),0);
assertEquals(item.getBrand(),null);
assertEquals(item.getCategory(),null);
assertEquals(item.getPrice(),0,1.0);
}
@Test
public void testIsNotNull(){
assertTrue(AppUtil.isNotNull("Sample"));
}
@Test
public void testIsNotNullval(){
assertTrue(!AppUtil.isNotNull(""));
}
}
|
d310f9d59981c77b387860039daf2188b436feb0
|
[
"Java"
] | 3
|
Java
|
sanjeevbvbit/SG
|
24a491ee6a055d8389887f528f95fe42f127bf2c
|
f174032d43d74b74ca31850c713da239888dfc05
|
refs/heads/master
|
<repo_name>lengku8e/RecyclerViewDemo<file_sep>/app/src/main/java/me/xiazdong/recyclerviewdemo/demo1/MyAdapter.java
package me.xiazdong.recyclerviewdemo.demo1;
/**
* Created by sunhailong01 on 17/12/30.
*/
public class MyAdapter {
}
|
60dccd213c2c8cfe7dcd68c0598af00af2d06be8
|
[
"Java"
] | 1
|
Java
|
lengku8e/RecyclerViewDemo
|
94487077b1090abef2879ad997a2dfc463089d5e
|
7733045d09509a24eb0c25c8c6f117daa5707cd3
|
refs/heads/master
|
<file_sep><?php /* Smarty version Smarty-3.1.16, created on 2014-02-24 14:23:27
compiled from ".\templates\novo.tpl" */ ?>
<?php /*%%SmartyHeaderCode:288805307ef3344b2c0-17163682%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'3a3dfb55807b05528e70acb0c56e21847a0df378' =>
array (
0 => '.\\templates\\novo.tpl',
1 => 1393248183,
2 => 'file',
),
),
'nocache_hash' => '288805307ef3344b2c0-17163682',
'function' =>
array (
),
'version' => 'Smarty-3.1.16',
'unifunc' => 'content_5307ef3347a0d9_78853018',
'variables' =>
array (
'setores' => 0,
'setor' => 0,
'tipos' => 0,
'tipo' => 0,
),
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_5307ef3347a0d9_78853018')) {function content_5307ef3347a0d9_78853018($_smarty_tpl) {?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 4.01 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/reset.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/text.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/960_24_col.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.maskedinput-1.1.4.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#cpf").mask("999.999.999-99");
});
</script>
<title></title>
</head>
<body>
<div class="container_24">
<form method="POST" action="ticket.php">
<table class="chamado">
<tr>
<td>
<div class="rotulo">
Nome
</div>
<div class="valor">
<input type="text" name="nome"/>
</div>
</td>
<td>
<div class="rotulo">
CPF
</div>
<div class="valor">
<input type="text" name="cpf" id="cpf"/>
</div>
</td>
<td>
<div class="rotulo">
Número da Sala
</div>
<div class="valor">
<input type="text" name="sala"/>
</div>
</td>
</tr>
<tr>
<td>
<div class="rotulo">
Ramal
</div>
<div class="valor">
<input type="text" name="ramal"/>
</div>
</td>
<td>
<div class="rotulo">
E-mail
</div>
<div class="valor">
<input type="text" name="email"/>
</div>
</td>
<td>
<div class="rotulo">
Setor
</div>
<div class="valor">
<select name="setor">
<?php $_smarty_tpl->tpl_vars['setor'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['setor']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['setores']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['setor']->key => $_smarty_tpl->tpl_vars['setor']->value) {
$_smarty_tpl->tpl_vars['setor']->_loop = true;
?>
<option value="<?php echo $_smarty_tpl->tpl_vars['setor']->value['id'];?>
"><?php echo $_smarty_tpl->tpl_vars['setor']->value['sigla'];?>
</option>
<?php } ?>
</select>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="rotulo">
Tipo de Chamado
</div>
<div class="valor">
<select name="setor">
<?php $_smarty_tpl->tpl_vars['tipo'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['tipo']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['tipos']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['tipo']->key => $_smarty_tpl->tpl_vars['tipo']->value) {
$_smarty_tpl->tpl_vars['tipo']->_loop = true;
?>
<option value="<?php echo $_smarty_tpl->tpl_vars['tipo']->value['id'];?>
"><?php echo $_smarty_tpl->tpl_vars['tipo']->value['descricao'];?>
</option>
<?php } ?>
</select>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="rotulo">
Descrição
</div>
<div class="valor">
<textarea name="descricao" rows="10" cols="80"></textarea>
<div align="center">
<input type="submit" value="Abrir Chamado"/>
</div>
</div>
</td>
</tr>
</table>
</form>
</div>
</body>
</html><?php }} ?>
<file_sep><?php
class DbConnector {
protected $database_name;
protected $hostname;
protected $username;
protected $password;
protected $connection;
function __construct($db_hostname, $db_name, $db_user, $db_pass) {
$this->hostname = $db_hostname;
$this->database_name = $db_name;
$this->username = $db_user;
$this->password = $<PASSWORD>;
}
function createDatabase() {
return false;
}
function connect() {
return false;
}
function execSql($sql) {
return false;
}
function execScript($script) {
return false;
}
}
?><file_sep><?php /* Smarty version Smarty-3.1.16, created on 2014-02-24 14:25:18
compiled from ".\templates\chamado.tpl" */ ?>
<?php /*%%SmartyHeaderCode:90385307f168bc2ac3-44986324%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'2f8fe075a03fec0c7b57f7fd1f55b389aea7fd25' =>
array (
0 => '.\\templates\\chamado.tpl',
1 => 1393248183,
2 => 'file',
),
),
'nocache_hash' => '90385307f168bc2ac3-44986324',
'function' =>
array (
),
'version' => 'Smarty-3.1.16',
'unifunc' => 'content_5307f168c571f4_03600654',
'variables' =>
array (
'situacao' => 0,
'admin' => 0,
'opcoes' => 0,
'opcao' => 0,
'ticket' => 0,
'nome' => 0,
'cpf' => 0,
'data' => 0,
'sala' => 0,
'ramal' => 0,
'hora' => 0,
'email' => 0,
'setor' => 0,
'tipo' => 0,
'descricao' => 0,
),
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_5307f168c571f4_03600654')) {function content_5307f168c571f4_03600654($_smarty_tpl) {?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 4.01 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/reset.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/text.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/960_24_col.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
<title></title>
</head>
<body>
<div class="container_24">
<table class="chamado">
<tr>
<td colspan="3" style="text-align: center;">
<div
<?php if (mb_strtoupper($_smarty_tpl->tpl_vars['situacao']->value, 'UTF-8')=="ABERTO") {?>
class="destaque-aberto"
<?php } elseif (mb_strtoupper($_smarty_tpl->tpl_vars['situacao']->value, 'UTF-8')=="EM ATENDIMENTO") {?>
class="destaque-atendimento"
<?php } elseif (mb_strtoupper($_smarty_tpl->tpl_vars['situacao']->value, 'UTF-8')=="FECHADO") {?>
class="destaque-fechado"
<?php }?>>
<?php echo mb_strtoupper($_smarty_tpl->tpl_vars['situacao']->value, 'UTF-8');?>
</div>
</td>
</tr>
<?php if (isset($_smarty_tpl->tpl_vars['admin']->value)&&$_smarty_tpl->tpl_vars['admin']->value==true) {?>
<tr>
<td colspan="3">
<div class="rotulo">
Nova situação
</div>
<div class="valor">
<form method="POST" action="">
<select name="nova_situacao">
<?php $_smarty_tpl->tpl_vars['opcao'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['opcao']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['opcoes']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['opcao']->key => $_smarty_tpl->tpl_vars['opcao']->value) {
$_smarty_tpl->tpl_vars['opcao']->_loop = true;
?>
<option value="<?php echo $_smarty_tpl->tpl_vars['opcao']->value['id'];?>
"><?php echo $_smarty_tpl->tpl_vars['opcao']->value['nome'];?>
</option>
<?php } ?>
</select>
<input type="submit" value="Salvar"/>
</form>
</div>
</td>
</tr>
<?php }?>
<?php if (isset($_smarty_tpl->tpl_vars['ticket']->value)) {?>
<tr>
<td colspan="3" style="text-align:center;">
<div class="rotulo">Número do Ticket</div>
<div class="valor">
<?php echo mb_strtoupper($_smarty_tpl->tpl_vars['ticket']->value, 'UTF-8');?>
</div>
</td>
</tr>
<?php }?>
<tr>
<td><div class="rotulo">Nome</div><div class="valor"><?php echo $_smarty_tpl->tpl_vars['nome']->value;?>
</div></td>
<td><div class="rotulo">CPF</div><div class="valor"><?php echo $_smarty_tpl->tpl_vars['cpf']->value;?>
</div></td>
<td><div class="rotulo">Data de Abertura</div><div class="valor"><?php echo $_smarty_tpl->tpl_vars['data']->value;?>
</div></td>
</tr>
<tr>
<td><div class="rotulo">Sala</div><div class="valor"><?php echo $_smarty_tpl->tpl_vars['sala']->value;?>
</div></td>
<td><div class="rotulo">Ramal</div><div class="valor"><?php echo $_smarty_tpl->tpl_vars['ramal']->value;?>
</div></td>
<td><div class="rotulo">Hora da Abertura</div><div class="valor"><?php echo $_smarty_tpl->tpl_vars['hora']->value;?>
</div></td>
</tr>
<tr>
<td colspan="2">
<div class="rotulo">E-mail</div><div class="valor"><?php echo $_smarty_tpl->tpl_vars['email']->value;?>
</div>
</td>
<td>
<div class="rotulo">Setor</div><div class="valor"><?php echo $_smarty_tpl->tpl_vars['setor']->value;?>
</div>
</td>
</tr>
<tr>
<td colspan="3"><div class="rotulo">Tipo de Chamado</div><div class="valor"><?php echo $_smarty_tpl->tpl_vars['tipo']->value;?>
</div></td>
</tr>
<tr>
<td colspan="3"><div class="rotulo">Descrição</div><div class="valor"><?php echo $_smarty_tpl->tpl_vars['descricao']->value;?>
</div></td>
</tr>
</table>
</div>
</body>
</html>
<?php }} ?>
<file_sep><?php
require("libs/Smarty.class.php");
$smarty = new Smarty();
$setores = array(array('id' => 1, 'sigla' => 'ASCOM'),
array('id' => 2, 'sigla' => 'CGMI'),
array('id' => 3, 'sigla' => 'CGMRR'),
array('id' => 4, 'sigla' => 'COCAP'),
array('id' => 5, 'sigla' => 'CGMAB'));
$smarty->assign('setores', $setores);
$tipos = array(array('id' => 1, 'descricao' => 'Problema em equipamento'),
array('id' => 2, 'descricao' => 'Problema de software'),
array('id' => 3, 'descricao' => 'Problema de rede e conectividade'),
array('id' => 4, 'descricao' => 'Instalação de software'),
array('id' => 5, 'descricao' => 'Instalação de equipamento'));
$smarty->assign('tipos', $tipos);
$smarty->display("novo.tpl");
?><file_sep><?php
/**
* isCpfValid
*
* Esta função testa se um cpf é valido ou não.
*
* @author <NAME> <<EMAIL>>
* @version 1.0 Debugada em 26/09/2011 no PHP 5.3.8
* @param string $cpf Guarda o cpf como ele foi digitado pelo cliente
* @param array $num Guarda apenas os números do cpf
* @param boolean $isCpfValid Guarda o retorno da função
* @param int $multiplica Auxilia no Calculo dos DÃgitos verificadores
* @param int $soma Auxilia no Calculo dos DÃgitos verificadores
* @param int $resto Auxilia no Calculo dos DÃgitos verificadores
* @param int $dg DÃgito verificador
* @return boolean "true" se o cpf é válido ou "false" caso o contrário
*
*/
function isCpfValid($cpf)
{
//Etapa 1: Cria um array com apenas os digitos numéricos, isso permite receber o cpf em diferentes formatos como "000.000.000-00", "00000000000", "000 000 000 00" etc...
$j=0;
for($i=0; $i<(strlen($cpf)); $i++)
{
if(is_numeric($cpf[$i]))
{
$num[$j]=$cpf[$i];
$j++;
}
}
//Etapa 2: Conta os dÃgitos, um cpf válido possui 11 dÃgitos numéricos.
if(count($num)!=11)
{
$isCpfValid=false;
}
//Etapa 3: Combinações como 00000000000 e 22222222222 embora não sejam cpfs reais resultariam em cpfs válidos após o calculo dos dÃgitos verificares e por isso precisam ser filtradas nesta parte.
else
{
for($i=0; $i<10; $i++)
{
if ($num[0]==$i && $num[1]==$i && $num[2]==$i && $num[3]==$i && $num[4]==$i && $num[5]==$i && $num[6]==$i && $num[7]==$i && $num[8]==$i)
{
$isCpfValid=false;
break;
}
}
}
//Etapa 4: Calcula e compara o primeiro dÃgito verificador.
if(!isset($isCpfValid))
{
$j=10;
for($i=0; $i<9; $i++)
{
$multiplica[$i]=$num[$i]*$j;
$j--;
}
$soma = array_sum($multiplica);
$resto = $soma%11;
if($resto<2)
{
$dg=0;
}
else
{
$dg=11-$resto;
}
if($dg!=$num[9])
{
$isCpfValid=false;
}
}
//Etapa 5: Calcula e compara o segundo dÃgito verificador.
if(!isset($isCpfValid))
{
$j=11;
for($i=0; $i<10; $i++)
{
$multiplica[$i]=$num[$i]*$j;
$j--;
}
$soma = array_sum($multiplica);
$resto = $soma%11;
if($resto<2)
{
$dg=0;
}
else
{
$dg=11-$resto;
}
if($dg!=$num[10])
{
$isCpfValid=false;
}
else
{
$isCpfValid=true;
}
}
//Trecho usado para depurar erros.
/*
if($isCpfValid==true)
{
echo "<font color=\"GREEN\">Cpf é Válido</font>";
}
if($isCpfValid==false)
{
echo "<font color=\"RED\">Cpf Inválido</font>";
}
*/
//Etapa 6: Retorna o Resultado em um valor booleano.
return $isCpfValid;
}
?><file_sep><?php /* Smarty version Smarty-3.1.16, created on 2014-02-22 02:35:30
compiled from ".\templates\editar.tpl" */ ?>
<?php /*%%SmartyHeaderCode:318555307fe83bca148-80759797%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'913c76638d779b2bf8f41b3426332ab6e33ba528' =>
array (
0 => '.\\templates\\editar.tpl',
1 => 1393032927,
2 => 'file',
),
),
'nocache_hash' => '318555307fe83bca148-80759797',
'function' =>
array (
),
'version' => 'Smarty-3.1.16',
'unifunc' => 'content_5307fe83ceb285_54444157',
'variables' =>
array (
'data' => 0,
'hora' => 0,
'nome' => 0,
'cpf' => 0,
'sala' => 0,
'ramal' => 0,
'email' => 0,
'tipo' => 0,
'descricao' => 0,
'opcoes' => 0,
'opcao' => 0,
'id_situacao' => 0,
),
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_5307fe83ceb285_54444157')) {function content_5307fe83ceb285_54444157($_smarty_tpl) {?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 4.01 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title></title>
</head>
<body>
<form method="POST" action="">
Data de Abertura: <?php echo $_smarty_tpl->tpl_vars['data']->value;?>
<br/>
Hora: <?php echo $_smarty_tpl->tpl_vars['hora']->value;?>
<br/>
Nome: <?php echo $_smarty_tpl->tpl_vars['nome']->value;?>
<br/>
CPF: <?php echo $_smarty_tpl->tpl_vars['cpf']->value;?>
<br/>
Número da Sala: <?php echo $_smarty_tpl->tpl_vars['sala']->value;?>
<br/>
Ramal: <?php echo $_smarty_tpl->tpl_vars['ramal']->value;?>
<br/>
E-mail: <?php echo $_smarty_tpl->tpl_vars['email']->value;?>
<br/>
Tipo de chamado: <?php echo $_smarty_tpl->tpl_vars['tipo']->value;?>
<br/>
Descrição: <?php echo $_smarty_tpl->tpl_vars['descricao']->value;?>
<br/>
Situação:
<select name="situacao">
<?php $_smarty_tpl->tpl_vars['opcao'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['opcao']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['opcoes']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['opcao']->key => $_smarty_tpl->tpl_vars['opcao']->value) {
$_smarty_tpl->tpl_vars['opcao']->_loop = true;
?>
<option value="<?php echo $_smarty_tpl->tpl_vars['opcao']->value['id'];?>
"
<?php if ($_smarty_tpl->tpl_vars['opcao']->value['id']==$_smarty_tpl->tpl_vars['id_situacao']->value) {?>
selected
<?php }?>
><?php echo $_smarty_tpl->tpl_vars['opcao']->value['nome'];?>
</option>
<?php } ?>
</select><br/>
<input type="submit" value="Salvar"/>
</form>
</body>
</html><?php }} ?>
<file_sep><?php /* Smarty version Smarty-3.1.16, created on 2014-02-24 14:23:19
compiled from ".\templates\index.tpl" */ ?>
<?php /*%%SmartyHeaderCode:178325307ed55864b08-52635474%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'749422d4cfc3eb5677cf499730392b6accd4d1c7' =>
array (
0 => '.\\templates\\index.tpl',
1 => 1393248183,
2 => 'file',
),
),
'nocache_hash' => '178325307ed55864b08-52635474',
'function' =>
array (
),
'version' => 'Smarty-3.1.16',
'unifunc' => 'content_5307ed55893900_16790590',
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_5307ed55893900_16790590')) {function content_5307ed55893900_16790590($_smarty_tpl) {?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 4.01 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/reset.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/text.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/960_24_col.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
<title></title>
</head>
<body>
<div class="container_24">
<div class="grid_24">
<table class="chamado">
<tr>
<td>
<div class="rotulo">
Acompanhar chamado
</div>
<div class="valor">
<form method="POST" action="chamado.php">
<input type="text" name="ticket" style="width: 180px"/><input type="submit" value="Acompanhar Chamado"/>
</form>
</div>
</td>
</tr>
<tr>
<td>
<div class="rotulo">
Novo chamado
</div>
<div class="valor">
<form action="novo.php">
<input type="submit" value="Abrir Novo Chamado" style="width: 100%"/>
</form>
</div>
</td>
</tr>
</table>
</div>
</div>
</body>
</html><?php }} ?>
<file_sep><?php /* Smarty version Smarty-3.1.16, created on 2014-02-25 18:07:19
compiled from ".\templates\login.tpl" */ ?>
<?php /*%%SmartyHeaderCode:28998530ccb09a0f265-12439548%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'0390f83576cc40b989c12a7362afcba143967e43' =>
array (
0 => '.\\templates\\login.tpl',
1 => 1393348038,
2 => 'file',
),
),
'nocache_hash' => '28998530ccb09a0f265-12439548',
'function' =>
array (
),
'version' => 'Smarty-3.1.16',
'unifunc' => 'content_530ccb09a883e4_72291509',
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_530ccb09a883e4_72291509')) {function content_530ccb09a883e4_72291509($_smarty_tpl) {?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 4.01 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/reset.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/text.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/960_24_col.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
<title></title>
</head>
<body>
<div class="container_24">
<div class="grid_24">
<form method="POST" action="">
<table class="login">
<tr class="rotulo">
<td>Usuário</td>
</tr>
<tr class="valor">
<td>
<input type="text" name="usuario"/>
</td>
</tr>
<tr class="rotulo">
<td>Senha</td>
</tr>
<tr class="valor">
<td>
<input type="<PASSWORD>" name="<PASSWORD>"/>
<div style="text-align: center;"><input type="submit" value="Login"/></div>
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html><?php }} ?>
<file_sep><?php /* Smarty version Smarty-3.1.16, created on 2014-02-24 14:24:59
compiled from ".\templates\ticket.tpl" */ ?>
<?php /*%%SmartyHeaderCode:144385307efefd00ce9-89338971%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'5b267f344bdf5c2f5a090912643e12977d8e6987' =>
array (
0 => '.\\templates\\ticket.tpl',
1 => 1393248183,
2 => 'file',
),
),
'nocache_hash' => '144385307efefd00ce9-89338971',
'function' =>
array (
),
'version' => 'Smarty-3.1.16',
'unifunc' => 'content_5307efefd3b671_64107923',
'variables' =>
array (
'ticket' => 0,
),
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_5307efefd3b671_64107923')) {function content_5307efefd3b671_64107923($_smarty_tpl) {?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 4.01 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/reset.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/text.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/960_24_col.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
<title></title>
</head>
<body>
<div class="container_24">
<table class="chamado">
<td>
<div class="rotulo">
Mensagem
</div>
<div class="valor">
<p>O seu chamado foi aberto. Guarde o número do ticket abaixo para acompanhar o andamento do chamado.</p>
</div>
<div class="rotulo">
Número do Ticket
</div>
<div class="ticket">
<?php echo $_smarty_tpl->tpl_vars['ticket']->value;?>
</div>
</td>
</table>
</div>
</body>
</html><?php }} ?>
<file_sep><?php
require("DbConnector.class.php");
class MySqlConnector extends DbConnector {
function createDatabase() {
$this->connection = new mysqli($this->hostname,
$this->username,
$this->password);
$this->connection->query("DROP SCHEMA IF EXISTS '".$this->database_name."'");
$this->connection->query("CREATE SCHEMA IF NOT EXISTS '".$this->database_name."' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
$this->connection->query("USE '".$this->database_name."'");
}
function connect() {
$this->connection = new mysqli($this->hostname,
$this->username,
$this->password,
$this->database_name);
if(mysqli_connect_error()) {
return false;
} else {
return true;
}
}
function getLastInsertId() {
return $this->connection->insert_id;
}
function execSql($sql) {
$query_result = $this->connection->query($sql);
if($query_result === false ||
$query_result === true) {
return $query_result;
}
$rows = array();
while($array_result = $query_result->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $array_result);
}
$query_result->free();
return $rows;
}
function execScript($script) {
$lines = explode('\n', $script);
$commands = '';
foreach($lines as $line) {
$line = trim($line);
if($line && !$this->startsWith($line, '--')) {
$commands .= $line.'\n';
}
}
$commands = explode(';', $commands);
foreach($commands as $command) {
if(trim($command)) {
$this->execSql($command);
}
}
}
private function startsWith($haystack, $needle) {
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
}
?><file_sep><?php
require("libs/Smarty.class.php");
$smarty = new Smarty();
$smarty->assign("ticket", 987458105);
$smarty->display("ticket.tpl");
?><file_sep><?php
require("libs/Smarty.class.php");
$smarty = new Smarty();
$smarty->assign("nome", "<NAME>");
$smarty->assign("cpf", "123.456.789-10");
$smarty->assign("data", "01/02/2014");
$smarty->assign("hora", "14:36");
$smarty->assign("sala", 1234);
$smarty->assign("ramal", 4321);
$smarty->assign("email", "<EMAIL>");
$smarty->assign("tipo", "Instalação de software");
$smarty->assign("descricao", "Instalar AutoCAD 2014.");
$opcoes = array(
array('id' => 1, 'nome' => 'Aberto'),
array('id' => 2, 'nome' => 'Em Atendimento'),
array('id' => 3, 'nome' => 'Fechado')
);
$smarty->assign('id_situacao', 2);
$smarty->assign('opcoes', $opcoes);
$smarty->display("editar.tpl");
?><file_sep><?php
require("libs/Smarty.class.php");
$smarty = new Smarty();
if(isset($_REQUEST['ticket'])) {
$smarty->assign("ticket", $_REQUEST['ticket']);
}
$smarty->assign("nome", "<NAME>");
$smarty->assign("cpf", "123.456.789-10");
$smarty->assign("data", "01/02/2014");
$smarty->assign("hora", "14:36");
$smarty->assign("sala", 1234);
$smarty->assign("ramal", 4321);
$smarty->assign("email", "<EMAIL>");
$smarty->assign("setor", "CGMRR");
$smarty->assign("tipo", "Instalação de software");
$smarty->assign("descricao", nl2br("The revival of Korean Brood War seemingly cannot be stopped. Arguably it was never dead to begin with, but this doesn’t mean the current resurgence is anything short of miraculous. Just 2 years ago, hope seemed all but gone, but then Sonic outperformed himself over and over again.
The first Sonic KOTH tournament was extremely fun, but now we might be getting a more professional and frequent league, with a more standardized format, as sponsors start trickling in. Even though no hard facts are available just yet, the start certainly looks promising. Read on for this week’s Sonic Proleague preview."));
$smarty->assign("situacao", "aberto");
$opcoes = array(array('id' => 1, 'nome' => 'Aberto'), array('id' => 2, 'nome' => 'Em atendimento'), array('id' => 3, 'nome' => 'Fechado'));
$smarty->assign("admin", true);
$smarty->assign("opcoes", $opcoes);
$smarty->display("chamado.tpl");
?><file_sep><?php
session_start();
require("libs/Smarty.class.php");
require("utils/MySqlConnector.class.php");
if(!isset($_SESSION['administrador']) || empty($_SESSION['administrador'])) {
die("Acesso negado.");
}
$db = new MySqlConnector("localhost", "suporte", "root", "");
if(!$db->connect()) {
die("Não foi possível conectar-se ao banco de dados.");
}
$chamados_abertos = $db->execSql("SELECT *
FROM chamado
WHERE chamado.id_situacao_chamado = (SELECT id FROM situacao_chamado WHERE situacao_chamado.nome LIKE 'Aberto') ORDER BY data");
$abertos = array();
foreach($chamados_abertos as $aberto) {
$setor_dados = $db->execSql("SELECT * FROM setor WHERE setor.id='".$aberto['id_setor']."'");
$tipo_dados = $db->execSql("SELECT * FROM tipo_chamado WHERE tipo_chamado.id='".$aberto['id_tipo_chamado']."'");
array_push($abertos, array('ticket' => $aberto['ticket'],
'data' => $aberto['data'],
'hora' => $aberto['hora'],
'nome' => $aberto['nome'],
'cpf' => $aberto['cpf'],
'sala' => $aberto['sala'],
'ramal' => $aberto['ramal'],
'email' => $aberto['email'],
'descricao' => $aberto['descricao'],
'tipo' => $tipo_dados[0]['nome'],
'setor' => $setor_dados[0]['sigla']));
}
$chamados_atendimentos = $db->execSql("SELECT *
FROM chamado
WHERE chamado.id_situacao_chamado = (SELECT id FROM situacao_chamado WHERE situacao_chamado.nome LIKE 'Em atendimento') ORDER BY data");
$atendimentos = array();
foreach($chamados_atendimentos as $atendimento) {
$setor_dados = $db->execSql("SELECT * FROM setor WHERE setor.id='".$atendimento['id_setor']."'");
$tipo_dados = $db->execSql("SELECT * FROM tipo_chamado WHERE tipo_chamado.id='".$atendimento['id_tipo_chamado']."'");
array_push($atendimentos, array('ticket' => $atendimento['ticket'],
'data' => $atendimento['data'],
'hora' => $atendimento['hora'],
'nome' => $atendimento['nome'],
'cpf' => $atendimento['cpf'],
'sala' => $atendimento['sala'],
'ramal' => $atendimento['ramal'],
'email' => $atendimento['email'],
'descricao' => $atendimento['descricao'],
'tipo' => $tipo_dados[0]['nome'],
'setor' => $setor_dados[0]['sigla']));
}
$chamados_fechados = $db->execSql("SELECT *
FROM chamado
WHERE chamado.id_situacao_chamado = (SELECT id FROM situacao_chamado WHERE situacao_chamado.nome LIKE 'Fechado') ORDER BY data, hora");
$fechados = array();
foreach($chamados_fechados as $fechado) {
$setor_dados = $db->execSql("SELECT * FROM setor WHERE setor.id='".$fechado['id_setor']."'");
$tipo_dados = $db->execSql("SELECT * FROM tipo_chamado WHERE tipo_chamado.id='".$fechado['id_tipo_chamado']."'");
array_push($fechados, array('ticket' => $fechado['ticket'],
'data' => $fechado['data'],
'hora' => $fechado['hora'],
'nome' => $fechado['nome'],
'cpf' => $fechado['cpf'],
'sala' => $fechado['sala'],
'ramal' => $fechado['ramal'],
'email' => $fechado['email'],
'descricao' => $fechado['descricao'],
'tipo' => $tipo_dados[0]['descricao'],
'setor' => $setor_dados[0]['sigla']));
}
$smarty = new Smarty();
$smarty->assign("abertos", $abertos);
$smarty->assign("atendimentos", $atendimentos);
$smarty->assign("fechados", $fechados);
$smarty->display("admin.tpl");
?><file_sep><?php
session_start();
require("libs/Smarty.class.php");
require("utils/MySqlConnector.class.php");
$smarty = new Smarty();
$smarty->display("login.tpl");
?><file_sep><?php /* Smarty version Smarty-3.1.16, created on 2014-02-24 22:12:28
compiled from ".\templates\admin.tpl" */ ?>
<?php /*%%SmartyHeaderCode:63455307fc85c5ddb6-67327875%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'dde4406728b78ad8acb77d025ffd08e41bf138dd' =>
array (
0 => '.\\templates\\admin.tpl',
1 => 1393276345,
2 => 'file',
),
),
'nocache_hash' => '63455307fc85c5ddb6-67327875',
'function' =>
array (
),
'version' => 'Smarty-3.1.16',
'unifunc' => 'content_5307fc85d15767_86184552',
'variables' =>
array (
'abertos' => 0,
'i' => 0,
'chamado' => 0,
'paginas_abertos' => 0,
'pagina' => 0,
'atendimentos' => 0,
'paginas_atendimento' => 0,
'paginas_fechados' => 0,
'fechados' => 0,
),
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_5307fc85d15767_86184552')) {function content_5307fc85d15767_86184552($_smarty_tpl) {?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 4.01 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="refresh" content="10">
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/reset.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/text.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/grid960/960_24_col.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/simpletabs.css" />
<script type="text/javascript" src="js/simpletabs_1.3.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("tr.par").click(function() {
window.location.href = $(this).find("a").attr("href");
});
$("tr.impar").click(function() {
window.location.href = $(this).find("a").attr("href");
});
});
</script>
<title></title>
</head>
<body>
<div class="container_24">
<div class="simpleTabs">
<ul class="simpleTabsNavigation">
<li><a href="#">Abertos</a></li>
<li><a href="#">Em Atendimento</a></li>
<li><a href="#">Fechados</a></li>
</ul>
<div class="simpleTabsContent">
<table class="admin">
<tr class="header">
<th>Data</th>
<th>Hora</th>
<th>Ticket</th>
<th>Setor</th>
<th>Tipo</th>
<th>Nome</th>
</tr>
<?php $_smarty_tpl->tpl_vars['chamado'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['chamado']->_loop = false;
$_smarty_tpl->tpl_vars['i'] = new Smarty_Variable;
$_from = $_smarty_tpl->tpl_vars['abertos']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['chamado']->key => $_smarty_tpl->tpl_vars['chamado']->value) {
$_smarty_tpl->tpl_vars['chamado']->_loop = true;
$_smarty_tpl->tpl_vars['i']->value = $_smarty_tpl->tpl_vars['chamado']->key;
?>
<tr
<?php if ($_smarty_tpl->tpl_vars['i']->value%2==0) {?>
class="par"
<?php } else { ?>
class="impar"
<?php }?>
>
<td><a href="chamado.php?ticket=<?php echo $_smarty_tpl->tpl_vars['chamado']->value['ticket'];?>
"><?php echo $_smarty_tpl->tpl_vars['chamado']->value['data'];?>
</a></td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['hora'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['ticket'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['setor'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['tipo'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['nome'];?>
</td>
</tr>
<?php } ?>
</table>
<?php if (isset($_smarty_tpl->tpl_vars['paginas_abertos']->value)) {?>
<div class="paginacao">
<?php $_smarty_tpl->tpl_vars['pagina'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['pagina']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['paginas_abertos']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['pagina']->key => $_smarty_tpl->tpl_vars['pagina']->value) {
$_smarty_tpl->tpl_vars['pagina']->_loop = true;
?>
<a href="admin.php?p=<?php echo $_smarty_tpl->tpl_vars['pagina']->value;?>
"><?php echo $_smarty_tpl->tpl_vars['pagina']->value;?>
</a>
<?php } ?>
</div>
<?php }?>
</div>
<div class="simpleTabsContent">
<table class="admin">
<tr class="header">
<th>Data</th>
<th>Hora</th>
<th>Ticket</th>
<th>Setor</th>
<th>Tipo</th>
<th>Nome</th>
</tr>
<?php $_smarty_tpl->tpl_vars['chamado'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['chamado']->_loop = false;
$_smarty_tpl->tpl_vars['i'] = new Smarty_Variable;
$_from = $_smarty_tpl->tpl_vars['atendimentos']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['chamado']->key => $_smarty_tpl->tpl_vars['chamado']->value) {
$_smarty_tpl->tpl_vars['chamado']->_loop = true;
$_smarty_tpl->tpl_vars['i']->value = $_smarty_tpl->tpl_vars['chamado']->key;
?>
<tr
<?php if ($_smarty_tpl->tpl_vars['i']->value%2==0) {?>
class="par"
<?php } else { ?>
class="impar"
<?php }?>
>
<td><a href="chamado.php?ticket=<?php echo $_smarty_tpl->tpl_vars['chamado']->value['ticket'];?>
"><?php echo $_smarty_tpl->tpl_vars['chamado']->value['data'];?>
</a></td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['hora'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['ticket'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['setor'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['tipo'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['nome'];?>
</td>
</tr>
<?php } ?>
</table>
<?php if (isset($_smarty_tpl->tpl_vars['paginas_atendimento']->value)) {?>
<div class="paginacao">
<?php $_smarty_tpl->tpl_vars['pagina'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['pagina']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['paginas_fechados']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['pagina']->key => $_smarty_tpl->tpl_vars['pagina']->value) {
$_smarty_tpl->tpl_vars['pagina']->_loop = true;
?>
<a href="admin.php?p=<?php echo $_smarty_tpl->tpl_vars['pagina']->value;?>
"><?php echo $_smarty_tpl->tpl_vars['pagina']->value;?>
</a>
<?php } ?>
</div>
<?php }?>
</div>
<div class="simpleTabsContent">
<table class="admin">
<tr class="header">
<th>Data</th>
<th>Hora</th>
<th>Ticket</th>
<th>Setor</th>
<th>Tipo</th>
<th>Nome</th>
</tr>
<?php $_smarty_tpl->tpl_vars['chamado'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['chamado']->_loop = false;
$_smarty_tpl->tpl_vars['i'] = new Smarty_Variable;
$_from = $_smarty_tpl->tpl_vars['fechados']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['chamado']->key => $_smarty_tpl->tpl_vars['chamado']->value) {
$_smarty_tpl->tpl_vars['chamado']->_loop = true;
$_smarty_tpl->tpl_vars['i']->value = $_smarty_tpl->tpl_vars['chamado']->key;
?>
<tr
<?php if ($_smarty_tpl->tpl_vars['i']->value%2==0) {?>
class="par"
<?php } else { ?>
class="impar"
<?php }?>
>
<td><a href="chamado.php?ticket=<?php echo $_smarty_tpl->tpl_vars['chamado']->value['ticket'];?>
"><?php echo $_smarty_tpl->tpl_vars['chamado']->value['data'];?>
</a></td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['hora'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['ticket'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['setor'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['tipo'];?>
</td>
<td><?php echo $_smarty_tpl->tpl_vars['chamado']->value['nome'];?>
</td>
</tr>
<?php } ?>
</table>
<?php if (isset($_smarty_tpl->tpl_vars['paginas_fechados']->value)) {?>
<div class="paginacao">
<?php $_smarty_tpl->tpl_vars['pagina'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['pagina']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['paginas_fechados']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['pagina']->key => $_smarty_tpl->tpl_vars['pagina']->value) {
$_smarty_tpl->tpl_vars['pagina']->_loop = true;
?>
<a href="admin.php?p=<?php echo $_smarty_tpl->tpl_vars['pagina']->value;?>
"><?php echo $_smarty_tpl->tpl_vars['pagina']->value;?>
</a>
<?php } ?>
</div>
<?php }?>
</div>
</div>
</div>
</body>
</html><?php }} ?>
|
b1fce5df73df409b7cde87a0839db81ceb582fae
|
[
"PHP"
] | 16
|
PHP
|
fazevedodev/suporte
|
30bc61076e26fd72752ff2eddc735405f9251904
|
fc35613f512171f2eb46da4bb737e70da2fea92b
|
refs/heads/master
|
<repo_name>Abdurrahmanm4nn/MyAndroidAppExample<file_sep>/app/src/main/java/com/example/cargallery/AstonMartinOne77.kt
package com.example.cargallery
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class AstonMartinOne77 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_aston_martin_one77)
}
}<file_sep>/app/src/main/java/com/example/cargallery/MainActivity.kt
package com.example.cargallery
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
private lateinit var rvCars: RecyclerView
private var list: ArrayList<Cars> = arrayListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rvCars = findViewById(R.id.rv_cars)
rvCars.setHasFixedSize(true)
list.addAll(CarsData.listData)
showRecyclerList()
}
private fun showRecyclerList() {
rvCars.layoutManager = LinearLayoutManager(this)
val listCarAdapter = ListCarAdapter(list)
rvCars.adapter = listCarAdapter
listCarAdapter.setOnItemClickCallback(object : ListCarAdapter.OnItemClickCallback {
override fun onItemClicked(data: Cars) {
showSelectedCars(data)
}
})
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_utama, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
setMode(item.itemId)
return super.onOptionsItemSelected(item)
}
private fun setMode(selectedMode: Int) {
when (selectedMode) {
R.id.profile -> {
val moveIntent = Intent(this@MainActivity, Profile::class.java)
startActivity(moveIntent)
}
}
}
private fun showSelectedCars(cars: Cars){
var infoIntent:Intent? = null
when(cars.name){
"Ferrari F40" -> infoIntent = Intent(this@MainActivity, FerrariF40::class.java)
"Porsche 959" -> infoIntent = Intent(this@MainActivity, Porsche959::class.java)
"<NAME> DB5" -> infoIntent = Intent(this@MainActivity, AstonMartinDb5::class.java)
"<NAME>" -> infoIntent = Intent(this@MainActivity, FerrariLaFerrari::class.java)
"<NAME>" -> infoIntent = Intent(this@MainActivity, MclarenSenna::class.java)
"<NAME> GT" -> infoIntent = Intent(this@MainActivity, PorscheCarreraGt::class.java)
"Porsche 935 Clubsport" -> infoIntent = Intent(this@MainActivity, Porsche935::class.java)
"Ferrari 488 Pista" -> infoIntent = Intent(this@MainActivity, Ferrari488Pista::class.java)
"Ferrari 812 Superfast" -> infoIntent = Intent(this@MainActivity, Ferrari812Superfast::class.java)
"<NAME> One-77" -> infoIntent = Intent(this@MainActivity, AstonMartinOne77::class.java)
}
startActivity(infoIntent)
}
}<file_sep>/app/src/main/java/com/example/cargallery/CarsData.kt
package com.example.cargallery
object CarsData {
private val carNames = arrayOf("<NAME>",
"Porsche 959",
"<NAME>5",
"<NAME>",
"<NAME>",
"<NAME> GT",
"Porsche 935 Clubsport",
"Ferrari 488 Pista",
"Ferrari 812 Superfast",
"<NAME> One-77")
private val carDetails = arrayOf("Engine : 2936cc twin-turbo 90-degree V8 engine. Peak Power : 478ps@7000rpm, Peak Torque : 577Nm@4000rpm. 0-60mph in 4.2 seconds, 0-100mph in 8.3 seconds. Top Speed : 201 mph.",
"Engine : 2849cc twin-turbo flat-6 engine. Peak Power : 450ps@6500rpm, Peak Torque : 500Nm@5000rpm. 0-60mph in 3.6 seconds, 0-100mph in 8.2 seconds. Top Speed : 198 mph.",
"Engine : 3995cc Inline-6 NA. Peak Power : 325hp@5500rpm, Peak Torque : 390Nm@4500rpm. 0-60mph in 8 Seconds. Top Speed : 145mph.",
"Detail Figure : 6262cc V12 with KERS. Peak Power : 963ps@9000rpm, Peak Torque : 900Nm@6750rpm. 0-60mph in 2.4 seconds, 0-124mph in 6.3 seconds. Top Speed : 220mph.",
"Detail Figure : 3994cc V8 twin-turbo. Peak Power : 800ps@7250rpm, Peak Torque : 800Nm@5500rpm. 0-60mph in 2.8 seconds, 0-124mph in 6.8 seconds. Top Speed : 211mph.",
"Detail Figure : 5733cc V10 NA. Peak Power : 612ps@8000rpm, Peak Torque : 590Nm@5750rpm. 0-60mph in 3.6 seconds, 0-124mph in 6.5 seconds. Top Speed : 208mph.",
"Detail Figure : 3800cc flat-6 twin-turbo. Peak Power : 700ps@7000rpm, Peak Torque : 750Nm. 0-60mph in 2.7 seconds. Top Speed : 211 mph.",
"Detail Figure : 3902cc V8 twin-turbo. Peak Power : 710ps@8000rpm, Peak Torque : 770Nm@3000rpm. 0-60mph in 2.85 seconds. 0-124mph in 7.6 seconds. Top Speed : 211mph.",
"Detail Figure : 6496cc V12 NA. Peak Power : 800ps@8500rpm, Peak Torque : 718Nm@7000rpm. 0-60mph in 2.9 seconds. Top Speed : 211mph.",
"Detail Figure : 7312cc V12 NA. Peak Power : 760ps@7500rpm, Peak Torque : 750Nm@5000rpm. 0-60mph in 3.5 seconds. Top Speed : 220mph.")
private val carImages = intArrayOf(R.drawable.ferrari_f40,
R.drawable.porsche_959,
R.drawable.aston_martin_db5,
R.drawable.ferrari_laferrari,
R.drawable.mclaren_senna,
R.drawable.porsche_carrera_gt,
R.drawable.porsche_935,
R.drawable.ferrari_488_pista,
R.drawable.ferrari_812_superfast,
R.drawable.aston_martin_one77)
val listData: ArrayList<Cars>
get() {
val list = arrayListOf<Cars>()
for (position in carNames.indices) {
val cars = Cars()
cars.name = carNames[position]
cars.detail = carDetails[position]
cars.photo = carImages[position]
list.add(cars)
}
return list
}
}<file_sep>/app/src/main/java/com/example/cargallery/Porsche959.kt
package com.example.cargallery
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class Porsche959 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_porsche959)
}
}<file_sep>/app/src/main/java/com/example/cargallery/PorscheCarreraGt.kt
package com.example.cargallery
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class PorscheCarreraGt : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_porsche_carrera_gt)
}
}<file_sep>/app/src/main/java/com/example/cargallery/ListCarAdapter.kt
package com.example.cargallery
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
class ListCarAdapter( val listCars: ArrayList<Cars>) : RecyclerView.Adapter<ListCarAdapter.ListViewHolder>(){
private lateinit var onItemClickCallback: OnItemClickCallback
fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback) {
this.onItemClickCallback = onItemClickCallback
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ListViewHolder {
val view: View = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_row_cars, viewGroup, false)
return ListViewHolder(view)
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val cars = listCars[position]
Glide.with(holder.itemView.context)
.load(cars.photo)
.apply(RequestOptions().override(55, 55))
.into(holder.imgPhoto)
holder.tvName.text = cars.name
holder.tvDetail.text = cars.detail
holder.itemView.setOnClickListener { onItemClickCallback.onItemClicked(listCars[holder.adapterPosition]) }
}
override fun getItemCount(): Int {
return listCars.size
}
inner class ListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var imgPhoto: ImageView = itemView.findViewById(R.id.img_item_photo)
var tvName: TextView = itemView.findViewById(R.id.tv_item_name)
var tvDetail: TextView = itemView.findViewById(R.id.tv_item_detail)
}
interface OnItemClickCallback {
fun onItemClicked(data: Cars)
}
}
|
81bb6959cc921a28251fbeaaef763a95ad1aa0c5
|
[
"Kotlin"
] | 6
|
Kotlin
|
Abdurrahmanm4nn/MyAndroidAppExample
|
4e9601b85a0e4474243bc254295c4b0d0ceb1538
|
1b0dec9ea3428d406230821f743c0ecbc94b2f0b
|
refs/heads/master
|
<file_sep>"""
Module that supports all the CRUD operations and statistics endpoint
"""
import json
import pandas as pd
from flask import make_response, abort
from config import db
from models import Restaurant, RestaurantSchema
from math import radians
from geopy import distance
#Function that returns all the rows /api/restaurant GET
def read_all():
#List of restaurant
res = Restaurant.query.order_by(Restaurant.name).all()
# Serialize the data
restaurant_schema = RestaurantSchema(many=True)
data = restaurant_schema.dump(res)
return data
#Function that returns a especific row by ID /api/restaurant/{id]} GET
def read_one(id):
#Get the row by id
res = Restaurant.query.filter(Restaurant.id == id).one_or_none()
#Condition if exists
if res is not None:
# Serialize the data for the response
restaurant_schema = RestaurantSchema()
data = restaurant_schema.dump(res)
return data
#If not catch an error
else:
abort(
404,
"Restaurant not found for Id: id".format(id=id),
)
#Function tha allow insert a row /api/restaurant POST
def create(restaurant):
#Setting the rows to insert
id = restaurant.get("id")
rating = restaurant.get("rating")
name = restaurant.get("name")
site = restaurant.get("site")
email = restaurant.get("email")
phone = restaurant.get("phone")
street = restaurant.get("street")
city = restaurant.get("city")
state = restaurant.get("state")
lat = restaurant.get("lat")
lng = restaurant.get("lng")
#Boolean if row already exists by ID
existing_restaurant = (
Restaurant.query.filter(Restaurant.id == id)
.one_or_none()
)
#Condition if already exists
if existing_restaurant is None:
#Create a restaurant instance using the schema
schema = RestaurantSchema()
new_restaurant = schema.load(restaurant, session=db.session)
#Insert row to the DB
db.session.add(new_restaurant)
db.session.commit()
#Serialize and return the newly created row
data = schema.dump(new_restaurant)
return data, 201
#If not exists catch an error
else:
abort(
409,
"Restaurant {id} already exists".format(
id=id
),
)
#Function that update a row by ID /api/restaurant/{id} PUT
def update(id, restaurant):
#Get the row requested from the db
update_restaurant = Restaurant.query.filter(
Restaurant.id == id
).one_or_none()
#Setting the rows to update
rating=restaurant.get("rating")
name=restaurant.get("name")
site=restaurant.get("site")
email=restaurant.get("email")
phone=restaurant.get("phone")
street=restaurant.get("street")
city=restaurant.get("city")
state=restaurant.get("state")
lat=restaurant.get("lat")
lng=restaurant.get("lng")
#Boolean if row already exists by ID
existing_restaurant = (
Restaurant.query.filter(Restaurant.id == id)
.one_or_none()
)
#If not exists catch an error
if existing_restaurant is None:
abort(
404,
"Restaurant not found for Id: {id}".format(id=id),
)
#If exists and check if already exists in DB
elif (
existing_restaurant is not None and existing_restaurant.name == name
):
abort(
409,
"Restaurant {name} exists already".format(
name=name
),
)
#Otherwise update the row
else:
#Create a restaurant instance using the schema
schema = RestaurantSchema()
update = schema.load(restaurant, session=db.session)
#Set the id to the row that we want to update
update.id = update_restaurant.id
#Merge the new object into the old and commit it to the db
db.session.merge(update)
db.session.commit()
#Return updated row
data = schema.dump(update_restaurant)
return data, 200
#Function that delete a row by ID /api/restaurant/{id} DELETE
def delete(id):
#Get the row requested
res = Restaurant.query.filter(Restaurant.id == id).one_or_none()
#Condition if row exists
if res is not None:
db.session.delete(res)
db.session.commit()
return make_response(
"Restaurant {id} deleted".format(id=id), 200
)
#If not exists catch an error
else:
abort(
404,
"Restaurant not found for Id: {id}".format(id=id),
)
#Function that calculate the rows in input coordenates returning Count, Average and Standard Deviation /api/restaurant/statistics PUT
def statistics(coordenates):
#Intitialize variables
dictFinal = {}
final_data= []
#Get all rows
res = Restaurant.query.order_by(Restaurant.name).all()
#Serialize the data for the response
restaurant_schema = RestaurantSchema(many=True)
data = restaurant_schema.dump(res)
#Convert result into Dataframe
datos = pd.DataFrame(data)
#Setting variables
lat1 = float(coordenates["latitude"])
lng1 = float(coordenates["longitude"])
#Convert variables into radians
lat1, lng1 = map(radians, [lat1, lng1])
#Iterate over all rows
for x,y in datos.iterrows():
#Setting variables of corresponding row
lat2 = radians(y['lat'])
lng2 = radians(y['lng'])
#Create tuples with values of the corresponding row
center_point_tuple = tuple([lat1, lng1])
test_point_tuple = tuple([lat2, lng2])
#Check distance between center and coordenates of the previous row
dis = distance.distance(center_point_tuple, test_point_tuple).meters
#Validate if distance is less or equal from the radius
if dis <= int(coordenates["radius"]):
final_data.append(y)
#Create dataframe with records that meet the condition
df = pd.DataFrame(final_data)
#Create a dictionary with the final values (Count, Average and Standard Deviation) to return
dictFinal['count'] = str(df['name'].count())
dictFinal['avg'] = str(df['rating'].mean())
dictFinal['std'] = str(df['rating'].std())
json_data = json.dumps(dictFinal)
return json_data, 200
<file_sep>import os
import pandas as pd
from config import db
from models import Restaurant
#CSV to load into DB restaurant into table restaurant
RESTAURANT = pd.read_csv('https://recruiting-datasets.s3.us-east-2.amazonaws.com/restaurantes.csv', header=0)
#Delete DB if exists
if os.path.exists("restaurant.db"):
os.remove("restaurant.db")
#Create restaurant
db.create_all()
#Iterate over the file and populate the database
for key,res in RESTAURANT.iterrows():
r = Restaurant(id=res["id"], rating=res["rating"], name=res["name"], site=res["site"], email=res["email"],
phone=res["phone"], street=res["street"], city=res["city"], state=res["state"], lat=res["lat"],
lng=res["lng"])
db.session.add(r)
db.session.commit()
<file_sep>import os
import connexion
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
basedir = os.path.abspath(os.path.dirname(__file__))
# Application Instance
connex_app = connexion.App(__name__, specification_dir=basedir)
# Flask APP instance
app = connex_app.app
# Sqlite URL
sqlite_url = "sqlite:///" + os.path.join(basedir, "restaurant.db")
# Setting
app.config["SQLALCHEMY_ECHO"] = True
app.config["SQLALCHEMY_DATABASE_URI"] = sqlite_url
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
# SqlAlchemy db instance
db = SQLAlchemy(app)
# Initialize Marshmallow
ma = Marshmallow(app)<file_sep>from flask import render_template
import config
#Application instance
connex_app = config.connex_app
#swagger.yml file to configure the endpoints
connex_app.add_api("swagger.yml")
#Create a URL route
@connex_app.route("/")
def home():
return render_template("home.html")
if __name__ == "__main__":
connex_app.run(debug=True)<file_sep>from config import db, ma
#Create Restaurant Class
class Restaurant(db.Model):
__tablename__ = "restaurant"
id = db.Column(db.TEXT, primary_key=True)
rating = db.Column(db.INTEGER)
name = db.Column(db.TEXT)
site = db.Column(db.TEXT)
email = db.Column(db.TEXT)
phone = db.Column(db.TEXT)
street = db.Column(db.TEXT)
city = db.Column(db.TEXT)
state = db.Column(db.TEXT)
lat = db.Column(db.REAL)
lng = db.Column(db.REAL)
#Create Restaurant Schema
class RestaurantSchema(ma.ModelSchema):
class Meta:
model = Restaurant
sqla_session = db.session
|
9ab863ac9b396854acd3b6be2f69edd6b42741ee
|
[
"Python"
] | 5
|
Python
|
Oscar210695/intelimetrica_exam
|
7ba353ca8c30b7c39db5e20a699929e7d3bb77ff
|
ee217c1373dc57b36380a4358cb8d18a5efd5d90
|
refs/heads/master
|
<file_sep>#ifndef CONSOLE_HH
#define CONSOLE_HH
#include <list>
class message {
public:
message(char *text, unsigned int ttl);
~message();
public:
char *_text;
unsigned int _ttl;
};
message::message(char *text, unsigned int ttl):
_text(text),
_ttl(ttl)
{
}
message::~message()
{
delete[] _text;
}
typedef std::list<message *> message_list;
static message_list messages;
static inline void
console_printf(unsigned int ttl, const char *fmt, ...)
{
va_list ap;
char *text;
va_start(ap, fmt);
vasprintf(&text, fmt, ap);
va_end(ap);
messages.push_back(new message(text, ttl));
}
static void
draw_string(unsigned int x, unsigned int y, const char *str);
static inline void
console_draw(void)
{
unsigned int m_y = 1;
for (message_list::iterator i = messages.begin(),
end = messages.end(); i != end; ++i)
{
message* m = *i;
draw_string(1, m_y++, m->_text);
}
if (messages.size()) {
message* m = messages.front();
if (--m->_ttl == 0) {
messages.pop_front();
delete m;
}
}
}
#endif
<file_sep>#ifndef EXPLOSION_HH
#define EXPLOSION_HH
class explosion: public object {
public:
explosion(cpVect p, cpVect v);
virtual ~explosion();
public:
cpVect position();
cpVect velocity();
void draw();
void add_to_space(cpSpace *s);
void remove_from_space(cpSpace *s);
public:
unsigned int _switch_frame;
unsigned int _frame;
cpBody *_body;
cpShape *_shape;
};
explosion::explosion(cpVect p, cpVect v):
_switch_frame(0),
_frame(0)
{
_body = cpBodyNew(1, 10);
_body->p = p;
_body->v = v;
_shape = cpCircleShapeNew(_body, 16, cpvzero);
_shape->data = this;
_shape->collision_type = COLLISION_TYPE_EXPLOSION;
_shape->group = COLLISION_GROUP_EXPLOSION;
_shape->e = 0;
_shape->u = 0.5;
}
explosion::~explosion()
{
cpBodyDestroy(_body);
cpShapeDestroy(_shape);
}
cpVect
explosion::position()
{
return _body->p;
}
cpVect
explosion::velocity()
{
return _body->v;
}
void
explosion::draw()
{
draw_sprite(explosion_texture[_frame], _body->p.x, _body->p.y, 0);
if (++_switch_frame == CONFIG_FPS / 10) {
_switch_frame = 0;
if (++_frame == 6)
removed_objects.insert(this);
}
}
void
explosion::add_to_space(cpSpace *s)
{
cpSpaceAddBody(s, _body);
cpSpaceAddShape(s, _shape);
}
void
explosion::remove_from_space(cpSpace *s)
{
cpSpaceRemoveShape(s, _shape);
cpSpaceRemoveBody(s, _body);
}
#endif
<file_sep>#ifndef SPACEINV_ALIEN_HH
#define SPACEINV_ALIEN_HH
class spaceinv_alien: public object {
public:
spaceinv_alien(unsigned int nr_frames, texture** textures);
virtual ~spaceinv_alien();
public:
cpVect position();
cpVect velocity();
void draw();
void add_to_space(cpSpace *s);
void remove_from_space(cpSpace *s);
public:
unsigned int _nr_frames;
texture **_textures;
unsigned int _switch_frame;
unsigned int _frame;
cpBody *_body;
cpShape *_shape;
};
spaceinv_alien::spaceinv_alien(unsigned int nr_frames, texture **textures):
_nr_frames(nr_frames),
_textures(textures),
_switch_frame(0),
_frame(0)
{
_body = cpBodyNew(10, INFINITY);
_shape = cpCircleShapeNew(_body, cpvlength(cpv(4, 4)), cpvzero);
_shape->data = this;
_shape->collision_type = COLLISION_TYPE_SHIP;
_shape->e = 0;
_shape->u = 0.5;
}
spaceinv_alien::~spaceinv_alien()
{
cpBodyDestroy(_body);
cpShapeDestroy(_shape);
}
cpVect
spaceinv_alien::position()
{
return _body->p;
}
cpVect
spaceinv_alien::velocity()
{
return _body->v;
}
void
spaceinv_alien::draw()
{
draw_sprite(_textures[_frame], _body->p.x, _body->p.y, 0);
if (++_switch_frame == CONFIG_FPS / 2) {
_switch_frame = 0;
if (++_frame == _nr_frames)
_frame = 0;
}
}
void
spaceinv_alien::add_to_space(cpSpace *s)
{
cpSpaceAddBody(s, _body);
cpSpaceAddShape(s, _shape);
}
void
spaceinv_alien::remove_from_space(cpSpace *s)
{
cpSpaceRemoveShape(s, _shape);
cpSpaceRemoveBody(s, _body);
}
#endif
<file_sep>#ifndef BULLET_HH
#define BULLET_HH
class bullet: public object {
public:
bullet(texture *texture, unsigned int ttl);
virtual ~bullet();
public:
cpVect position();
cpVect velocity();
void draw();
void add_to_space(cpSpace *s);
void remove_from_space(cpSpace *s);
public:
texture *_texture;
unsigned int _ttl;
cpBody *_body;
cpShape *_shape;
};
bullet::bullet(texture *texture, unsigned int ttl):
_texture(texture),
_ttl(ttl)
{
_body = cpBodyNew(1, 10);
_shape = cpCircleShapeNew(_body, texture->_width / 2., cpvzero);
_shape->data = this;
_shape->collision_type = COLLISION_TYPE_BULLET;
_shape->e = 0;
_shape->u = 0.5;
}
bullet::~bullet()
{
cpBodyDestroy(_body);
cpShapeDestroy(_shape);
}
cpVect
bullet::position()
{
return _body->p;
}
cpVect
bullet::velocity()
{
return _body->v;
}
void
bullet::draw()
{
draw_sprite(_texture, _body->p.x, _body->p.y,
360 * cpvtoangle(_body->rot) / M_PI / 2 + 90);
if (--_ttl == 0)
removed_objects.insert(this);
}
void
bullet::add_to_space(cpSpace *s)
{
cpSpaceAddBody(s, _body);
cpSpaceAddShape(s, _shape);
}
void
bullet::remove_from_space(cpSpace *s)
{
cpSpaceRemoveShape(s, _shape);
cpSpaceRemoveBody(s, _body);
}
#endif
<file_sep>#ifndef MOTHERSHIP_HH
#define MOTHERSHIP_HH
class mothership: public object {
public:
mothership();
virtual ~mothership();
public:
cpVect position();
cpVect velocity();
void draw();
void add_to_space(cpSpace *s);
void remove_from_space(cpSpace *s);
public:
cpBody *_body;
cpShape *_shape[2];
};
mothership::mothership()
{
_body = cpBodyNew(10, INFINITY);
_shape[0] = cpCircleShapeNew(_body, 4, cpv(-4, 0));
_shape[0]->data = this;
_shape[0]->collision_type = COLLISION_TYPE_SHIP;
_shape[0]->e = 0;
_shape[0]->u = 0.5;
_shape[1] = cpCircleShapeNew(_body, 4, cpv(4, 0));
_shape[1]->data = this;
_shape[1]->collision_type = COLLISION_TYPE_SHIP;
_shape[1]->e = 0;
_shape[1]->u = 0.5;
}
mothership::~mothership()
{
cpBodyDestroy(_body);
cpShapeDestroy(_shape[0]);
cpShapeDestroy(_shape[1]);
}
cpVect
mothership::position()
{
return _body->p;
}
cpVect
mothership::velocity()
{
return _body->v;
}
void
mothership::draw()
{
draw_sprite(mothership_texture, _body->p.x, _body->p.y, 0);
// 360 * cpvtoangle(_body->rot) / M_PI / 2);
}
void
mothership::add_to_space(cpSpace *s)
{
cpSpaceAddBody(s, _body);
cpSpaceAddShape(s, _shape[0]);
cpSpaceAddShape(s, _shape[1]);
}
void
mothership::remove_from_space(cpSpace *s)
{
cpSpaceRemoveShape(s, _shape[0]);
cpSpaceRemoveShape(s, _shape[1]);
cpSpaceRemoveBody(s, _body);
}
#endif
<file_sep>#ifndef CAPTURE_HH
#define CAPTURE_HH
extern "C" {
#include <png.h>
}
#if CONFIG_CAPTURE
static void
capture()
{
static const unsigned int width = CONFIG_WINDOW_WIDTH;
static const unsigned int height = CONFIG_WINDOW_HEIGHT;
static unsigned int frame = 0;
++frame;
if (CONFIG_CAPTURE_FRAMES && frame == CONFIG_CAPTURE_FRAMES)
exit(0);
printf("\e[Lframe %d\r", frame);
fflush(stdout);
static unsigned short capture[width * height * 3];
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_SHORT, capture);
static char fn[32];
snprintf(fn, sizeof(fn), "png/%04d.png", frame - 1);
FILE *fp = fopen(fn, "wb");
if(!fp) {
fprintf(stderr, "error: fopen\n");
exit(1);
}
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
NULL, NULL, NULL);
if(!png_ptr) {
fprintf(stderr, "error: png_create_write_struct\n");
exit(1);
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if(!info_ptr) {
fprintf(stderr, "error: png_create_info_struct\n");
exit(1);
}
png_init_io(png_ptr, fp);
png_set_filter(png_ptr, 0, PNG_FILTER_NONE);
png_set_IHDR(png_ptr, info_ptr, width, height, 16, PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_bytep rows[height];
for(unsigned int i = 0; i < height; i++)
rows[i] = (png_bytep) &capture[(height - i - 1) * width * 3];
png_set_rows(png_ptr, info_ptr, rows);
png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
}
#else
static void
capture()
{
}
#endif
#endif
<file_sep>#ifndef SHIP_HH
#define SHIP_HH
class ship: public object {
public:
ship();
virtual ~ship();
public:
cpVect position();
cpVect velocity();
void draw();
void add_to_space(cpSpace *s);
void remove_from_space(cpSpace *s);
public:
cpBody *_body;
cpShape *_shape;
};
ship::ship()
{
_body = cpBodyNew(10, INFINITY);
_shape = cpCircleShapeNew(_body, 6, cpvzero);
_shape->data = this;
_shape->collision_type = COLLISION_TYPE_SHIP;
_shape->e = 0;
_shape->u = 0.5;
}
ship::~ship()
{
cpBodyDestroy(_body);
cpShapeDestroy(_shape);
}
cpVect
ship::position()
{
return _body->p;
}
cpVect
ship::velocity()
{
return _body->v;
}
void
ship::draw()
{
cpFloat a = cpvtoangle(_body->rot) + M_PI;
unsigned int x = round(4 * 6 * a / M_PI / 2);
draw_sprite(galaga1_texture[x % 6], _body->p.x, _body->p.y,
90. * (x / 6));
}
void
ship::add_to_space(cpSpace *s)
{
cpSpaceAddBody(s, _body);
cpSpaceAddShape(s, _shape);
}
void
ship::remove_from_space(cpSpace *s)
{
cpSpaceRemoveShape(s, _shape);
cpSpaceRemoveBody(s, _body);
}
#endif
<file_sep>extern "C" {
#include <stdint.h>
}
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <set>
#include <vector>
extern "C" {
#include <SDL.h>
#include <SDL_opengl.h>
#include <chipmunk.h>
#include <png.h>
}
#define CONFIG_DEBUG_HALFSIZE 0
#define CONFIG_DEBUG_DRAW_SPRITE_OUTLINE 0
#define CONFIG_FPS 60
#define CONFIG_PHYSICS_STEP_SIZE 1e-1
#define CONFIG_CAPTURE 0
#define CONFIG_CAPTURE_FRAMES 0
/* Size of the window */
#define CONFIG_WINDOW_WIDTH 1024
#define CONFIG_WINDOW_HEIGHT 768
/* Size of the game screen */
#define CONFIG_SCREEN_WIDTH 128
#define CONFIG_SCREEN_HEIGHT 128
#define CONFIG_LOG_DEFAULT_TTL (4 * CONFIG_FPS)
/* Choice: */
#define CONFIG_CONTROL CONFIG_CONTROL_POLAR
#define CONFIG_CONTROL_CARTESIAN 0
#define CONFIG_CONTROL_POLAR 1
#define CONFIG_CONTROL_CARTESIAN_FORCE 30
#define CONFIG_CONTROL_POLAR_TORQUE (M_PI / 4.)
#define CONFIG_CONTROL_POLAR_FORCE 250
#define CONFIG_BULLET_LIFETIME 30
#include "capture.hh"
#include "console.hh"
#include "texture.hh"
enum collision_type {
COLLISION_TYPE_NONE,
COLLISION_TYPE_SHIP,
COLLISION_TYPE_BULLET,
COLLISION_TYPE_EXPLOSION,
};
enum collision_group {
COLLISION_GROUP_NONE,
/* Shapes in the same group do not generate collisions */
COLLISION_GROUP_EXPLOSION,
};
static cpSpace *space;
static texture* font_texture;
static texture* starfield_texture[2];
static texture* mothership_texture;
static texture* galaga1_texture[6];
static texture* spaceinv_alien1_texture[2];
static texture* spaceinv_alien2_texture[2];
static texture* spaceinv_alien3_texture[2];
static texture* galaga_bullet_texture;
static texture* spaceinv_bullet1_texture;
static texture* explosion_texture[5];
class object {
public:
object();
virtual ~object();
public:
virtual cpVect position() = 0;
virtual cpVect velocity() = 0;
virtual void draw();
virtual void add_to_space(cpSpace *s);
virtual void remove_from_space(cpSpace *s);
};
object::object()
{
}
object::~object()
{
}
void
object::draw()
{
}
void
object::add_to_space(cpSpace *s)
{
}
void
object::remove_from_space(cpSpace *s)
{
}
static void
draw_sprite(texture *tex, double x, double y, double rot)
{
glPushMatrix();
/* Set up the new (local) coordinate system so that the coordinate
* (-1, -1) refers to the upper-left corner of the texture and
* (1, 1) refers to the lower-right corner. */
//glTranslatef(trunc(x), trunc(y), 0);
glTranslatef(x, y, 0);
glRotatef(rot, 0, 0, 1);
glScalef(tex->_width / 2., tex->_height / 2., 1);
tex->bind();
glColor4f(1, 1, 1, 1);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f(-1, -1);
glTexCoord2f(1, 0);
glVertex2f(1, -1);
glTexCoord2f(1, 1);
glVertex2f(1, 1);
glTexCoord2f(0, 1);
glVertex2f(-1, 1);
glEnd();
#if CONFIG_DEBUG_DRAW_SPRITE_OUTLINE
glBindTexture(GL_TEXTURE_2D, 0);
glBegin(GL_LINES);
glVertex2f(-1, -1);
glVertex2f(1, -1);
glVertex2f(1, -1);
glVertex2f(1, 1);
glVertex2f(1, 1);
glVertex2f(-1, 1);
glVertex2f(-1, 1);
glVertex2f(-1, -1);
glEnd();
#endif
glPopMatrix();
}
typedef std::set<object*> object_set;
static object_set objects;
static object_set removed_objects;
static object_set exploded_objects;
/* These are not proper header files: */
#include "bullet.hh"
#include "explosion.hh"
#include "mothership.hh"
#include "ship.hh"
#include "spaceinv_alien.hh"
static void
add_object(object* o)
{
objects.insert(o);
o->add_to_space(space);
}
static void
remove_object(object* o)
{
objects.erase(o);
o->remove_from_space(space);
}
enum bullet_type {
BULLET_TYPE_GALAGA,
BULLET_TYPE_SPACEINV,
NR_BULLET_TYPES,
};
static texture *const *bullet_textures[] = {
&galaga_bullet_texture,
&spaceinv_bullet1_texture,
};
static ship *player;
static bullet_type player_bullet_type = BULLET_TYPE_SPACEINV;
#if CONFIG_CONTROL == CONFIG_CONTROL_POLAR
static bool player_thrust;
static bool player_turn_left;
static bool player_turn_right;
#endif
static cpVect camera_p = cpvzero;
static cpVect camera_v = cpvzero;
static void camera_update(void)
{
cpVect p = player->_body->p;
cpVect v = player->_body->v;
/* Friction */
camera_v = cpvmult(camera_v, 0.9);
/* Spring force */
camera_v = cpvadd(camera_v, cpvmult(cpvsub(p, camera_p), 1e-3));
/* Damping */
camera_v = cpvadd(camera_v, cpvmult(cpvsub(v, camera_v), 1e-2));
camera_p = cpvadd(camera_p, camera_v);
}
static int
ship_bullet_collision(cpShape *shape_a, cpShape *shape_b,
cpContact *contacts, int nr_contacts, cpFloat normal_coef, void *data)
{
object *s = (object *) shape_a->data;
object *b = (object *) shape_b->data;
exploded_objects.insert(s);
removed_objects.insert(b);
console_printf(CONFIG_FPS, "Boom! at (%.2f %.2f)", s->position().x, s->position().y);
return 1;
}
static int
ship_ship_collision(cpShape *shape_a, cpShape *shape_b,
cpContact *contacts, int nr_contacts, cpFloat normal_coef, void *data)
{
object *a = (object *) shape_a->data;
object *b = (object *) shape_b->data;
exploded_objects.insert(a);
exploded_objects.insert(b);
return 1;
}
static int
ship_explosion_collision(cpShape *shape_a, cpShape *shape_b,
cpContact *contacts, int nr_contacts, cpFloat normal_coef, void *data)
{
object *a = (object *) shape_a->data;
object *b = (object *) shape_b->data;
exploded_objects.insert(a);
return 1;
}
static int
bullet_explosion_collision(cpShape *shape_a, cpShape *shape_b,
cpContact *contacts, int nr_contacts, cpFloat normal_coef, void *data)
{
return 0;
}
static cpVect
random_enemy_position()
{
while (1) {
double x = rand() % 1024 - 512;
double y = rand() % 1024 - 512;
if (cpvlength(cpv(x, y)) > 32)
return cpv(x, y);
}
}
static void
init_enemies()
{
for (unsigned int i = 0; i < 20; ++i) {
mothership *m = new mothership();
m->_body->p = random_enemy_position();
add_object(m);
}
for (unsigned int i = 0; i < 10; ++i) {
spaceinv_alien *a = new spaceinv_alien(2,
spaceinv_alien1_texture);
a->_body->p = random_enemy_position();
add_object(a);
}
for (unsigned int i = 0; i < 10; ++i) {
spaceinv_alien *a = new spaceinv_alien(2,
spaceinv_alien2_texture);
a->_body->p = random_enemy_position();
add_object(a);
}
for (unsigned int i = 0; i < 10; ++i) {
spaceinv_alien *a = new spaceinv_alien(2,
spaceinv_alien3_texture);
a->_body->p = random_enemy_position();
add_object(a);
}
}
static void
init()
{
cpInitChipmunk();
srand(time(NULL));
space = cpSpaceNew();
space->elasticIterations = 10;
space->gravity = cpvzero;
cpSpaceAddCollisionPairFunc(space,
COLLISION_TYPE_SHIP, COLLISION_TYPE_BULLET,
&ship_bullet_collision, NULL);
cpSpaceAddCollisionPairFunc(space,
COLLISION_TYPE_SHIP, COLLISION_TYPE_SHIP,
&ship_ship_collision, NULL);
cpSpaceAddCollisionPairFunc(space,
COLLISION_TYPE_SHIP, COLLISION_TYPE_EXPLOSION,
&ship_explosion_collision, NULL);
cpSpaceAddCollisionPairFunc(space,
COLLISION_TYPE_BULLET, COLLISION_TYPE_EXPLOSION,
&bullet_explosion_collision, NULL);
font_texture = texture::get_png("cp850-8x8.png");
starfield_texture[0] = texture::get_png("starfield-1.png");
starfield_texture[1] = texture::get_png("starfield-2.png");
mothership_texture = texture::get_png("spaceinv-mothership.png");
galaga1_texture[0] = texture::get_png("galaga-1-1.png");
galaga1_texture[1] = texture::get_png("galaga-1-2.png");
galaga1_texture[2] = texture::get_png("galaga-1-3.png");
galaga1_texture[3] = texture::get_png("galaga-1-4.png");
galaga1_texture[4] = texture::get_png("galaga-1-5.png");
galaga1_texture[5] = texture::get_png("galaga-1-6.png");
spaceinv_alien1_texture[0] = texture::get_png("spaceinv-alien1-1.png");
spaceinv_alien1_texture[1] = texture::get_png("spaceinv-alien1-2.png");
spaceinv_alien2_texture[0] = texture::get_png("spaceinv-alien2-1.png");
spaceinv_alien2_texture[1] = texture::get_png("spaceinv-alien2-2.png");
spaceinv_alien3_texture[0] = texture::get_png("spaceinv-alien3-1.png");
spaceinv_alien3_texture[1] = texture::get_png("spaceinv-alien3-2.png");
galaga_bullet_texture = texture::get_png("galaga-bullet.png");
spaceinv_bullet1_texture = texture::get_png("spaceinv-bullet-1.png");
explosion_texture[0] = texture::get_png("galaga-explosion-2-1.png");
explosion_texture[1] = texture::get_png("galaga-explosion-2-2.png");
explosion_texture[2] = texture::get_png("galaga-explosion-2-3.png");
explosion_texture[3] = texture::get_png("galaga-explosion-2-4.png");
explosion_texture[4] = texture::get_png("galaga-explosion-2-5.png");
player = new ship();
add_object(player);
init_enemies();
console_printf(5 * CONFIG_FPS, "-- Welcome! --");
}
static void
deinit()
{
}
static double aspect;
static void
resize(int width, int height)
{
if(width == 0 || height == 0)
return;
aspect = 1.0 * height / width;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, width, height);
}
static void draw_starfield(texture *tex, double scale)
{
/* XXX: Calculate starfield based on screen and texture size. */
double o_x = camera_p.x / scale;
double o_y = camera_p.y / scale;
int d_x = (int) trunc(o_x / 64.) - 1;
int d_y = (int) trunc(o_y / 64.) - 1;
for (int y = 0; y < 6; ++y) {
for (int x = 0; x < 6; ++x) {
draw_sprite(tex,
-o_x + 64 * (d_x + x) - 32 - 64,
-o_y + 64 * (d_y + y) - 32 - 64, 0);
}
}
}
static void
draw_char(unsigned int x, unsigned int y, char ch)
{
unsigned int w = font_texture->_width / 8;
unsigned int h = font_texture->_height / 8;
unsigned int fx = (ch % w);
unsigned int fy = ch / w;
double fx1 = 1. * fx / w;
double fy1 = 1. * fy / h;
double fx2 = 1. * (fx + 1) / w;
double fy2 = 1. * (fy + 1) / h;
glPushMatrix();
glTranslatef(x, y, 0);
font_texture->bind();
glColor4f(0, 1, 0, 0.8);
glBegin(GL_QUADS);
glTexCoord2f(fx1, fy1);
glVertex2f(0, 0);
glTexCoord2f(fx2, fy1);
glVertex2f(1, 0);
glTexCoord2f(fx2, fy2);
glVertex2f(1, 1);
glTexCoord2f(fx1, fy2);
glVertex2f(0, 1);
glEnd();
glPopMatrix();
}
static void
draw_string(unsigned int x, unsigned int y, const char *str)
{
for (unsigned int i = 0; str[i]; ++i)
draw_char(x + i, y, str[i]);
}
static void
display()
{
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluOrtho2D(-CONFIG_SCREEN_WIDTH, CONFIG_SCREEN_WIDTH,
CONFIG_SCREEN_HEIGHT * aspect, -CONFIG_SCREEN_HEIGHT * aspect);
#if CONFIG_DEBUG_HALFSIZE
glPushMatrix();
glScalef(0.5, 0.5, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glColor4f(1, 1, 1, 1);
glBegin(GL_LINES);
glVertex2f(-CONFIG_SCREEN_WIDTH, -CONFIG_SCREEN_HEIGHT);
glVertex2f(-CONFIG_SCREEN_WIDTH, CONFIG_SCREEN_HEIGHT);
glVertex2f(-CONFIG_SCREEN_WIDTH, CONFIG_SCREEN_HEIGHT);
glVertex2f( CONFIG_SCREEN_WIDTH, CONFIG_SCREEN_HEIGHT);
glVertex2f( CONFIG_SCREEN_WIDTH, CONFIG_SCREEN_HEIGHT);
glVertex2f( CONFIG_SCREEN_WIDTH, -CONFIG_SCREEN_HEIGHT);
glVertex2f( CONFIG_SCREEN_WIDTH, -CONFIG_SCREEN_HEIGHT);
glVertex2f(-CONFIG_SCREEN_WIDTH, -CONFIG_SCREEN_HEIGHT);
glEnd();
#endif
draw_starfield(starfield_texture[0], 2);
draw_starfield(starfield_texture[1], 3);
glTranslatef(-camera_p.x, -camera_p.y, 0);
for (object_set::iterator i = objects.begin(), end = objects.end();
i != end; ++i)
{
(*i)->draw();
}
#if CONFIG_DEBUG_HALFSIZE
glPopMatrix();
#endif
glLoadIdentity();
gluOrtho2D(0, 2 * CONFIG_SCREEN_WIDTH,
2 * CONFIG_SCREEN_HEIGHT * aspect, 0);
glScalef(8, 8, 1);
console_draw();
SDL_GL_SwapBuffers();
capture();
cpSpaceStep(space, CONFIG_PHYSICS_STEP_SIZE);
camera_update();
for (object_set::iterator i = removed_objects.begin(),
end = removed_objects.end();
i != end; ++i)
{
remove_object(*i);
}
removed_objects.clear();
for (object_set::iterator i = exploded_objects.begin(),
end = exploded_objects.end();
i != end; ++i)
{
object *o = *i;
add_object(new explosion(o->position(), o->velocity()));
remove_object(o);
delete o;
if (o == player) {
player = new ship();
add_object(player);
#if CONFIG_CONTROL == CONFIG_CONTROL_POLAR
player_thrust = false;
player_turn_left = false;
player_turn_right = false;
#endif
}
}
exploded_objects.clear();
#if CONFIG_CONTROL == CONFIG_CONTROL_POLAR
if (player_thrust) {
double force = 1. * CONFIG_CONTROL_POLAR_FORCE
/ CONFIG_FPS;
cpBodyApplyImpulse(player->_body,
cpvmult(player->_body->rot, force), cpvzero);
}
#endif
}
static Uint32
displayTimer(Uint32 interval, void* param)
{
SDL_Event event;
event.type = SDL_USEREVENT;
SDL_PushEvent(&event);
return interval;
}
static void
keyboard(SDL_KeyboardEvent* key)
{
switch(key->keysym.sym) {
#if CONFIG_CONTROL == CONFIG_CONTROL_CARTESIAN
case SDLK_DOWN:
cpBodyApplyForce(player->_body,
cpv(0, CONFIG_CONTROL_CARTESIAN_FORCE), cpvzero);
break;
case SDLK_UP:
cpBodyApplyForce(player->_body,
cpv(0, -CONFIG_CONTROL_CARTESIAN_FORCE), cpvzero);
break;
case SDLK_LEFT:
cpBodyApplyForce(player->_body,
cpv(-CONFIG_CONTROL_CARTESIAN_FORCE, 0), cpvzero);
break;
case SDLK_RIGHT:
cpBodyApplyForce(player->_body,
cpv(CONFIG_CONTROL_CARTESIAN_FORCE, 0), cpvzero);
break;
#endif
#if CONFIG_CONTROL == CONFIG_CONTROL_POLAR
case SDLK_DOWN:
break;
case SDLK_UP:
player_thrust = true;
break;
case SDLK_LEFT:
player->_body->w -= CONFIG_CONTROL_POLAR_TORQUE;
player_turn_left = true;
break;
case SDLK_RIGHT:
player->_body->w += CONFIG_CONTROL_POLAR_TORQUE;
player_turn_right = true;
break;
#endif
case SDLK_TAB: {
player_bullet_type = (bullet_type)
((int) player_bullet_type + 1);
if (player_bullet_type == NR_BULLET_TYPES)
player_bullet_type = (bullet_type) 0;
break;
}
case SDLK_SPACE: {
bullet *b = new bullet(*bullet_textures[player_bullet_type],
CONFIG_BULLET_LIFETIME * CONFIG_FPS);
b->_body->p = cpvadd(player->_body->p,
cpvmult(player->_body->rot, 10));
b->_body->v = cpvadd(player->_body->v,
cpvmult(player->_body->rot, 20));
cpBodySetAngle(b->_body,
cpvtoangle(player->_body->rot));
add_object(b);
break;
}
case SDLK_F1:
init_enemies();
break;
case SDLK_ESCAPE: {
SDL_Event event;
event.type = SDL_QUIT;
SDL_PushEvent(&event);
}
break;
default:
printf("key %d\n", key->keysym.sym);
}
}
static void
keyboardUp(SDL_KeyboardEvent* key)
{
switch(key->keysym.sym) {
#if CONFIG_CONTROL == CONFIG_CONTROL_CARTESIAN
case SDLK_DOWN:
cpBodyApplyForce(player->_body,
cpv(0, -CONFIG_CONTROL_CARTESIAN_FORCE), cpvzero);
break;
case SDLK_UP:
cpBodyApplyForce(player->_body,
cpv(0, CONFIG_CONTROL_CARTESIAN_FORCE), cpvzero);
break;
case SDLK_LEFT:
cpBodyApplyForce(player->_body,
cpv(CONFIG_CONTROL_CARTESIAN_FORCE, 0), cpvzero);
break;
case SDLK_RIGHT:
cpBodyApplyForce(player->_body,
cpv(-CONFIG_CONTROL_CARTESIAN_FORCE, 0), cpvzero);
break;
#endif
#if CONFIG_CONTROL == CONFIG_CONTROL_POLAR
case SDLK_DOWN:
break;
case SDLK_UP:
player_thrust = false;
break;
case SDLK_LEFT:
if (player_turn_left)
player->_body->w += CONFIG_CONTROL_POLAR_TORQUE;
player_turn_left = false;
break;
case SDLK_RIGHT:
if (player_turn_right)
player->_body->w -= CONFIG_CONTROL_POLAR_TORQUE;
player_turn_right = false;
break;
#endif
default:
break;
}
}
int
main(int argc, char *argv[])
{
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1) {
fprintf(stderr, "error: %s\n", SDL_GetError());
exit(1);
}
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_Surface* surface = SDL_SetVideoMode(CONFIG_WINDOW_WIDTH,
CONFIG_WINDOW_HEIGHT, 0, SDL_OPENGL);
if (!surface) {
fprintf(stderr, "error: %s\n", SDL_GetError());
exit(1);
}
init();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
glClearColor(0, 0, 0, 1);
resize(CONFIG_WINDOW_WIDTH, CONFIG_WINDOW_HEIGHT);
#if CONFIG_CAPTURE == 0
SDL_TimerID display_timer = SDL_AddTimer(1000 / CONFIG_FPS,
&displayTimer, NULL);
if (!display_timer) {
fprintf(stderr, "error: %s\n", SDL_GetError());
exit(1);
}
#endif
bool running = true;
while (running) {
SDL_Event event;
#if CONFIG_CAPTURE
display();
while (SDL_PollEvent(&event))
#else
SDL_WaitEvent(&event);
#endif
switch (event.type) {
case SDL_USEREVENT:
display();
break;
case SDL_KEYDOWN:
keyboard(&event.key);
break;
case SDL_KEYUP:
keyboardUp(&event.key);
break;
case SDL_MOUSEBUTTONDOWN:
break;
case SDL_QUIT:
running = false;
break;
case SDL_VIDEORESIZE:
resize(event.resize.w, event.resize.h);
break;
}
}
deinit();
SDL_Quit();
return 0;
}
|
a9991b22132651b699a76d141c16fccb14a4e82a
|
[
"C++"
] | 8
|
C++
|
vegard/spaceinv
|
5fe7cf85b8c0a273f2870e58963a96330baa15a4
|
5aa15524122c309e161b391efe6ec534c5fdf3c0
|
refs/heads/master
|
<file_sep>import numpy as np
import matplotlib as mp
%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.examples.tutorials.mnist import input_data
import math
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
<file_sep># tensorflow-projects
Testing CNN and others in tensorflow
Development setup
=================
* Docker pre-configured with dependencies:
* INSTALLING DEPENDENCES
From the root of the repo, run the following command:
$ pip install -r requirements/requirements.txt
<file_sep>
import numpy as np
import glob
from skimage import io
import numpy.matlib
import os
def flat_pixels(imageFolderPath, ext):
"""---."""
imagePath = glob.glob(imageFolderPath + ext)
featues_path = []
for img in imagePath:
im = io.imread(img)
feat_im = im.reshape(1,im.shape[0]*im.shape[1],3)
if featues_path==[]:
featues_path = feat_im
else:
featues_path = np.vstack((featues_path, feat_im))
#print(img)
#Return flatten pixels from images of path
return featues_path
def do_labels(num_imagens, label):
"""---."""
labels_path = np.ones(num_imagens, dtype=np.int32)*label
return labels_path
def main(folderPath, ext):
"""---."""
label = -1
labels = []
features = []
for root,dirs,_ in os.walk(folderPath):
for d in dirs:
label = label+1
path = os.path.join(root,d)
features_path = flat_pixels(path+os.sep, ext)
labels_path = do_labels(len(features_path), label)
if features==[]:
features = features_path
labels = labels_path
else:
features = np.vstack((features, features_path))
labels = np.hstack((labels, labels_path))
return features, labels
if __name__ == "__main__":
features = main(folderPath='bears/train/', ext='*.jpg')
<file_sep>os
tensorflow-gpu
sklearn
scikit-learn
scikit-image
|
4f5f7704280137ea8fd416a9653612bd5881f2e8
|
[
"Markdown",
"Python",
"Text"
] | 4
|
Python
|
marcoruizrueda/tensorflow-projects
|
0596322f13728ba97f13aa4502033545333392d7
|
6bc3cc80654b84ebd3fa2e862667ad466f1f6f57
|
refs/heads/master
|
<file_sep>#!/bin/bash
echo "Loading all files into gedit ..."
gedit main.h main.cpp grid.h grid.cpp dictionary.txt
<file_sep>#!/bin/bash
echo "Compiling all source ... "
g++ main.cpp grid.cpp -o main
echo "Done compiling! Now attempting to run ..."
./main
<file_sep>#include <cstdlib>
#include <string>
#include <iostream>
#include <fstream> // for file i/o
#include <stdlib.h> // for srand() and rand()
#include <time.h> // to seed srand()
#include "main.h"
#include "grid.h"
using namespace std;
int main() {
srand((unsigned)time(NULL)); // seed rand by system time
cout << endl; // for output prettiness
Grid test;
doSearch(test);
return 0;
}
// member function definitions
void doSearch( Grid & grid ) {
unsigned found = 0; // how many words were found in the grid?
string item = "";
string output = "Found: ";
ifstream dict ("dictionary.txt");
while( dict.good() ) { // while there are still good entries in the list
getline( dict, item ); // get a line from dict (file) and set that to 'item'
if( item == "" ) continue; // skip this item if it is empty
grid.resetChecked(); // set grid of bools to false (not yet checked)
if( checkWord( item, grid, output ) ) {
found++;
}
}
grid.display();
cout << output << endl << "Total: " << found << " words!" << end2l;
return;
}
bool checkWord( const string & item, Grid & grid, string & output ) {
bool found = false;
// run through the grid checking the first letter in 'item' can be found
for( unsigned y = 0; y < GRID_SIZE; y++ ) {
for( unsigned x = 0; x < GRID_SIZE; x++ ) {
if( grid.getChar(y,x) == (char)item[0]) {
grid.setChecked(y,x);
found = checkNextLetter( item, grid, output, y, x, 1 );
if (found) return found;
}
}
}
return found; // if true is never returned, just return false
}
bool checkNextLetter( const string & item, Grid & grid, string & output, const unsigned & y, const unsigned & x, unsigned slot ) {
bool chainAlive = false;
if( slot == item.length() ) {
output += (item + ", ");
return true;
}
// check above, if not already checked!
if( y > 0 ) { // don't check above if we're already at the top!
if( grid.getChar(y-1,x) == (char)item[slot] && !grid.checkSpot(y-1,x) ) {
grid.setChecked(y-1,x);
chainAlive = checkNextLetter( item, grid, output, y-1, x, slot+1 );
}
}
// check below, if not already checked!
if( y < (GRID_SIZE-1) && !chainAlive) { // don't check below if we're already at the bottom!
if( grid.getChar(y+1,x) == (char)item[slot] && !grid.checkSpot(y+1,x) ) {
grid.setChecked(y+1,x);
chainAlive = checkNextLetter( item, grid, output, y+1, x, slot+1 );
}
}
// check right, if not already checked!
if( x < (GRID_SIZE-1) && !chainAlive) { // don't check right if we're already at the right!
if( grid.getChar(y,x+1) == (char)item[slot] && !grid.checkSpot(y,x+1) ) {
grid.setChecked(y,x+1);
chainAlive = checkNextLetter( item, grid, output, y, x+1, slot+1 );
}
}
// check left, if not already checked!
if( x > 0 && !chainAlive ) { // don't check left if we're already at the left!
if( grid.getChar(y,x-1) == (char)item[slot] && !grid.checkSpot(y,x-1) ) {
grid.setChecked(y,x-1);
chainAlive = checkNextLetter( item, grid, output, y, x-1, slot+1 );
}
}
return chainAlive;
}
<file_sep>WordSearch
==========
A 'boggle' style wordsearch that generates a random grid of letters and then searches it against a dictionary text file for valid words<file_sep>#ifndef main_h
#define main_h
#ifndef end2l
#define end2l endl<<endl
#endif
#ifndef GRID_SIZE
#define GRID_SIZE 10
#endif
#include "grid.h"
using namespace std;
void doSearch( Grid & grid );
bool checkWord( const string & item, Grid & grid, string & output );
bool checkNextLetter( const string & item, Grid & grid, string & output, const unsigned & y, const unsigned & x, unsigned slot );
#endif
<file_sep>#include <stdlib.h> // needed for srand(), rand()
#include "main.h"
#include "grid.h"
Grid::Grid( void ) {
for( unsigned y = 0; y < GRID_SIZE; y++ ) {
for( unsigned x = 0; x < GRID_SIZE; x++ ) {
spot[y][x].c = (char)(rand() % 26 + 97);
spot[y][x].checked = false;
}
}
resetChecked();
};
// member function definitions
void Grid::sayHi( void ) const {
cout << end2l << "Hello, World!" << end2l;
}
void Grid::display( void ) const {
cout << "Current grid content:" << end2l;
for( unsigned y = 0; y < GRID_SIZE; y++ ) { // for each row
for( unsigned x = 0; x < GRID_SIZE; x++ ) { // for each item in the row
cout << (x ? " " : "") << spot[y][x].c;
}
cout << endl;
}
cout << endl;
}
void Grid::displayChecked( void ) const {
cout << "Current checked status:" << end2l;
for( unsigned y = 0; y < GRID_SIZE; y++ ) { // for each row
for( unsigned x = 0; x < GRID_SIZE; x++ ) { // for each item in the row
cout << (x ? " " : "") << spot[y][x].checked;
}
cout << endl;
}
}
char Grid::getChar( unsigned y, unsigned x ) const {
return spot[y][x].c;
}
bool Grid::checkSpot( unsigned y, unsigned x ) const {
return spot[y][x].checked;
}
void Grid::setChecked( unsigned y, unsigned x) {
spot[y][x].checked = true;
}
void Grid::resetChecked( void ) {
for( unsigned y = 0; y < GRID_SIZE; y++ ) {
for( unsigned x = 0; x < GRID_SIZE; x++ ) {
spot[y][x].checked = false;
}
}
}
<file_sep>// [97, 122] <<< ASCII values of all lowercase letters
#ifndef _grid
#define _grid
#include <string>
#include <iostream>
#include "main.h"
using namespace std;
struct Node {
char c;
bool checked;
}; // node
class Grid {
public:
Grid( void );
void sayHi( void ) const;
void display( void ) const;
void displayChecked( void ) const;
char getChar( unsigned y, unsigned x ) const;
bool checkSpot( unsigned y, unsigned x ) const;
void setChecked( unsigned y, unsigned x);
void resetChecked( void );
private:
Node spot[GRID_SIZE][GRID_SIZE];
};
#endif
|
fb2dbabf1bee97414545536ec313400c7108d09d
|
[
"Markdown",
"C++",
"Shell"
] | 7
|
Shell
|
StevenKitzes/WordSearch
|
53c31cf0375339688bac8860beb294a74bd6dedf
|
3f235f19be4901883cb2c97784af2eb653947332
|
refs/heads/master
|
<repo_name>YStrano/ds_jk<file_sep>/sphinx_dat/build/html/_sources/index.rst.txt
.. GA-DAT-3-20 documentation master file, created by
sphinx-quickstart on Mon May 21 23:32:40 2018.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to GA-DAT-3-20's documentation!
=======================================
/anaconda3/Anaconda-Navigator.app
.. toctree::
:glob:
:caption: Course Materials
01-L5
02-L5
03-L5
04-L6
05-L6
03-L6.ipynb
01-L7.ipynb
02-L7.ipynb
03-L7.ipynb
01-L8.ipynb
02-L8.ipynb
01-L9.ipynb
02-L9.ipynb
03-L9.ipynb
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
<file_sep>/lyrics_precalc/lyrics/spiders/nas.py
# -*- coding: utf-8 -*-
import scrapy
class NasSpider(scrapy.Spider):
name = 'nas'
allowed_domains = ['www.azlyrics.com/n/nas.html']
start_urls = ['https://www.azlyrics.com/n/nas.html']
# linker = response.xpath('//div/div/a')
# links = []
# for link in linker:
# response.follow(link.css('a::attr(href)').extract())
def parse(self, response):
# gets hrefs
album_list = response.xpath('//*[@id="listAlbum"]/a')
for link in album_list[5:]:
ref = link.css('a::attr(href)').extract()[0][2:]
addie = 'https://www.azlyrics.com' + ref
yield response.follow(addie, self.lyric_parse)
def lyric_parse(self, response):
yield {
'lyrics': [i.strip() for i in response.xpath('/html/body/div[3]/div/div[2]/div[5]/text()').extract()]
}
# yield {
# 'lyrics': [i.strip() for i in response.xpath('/html/body/div[3]/div/div[2]/div[5]/text()').extract()],
# 'title': response.xpath('/html/body/div[3]/div/div[2]/b/text()').extract(),
# }
# for link in linker:
# next_page = response.follow(link, callback= self.parse)
# linker = response.xpath('//div/div/a')
# #generates links
# for link in linker:
# print(link.css('a::attr(href)').extract()<file_sep>/GA/GA-regression/README.md
#  Project #2: Exploratory Analysis
DS | Unit Project 2
### PROMPT
In this project, you will implement the exploratory analysis plan developed in Project 1. This will lay the groundwork for our first modeling exercise in Project 3.
Before completing an analysis, it is critical to understand your data. You will need to identify all the biases and variables in your model in order to accurately assess the strengths and limitations of your analysis and predictions.
Following these steps will help you better understand your dataset.
**Goal:** A Jupyter notebook writeup that provides a dataset overview with visualizations and statistical analysis.
---
### DELIVERABLES
#### Jupyter Notebook Exploratory Analysis
- **Requirements:**
- Read in your dataset, determine how many samples are present, and ID any missing data
- Create a table of descriptive statistics for each of the variables (n, mean, median, standard deviation)
- Describe the distributions of your data
- Plot box plots for each variable
- Create a covariance matrix
- Determine any issues or limitations, based on your exploratory analysis
- **Bonus:**
- Replace missing values using the median replacement method
- Log transform data to meet normality requirements
- Advanced Option: Replace missing values using multiple imputation methods
- **Submission:**
- Thursday April 5
- **Dataset**
- You may use the `admissions.csv` dataset from our last assignment or choose a different dataset that we've encountered in class.
<file_sep>/data-design/build/html/_sources/index.rst
.. Data and Design documentation master file, created by
sphinx-quickstart on Sun Jan 14 15:53:16 2018.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Data and Design's documentation!
===========================================
.. toctree::
:glob:
:caption: Course Materials
00-overview
01-syllabus
02-introPandas
03-datafiles
04-ProjectA
05-intro_to_scraping_I
07-scraping-jumpstreet
08_scraping_and_nltk
09-Machine-Learning-Intro
09_ML_Intro
010-Decision-Trees
11-django-intro
12-Django-templates
13-Django-Models-Blogs
<file_sep>/GA/GA-02-Modeling/projectIII.md
# Project III: Modeling I
The goal of this project is to implement the modeling process we have worked towards in class. You have options for what datasets you want to use,
however the primary goal is to frame, evaluate, and discuss a classification problem using at least Logistic Regression.
### Minimal Requirements
For this assignment, you are to prepare a Jupyter notebook that contains an analysis of a classification problem using Logistic Regression.
The `admissions` dataset provides a baseline example for this. You are free to find alternative examples. Regardless of your dataset, your notebook
should do the following:
- Describe the dataset including either an explicit data dictionary (in the case of a smaller dataset) or a link to an original data dictionary
(in the case of a large dataset)
- Explicitly frame your classification problem; what are you measuring and how are you going to understand the quality of your model?
- Describe any data cleaning and feature manipulation prior to model implementation
- Describe any parameter tuning or normalization that took place
- Be sure to use cross-validation in training
- Discuss results on test set
- Describe Accuracy, Precision, Recall, and F1 score of your model
- Plot and interpret the following:
- Precision and Recall curves together (thresholds vs. probability)
- Precision vs. Recall
- ROC curve
### Extra
- Frame and implement a Regression problem in the same dataset
- Use Gradient Descent to compare with closed form solutions
- Use KNearestNeighbors to frame and solve a classification problem in your data; discuss evaluation
<file_sep>/data-design/source/django/tutorial/accounts/templates/accounts/login.html
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</head>
<body>
<h1>Word up mom!</h1>
Welcome. Login Here.
<div class="container-fluid">
<p>Here's a paragraph in a container</p>
</div>
<blockquote class="blockquote">
<p class="mb-0">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p>
<footer class="blockquote-footer">Someone famous in <cite title="Source Title">Source Title</cite></footer>
</blockquote>
</body>
</html><file_sep>/lyrics_precalc/lyrics/spiders/trap_house.py
# -*- coding: utf-8 -*-
import scrapy
class TrapHouseSpider(scrapy.Spider):
name = 'trap_house'
allowed_domains = ['www.azlyrics.com/lyrics/guccimane/']
start_urls = ['https://www.azlyrics.com/lyrics/guccimane/intro.html',
'https://www.azlyrics.com/lyrics/guccimane/traphouse.html']
def parse(self, response):
yield {
'lyrics': [i.strip() for i in response.xpath('/html/body/div[3]/div/div[2]/div[5]/text()').extract()],
'title': response.xpath('/html/body/div[3]/div/div[2]/b/text()').extract() ,
}
<file_sep>/sphinx_dat/build/html/.ipynb_checkpoints/03-L5-checkpoint.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Regularized Methods — GA-DAT-3-20 1 documentation</title>
<link rel="stylesheet" href="../_static/alabaster.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="stylesheet" href="../_static/custom.css" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
</head>
<body>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<style>
/* CSS for nbsphinx extension */
/* remove conflicting styling from Sphinx themes */
div.nbinput,
div.nbinput div.prompt,
div.nbinput div.input_area,
div.nbinput div[class*=highlight],
div.nbinput div[class*=highlight] pre,
div.nboutput,
div.nbinput div.prompt,
div.nbinput div.output_area,
div.nboutput div[class*=highlight],
div.nboutput div[class*=highlight] pre {
background: none;
border: none;
padding: 0 0;
margin: 0;
box-shadow: none;
}
/* avoid gaps between output lines */
div.nboutput div[class*=highlight] pre {
line-height: normal;
}
/* input/output containers */
div.nbinput,
div.nboutput {
display: -webkit-flex;
display: flex;
align-items: flex-start;
margin: 0;
width: 100%;
}
@media (max-width: 540px) {
div.nbinput,
div.nboutput {
flex-direction: column;
}
}
/* input container */
div.nbinput {
padding-top: 5px;
}
/* last container */
div.nblast {
padding-bottom: 5px;
}
/* input prompt */
div.nbinput div.prompt pre {
color: #303F9F;
}
/* output prompt */
div.nboutput div.prompt pre {
color: #D84315;
}
/* all prompts */
div.nbinput div.prompt,
div.nboutput div.prompt {
min-width: 8ex;
padding-top: 0.4em;
padding-right: 0.4em;
text-align: right;
flex: 0;
}
@media (max-width: 540px) {
div.nbinput div.prompt,
div.nboutput div.prompt {
text-align: left;
padding: 0.4em;
}
div.nboutput div.prompt.empty {
padding: 0;
}
}
/* disable scrollbars on prompts */
div.nbinput div.prompt pre,
div.nboutput div.prompt pre {
overflow: hidden;
}
/* input/output area */
div.nbinput div.input_area,
div.nboutput div.output_area {
padding: 0.4em;
-webkit-flex: 1;
flex: 1;
overflow: auto;
}
@media (max-width: 540px) {
div.nbinput div.input_area,
div.nboutput div.output_area {
width: 100%;
}
}
/* input area */
div.nbinput div.input_area {
border: 1px solid #cfcfcf;
border-radius: 2px;
background: #f7f7f7;
}
/* override MathJax center alignment in output cells */
div.nboutput div[class*=MathJax] {
text-align: left !important;
}
/* override sphinx.ext.pngmath center alignment in output cells */
div.nboutput div.math p {
text-align: left;
}
/* standard error */
div.nboutput div.output_area.stderr {
background: #fdd;
}
/* ANSI colors */
.ansi-black-fg { color: #3E424D; }
.ansi-black-bg { background-color: #3E424D; }
.ansi-black-intense-fg { color: #282C36; }
.ansi-black-intense-bg { background-color: #282C36; }
.ansi-red-fg { color: #E75C58; }
.ansi-red-bg { background-color: #E75C58; }
.ansi-red-intense-fg { color: #B22B31; }
.ansi-red-intense-bg { background-color: #B22B31; }
.ansi-green-fg { color: #00A250; }
.ansi-green-bg { background-color: #00A250; }
.ansi-green-intense-fg { color: #007427; }
.ansi-green-intense-bg { background-color: #007427; }
.ansi-yellow-fg { color: #DDB62B; }
.ansi-yellow-bg { background-color: #DDB62B; }
.ansi-yellow-intense-fg { color: #B27D12; }
.ansi-yellow-intense-bg { background-color: #B27D12; }
.ansi-blue-fg { color: #208FFB; }
.ansi-blue-bg { background-color: #208FFB; }
.ansi-blue-intense-fg { color: #0065CA; }
.ansi-blue-intense-bg { background-color: #0065CA; }
.ansi-magenta-fg { color: #D160C4; }
.ansi-magenta-bg { background-color: #D160C4; }
.ansi-magenta-intense-fg { color: #A03196; }
.ansi-magenta-intense-bg { background-color: #A03196; }
.ansi-cyan-fg { color: #60C6C8; }
.ansi-cyan-bg { background-color: #60C6C8; }
.ansi-cyan-intense-fg { color: #258F8F; }
.ansi-cyan-intense-bg { background-color: #258F8F; }
.ansi-white-fg { color: #C5C1B4; }
.ansi-white-bg { background-color: #C5C1B4; }
.ansi-white-intense-fg { color: #A1A6B2; }
.ansi-white-intense-bg { background-color: #A1A6B2; }
.ansi-default-inverse-fg { color: #FFFFFF; }
.ansi-default-inverse-bg { background-color: #000000; }
.ansi-bold { font-weight: bold; }
.ansi-underline { text-decoration: underline; }
</style>
<div class="section" id="Regularized-Methods">
<h1>Regularized Methods<a class="headerlink" href="#Regularized-Methods" title="Permalink to this headline">¶</a></h1>
<ul class="simple">
<li>Feature Scaling</li>
<li>Test/Train split</li>
<li>Ridge, LASSO, Elastic Net Regression methods</li>
</ul>
<hr class="docutils" />
<p>In a regular linear scenario, we start with a regular linear function.</p>
<div class="math">
\[\hat y = b + ax_0\]</div>
<p>The mean square error of these predictions would be given by:</p>
<div class="math">
\[RSS(a, b) = \sum_{i = 1}^n(y_i - (ax_i + b))^2\]</div>
<p>From this basic <span class="math">\(MSE\)</span> formulation, we can introduce some
Regularized methods that add a <em>regularization term</em> to the <span class="math">\(MSE\)</span>.
We will look at three methods that offer slight variations on this term.</p>
<div class="section" id="Feature-Scaling">
<h2>Feature Scaling<a class="headerlink" href="#Feature-Scaling" title="Permalink to this headline">¶</a></h2>
<p>To use these methods, we want to scale our data. Many Machine Learning
algorithms don’t do well with data operating on very different scales.
Using the <code class="docutils literal"><span class="pre">MinMaxScaler</span></code> normalizes the data and brings the values
between 0 and 1. The <code class="docutils literal"><span class="pre">StandardScaler</span></code> method is less sensitive to wide
ranges of values. We will use both on our Ames housing data. To begin,
we need to select the numeric columns from the DataFrame so we can
transform them only.</p>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [1]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="o">%</span><span class="k">matplotlib</span> notebook
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [2]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="c1">#get our data and select the numer</span>
<span class="n">ames</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span><span class="s1">'data/ames_housing.csv'</span><span class="p">)</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">ames</span><span class="p">[</span><span class="s1">'SalePrice'</span><span class="p">]</span>
<span class="n">ames</span> <span class="o">=</span> <span class="n">ames</span><span class="o">.</span><span class="n">drop</span><span class="p">(</span><span class="s1">'SalePrice'</span><span class="p">,</span> <span class="n">axis</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [3]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">ames_numeric</span> <span class="o">=</span> <span class="n">ames</span><span class="o">.</span><span class="n">select_dtypes</span><span class="p">(</span><span class="n">include</span> <span class="o">=</span> <span class="s1">'int64'</span><span class="p">)</span>
<span class="n">ames_numeric</span><span class="o">.</span><span class="n">head</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[3]:
</pre></div>
</div>
<div class="output_area docutils container">
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Id</th>
<th>MSSubClass</th>
<th>LotArea</th>
<th>OverallQual</th>
<th>OverallCond</th>
<th>YearBuilt</th>
<th>YearRemodAdd</th>
<th>BsmtFinSF1</th>
<th>BsmtFinSF2</th>
<th>BsmtUnfSF</th>
<th>...</th>
<th>GarageArea</th>
<th>WoodDeckSF</th>
<th>OpenPorchSF</th>
<th>EnclosedPorch</th>
<th>3SsnPorch</th>
<th>ScreenPorch</th>
<th>PoolArea</th>
<th>MiscVal</th>
<th>MoSold</th>
<th>YrSold</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
<td>60</td>
<td>8450</td>
<td>7</td>
<td>5</td>
<td>2003</td>
<td>2003</td>
<td>706</td>
<td>0</td>
<td>150</td>
<td>...</td>
<td>548</td>
<td>0</td>
<td>61</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>2</td>
<td>2008</td>
</tr>
<tr>
<th>1</th>
<td>2</td>
<td>20</td>
<td>9600</td>
<td>6</td>
<td>8</td>
<td>1976</td>
<td>1976</td>
<td>978</td>
<td>0</td>
<td>284</td>
<td>...</td>
<td>460</td>
<td>298</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>5</td>
<td>2007</td>
</tr>
<tr>
<th>2</th>
<td>3</td>
<td>60</td>
<td>11250</td>
<td>7</td>
<td>5</td>
<td>2001</td>
<td>2002</td>
<td>486</td>
<td>0</td>
<td>434</td>
<td>...</td>
<td>608</td>
<td>0</td>
<td>42</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>9</td>
<td>2008</td>
</tr>
<tr>
<th>3</th>
<td>4</td>
<td>70</td>
<td>9550</td>
<td>7</td>
<td>5</td>
<td>1915</td>
<td>1970</td>
<td>216</td>
<td>0</td>
<td>540</td>
<td>...</td>
<td>642</td>
<td>0</td>
<td>35</td>
<td>272</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>2</td>
<td>2006</td>
</tr>
<tr>
<th>4</th>
<td>5</td>
<td>60</td>
<td>14260</td>
<td>8</td>
<td>5</td>
<td>2000</td>
<td>2000</td>
<td>655</td>
<td>0</td>
<td>490</td>
<td>...</td>
<td>836</td>
<td>192</td>
<td>84</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>12</td>
<td>2008</td>
</tr>
</tbody>
</table>
<p>5 rows × 34 columns</p>
</div></div>
</div>
</div>
<div class="section" id="Using-the-Scaler-on-a-DataFrame">
<h2>Using the Scaler on a DataFrame<a class="headerlink" href="#Using-the-Scaler-on-a-DataFrame" title="Permalink to this headline">¶</a></h2>
<p>Below, we can compare the results of the two scaling transformations by
passing a list of column names to the scaler. Note the practice of
initializing the object, fitting it, and transforming.</p>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [4]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="kn">from</span> <span class="nn">sklearn.preprocessing</span> <span class="k">import</span> <span class="n">StandardScaler</span><span class="p">,</span> <span class="n">MinMaxScaler</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [5]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">std_scaled</span> <span class="o">=</span> <span class="n">StandardScaler</span><span class="p">()</span>
<span class="n">minmax_scaled</span> <span class="o">=</span> <span class="n">MinMaxScaler</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [6]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">cols</span> <span class="o">=</span> <span class="n">ames_numeric</span><span class="o">.</span><span class="n">columns</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [7]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">std_df</span> <span class="o">=</span> <span class="n">std_scaled</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">ames</span><span class="p">[[</span><span class="n">name</span> <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">cols</span><span class="p">]])</span>
<span class="n">minmax_df</span> <span class="o">=</span> <span class="n">minmax_scaled</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">ames</span><span class="p">[[</span><span class="n">name</span> <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">cols</span><span class="p">]])</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [8]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">std_df</span><span class="p">)</span><span class="o">.</span><span class="n">head</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[8]:
</pre></div>
</div>
<div class="output_area docutils container">
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
<th>...</th>
<th>24</th>
<th>25</th>
<th>26</th>
<th>27</th>
<th>28</th>
<th>29</th>
<th>30</th>
<th>31</th>
<th>32</th>
<th>33</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>-1.730865</td>
<td>0.073375</td>
<td>-0.207142</td>
<td>0.651479</td>
<td>-0.517200</td>
<td>1.050994</td>
<td>0.878668</td>
<td>0.575425</td>
<td>-0.288653</td>
<td>-0.944591</td>
<td>...</td>
<td>0.351000</td>
<td>-0.752176</td>
<td>0.216503</td>
<td>-0.359325</td>
<td>-0.116339</td>
<td>-0.270208</td>
<td>-0.068692</td>
<td>-0.087688</td>
<td>-1.599111</td>
<td>0.138777</td>
</tr>
<tr>
<th>1</th>
<td>-1.728492</td>
<td>-0.872563</td>
<td>-0.091886</td>
<td>-0.071836</td>
<td>2.179628</td>
<td>0.156734</td>
<td>-0.429577</td>
<td>1.171992</td>
<td>-0.288653</td>
<td>-0.641228</td>
<td>...</td>
<td>-0.060731</td>
<td>1.626195</td>
<td>-0.704483</td>
<td>-0.359325</td>
<td>-0.116339</td>
<td>-0.270208</td>
<td>-0.068692</td>
<td>-0.087688</td>
<td>-0.489110</td>
<td>-0.614439</td>
</tr>
<tr>
<th>2</th>
<td>-1.726120</td>
<td>0.073375</td>
<td>0.073480</td>
<td>0.651479</td>
<td>-0.517200</td>
<td>0.984752</td>
<td>0.830215</td>
<td>0.092907</td>
<td>-0.288653</td>
<td>-0.301643</td>
<td>...</td>
<td>0.631726</td>
<td>-0.752176</td>
<td>-0.070361</td>
<td>-0.359325</td>
<td>-0.116339</td>
<td>-0.270208</td>
<td>-0.068692</td>
<td>-0.087688</td>
<td>0.990891</td>
<td>0.138777</td>
</tr>
<tr>
<th>3</th>
<td>-1.723747</td>
<td>0.309859</td>
<td>-0.096897</td>
<td>0.651479</td>
<td>-0.517200</td>
<td>-1.863632</td>
<td>-0.720298</td>
<td>-0.499274</td>
<td>-0.288653</td>
<td>-0.061670</td>
<td>...</td>
<td>0.790804</td>
<td>-0.752176</td>
<td>-0.176048</td>
<td>4.092524</td>
<td>-0.116339</td>
<td>-0.270208</td>
<td>-0.068692</td>
<td>-0.087688</td>
<td>-1.599111</td>
<td>-1.367655</td>
</tr>
<tr>
<th>4</th>
<td>-1.721374</td>
<td>0.073375</td>
<td>0.375148</td>
<td>1.374795</td>
<td>-0.517200</td>
<td>0.951632</td>
<td>0.733308</td>
<td>0.463568</td>
<td>-0.288653</td>
<td>-0.174865</td>
<td>...</td>
<td>1.698485</td>
<td>0.780197</td>
<td>0.563760</td>
<td>-0.359325</td>
<td>-0.116339</td>
<td>-0.270208</td>
<td>-0.068692</td>
<td>-0.087688</td>
<td>2.100892</td>
<td>0.138777</td>
</tr>
</tbody>
</table>
<p>5 rows × 34 columns</p>
</div></div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [9]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">minmax_df</span><span class="p">)</span><span class="o">.</span><span class="n">head</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[9]:
</pre></div>
</div>
<div class="output_area docutils container">
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
<th>...</th>
<th>24</th>
<th>25</th>
<th>26</th>
<th>27</th>
<th>28</th>
<th>29</th>
<th>30</th>
<th>31</th>
<th>32</th>
<th>33</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0.000000</td>
<td>0.235294</td>
<td>0.033420</td>
<td>0.666667</td>
<td>0.500</td>
<td>0.949275</td>
<td>0.883333</td>
<td>0.125089</td>
<td>0.0</td>
<td>0.064212</td>
<td>...</td>
<td>0.386460</td>
<td>0.000000</td>
<td>0.111517</td>
<td>0.000000</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>0.090909</td>
<td>0.50</td>
</tr>
<tr>
<th>1</th>
<td>0.000685</td>
<td>0.000000</td>
<td>0.038795</td>
<td>0.555556</td>
<td>0.875</td>
<td>0.753623</td>
<td>0.433333</td>
<td>0.173281</td>
<td>0.0</td>
<td>0.121575</td>
<td>...</td>
<td>0.324401</td>
<td>0.347725</td>
<td>0.000000</td>
<td>0.000000</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>0.363636</td>
<td>0.25</td>
</tr>
<tr>
<th>2</th>
<td>0.001371</td>
<td>0.235294</td>
<td>0.046507</td>
<td>0.666667</td>
<td>0.500</td>
<td>0.934783</td>
<td>0.866667</td>
<td>0.086109</td>
<td>0.0</td>
<td>0.185788</td>
<td>...</td>
<td>0.428773</td>
<td>0.000000</td>
<td>0.076782</td>
<td>0.000000</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>0.727273</td>
<td>0.50</td>
</tr>
<tr>
<th>3</th>
<td>0.002056</td>
<td>0.294118</td>
<td>0.038561</td>
<td>0.666667</td>
<td>0.500</td>
<td>0.311594</td>
<td>0.333333</td>
<td>0.038271</td>
<td>0.0</td>
<td>0.231164</td>
<td>...</td>
<td>0.452750</td>
<td>0.000000</td>
<td>0.063985</td>
<td>0.492754</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>0.090909</td>
<td>0.00</td>
</tr>
<tr>
<th>4</th>
<td>0.002742</td>
<td>0.235294</td>
<td>0.060576</td>
<td>0.777778</td>
<td>0.500</td>
<td>0.927536</td>
<td>0.833333</td>
<td>0.116052</td>
<td>0.0</td>
<td>0.209760</td>
<td>...</td>
<td>0.589563</td>
<td>0.224037</td>
<td>0.153565</td>
<td>0.000000</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>1.000000</td>
<td>0.50</td>
</tr>
</tbody>
</table>
<p>5 rows × 34 columns</p>
</div></div>
</div>
</div>
<div class="section" id="Fit-a-Linear-Model-on-Scaled-Data">
<h2>Fit a Linear Model on Scaled Data<a class="headerlink" href="#Fit-a-Linear-Model-on-Scaled-Data" title="Permalink to this headline">¶</a></h2>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [10]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="k">import</span> <span class="n">LinearRegression</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [11]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">lm</span> <span class="o">=</span> <span class="n">LinearRegression</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [12]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">y</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [13]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">ames_numeric_scaled</span> <span class="o">=</span> <span class="n">std_scaled</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">ames</span><span class="p">[[</span><span class="n">name</span> <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">cols</span><span class="p">]])</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [14]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">lm</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">ames_numeric_scaled</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput docutils container">
<div class="prompt empty docutils container">
</div>
<div class="stderr output_area docutils container">
<div class="highlight"><pre>
/anaconda3/lib/python3.6/site-packages/scipy/linalg/basic.py:1226: RuntimeWarning: internal gelsd driver lwork query error, required iwork dimension not returned. This is likely the result of LAPACK bug 0038, fixed in LAPACK 3.2.2 (released July 21, 2010). Falling back to 'gelss' driver.
warnings.warn(mesg, RuntimeWarning)
</pre></div></div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[14]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [15]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="kn">from</span> <span class="nn">sklearn.metrics</span> <span class="k">import</span> <span class="n">mean_squared_error</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [16]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">predictions</span> <span class="o">=</span> <span class="n">lm</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">ames_numeric_scaled</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [17]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">mse</span> <span class="o">=</span> <span class="n">mean_squared_error</span><span class="p">(</span><span class="n">y</span><span class="p">,</span> <span class="n">predictions</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [18]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rmse</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">mse</span><span class="p">)</span>
<span class="n">score</span> <span class="o">=</span> <span class="n">lm</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">ames_numeric_scaled</span><span class="p">,</span> <span class="n">predictions</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [19]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="nb">print</span><span class="p">(</span><span class="s1">'R-squared score: </span><span class="si">{}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">score</span><span class="p">),</span> <span class="s1">'</span><span class="se">\n</span><span class="s1">RMSE: </span><span class="si">{:.4f}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">rmse</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
R-squared score: 1.0
RMSE: 0.1457
</pre></div></div>
</div>
</div>
<div class="section" id="Splitting-the-Data">
<h2>Splitting the Data<a class="headerlink" href="#Splitting-the-Data" title="Permalink to this headline">¶</a></h2>
<p>As we have seen, we will tend to overfit the data if we use the entire
dataset to determine the model. To account for this, we will split our
datasets into a <strong>training set</strong> to build our model on, and a <strong>test
set</strong> to evaluate the performance of the model. We have a handy sklearn
method for doing this, who by default splits the data into 80% for
training and 20% for testing.</p>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [20]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="k">import</span> <span class="n">train_test_split</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [21]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">train_test_split</span><span class="p">(</span><span class="n">ames_numeric_scaled</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [22]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">lm</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[22]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [23]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">pred</span> <span class="o">=</span> <span class="n">lm</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [24]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">mse</span> <span class="o">=</span> <span class="n">mean_squared_error</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">pred</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [25]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rmse</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">mse</span><span class="p">)</span>
<span class="n">rmse</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[25]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>0.1907947761739675
</pre></div>
</div>
</div>
</div>
<div class="section" id="Regularized-Methods-Comparison">
<h2>Regularized Methods Comparison<a class="headerlink" href="#Regularized-Methods-Comparison" title="Permalink to this headline">¶</a></h2>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [26]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">crime</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span><span class="s1">'data/crime_data.csv'</span><span class="p">,</span> <span class="n">index_col</span> <span class="o">=</span> <span class="s1">'Unnamed: 0'</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [27]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">crime</span><span class="o">.</span><span class="n">head</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[27]:
</pre></div>
</div>
<div class="output_area docutils container">
<div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>population</th>
<th>householdsize</th>
<th>agePct12t21</th>
<th>agePct12t29</th>
<th>agePct16t24</th>
<th>agePct65up</th>
<th>numbUrban</th>
<th>pctUrban</th>
<th>medIncome</th>
<th>pctWWage</th>
<th>...</th>
<th>MedOwnCostPctInc</th>
<th>MedOwnCostPctIncNoMtg</th>
<th>NumInShelters</th>
<th>NumStreet</th>
<th>PctForeignBorn</th>
<th>PctBornSameState</th>
<th>PctSameHouse85</th>
<th>PctSameCity85</th>
<th>PctSameState85</th>
<th>ViolentCrimesPerPop</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>11980</td>
<td>3.10</td>
<td>12.47</td>
<td>21.44</td>
<td>10.93</td>
<td>11.33</td>
<td>11980</td>
<td>100.0</td>
<td>75122</td>
<td>89.24</td>
<td>...</td>
<td>21.1</td>
<td>14.0</td>
<td>11</td>
<td>0</td>
<td>10.66</td>
<td>53.72</td>
<td>65.29</td>
<td>78.09</td>
<td>89.14</td>
<td>41.02</td>
</tr>
<tr>
<th>1</th>
<td>23123</td>
<td>2.82</td>
<td>11.01</td>
<td>21.30</td>
<td>10.48</td>
<td>17.18</td>
<td>23123</td>
<td>100.0</td>
<td>47917</td>
<td>78.99</td>
<td>...</td>
<td>20.7</td>
<td>12.5</td>
<td>0</td>
<td>0</td>
<td>8.30</td>
<td>77.17</td>
<td>71.27</td>
<td>90.22</td>
<td>96.12</td>
<td>127.56</td>
</tr>
<tr>
<th>2</th>
<td>29344</td>
<td>2.43</td>
<td>11.36</td>
<td>25.88</td>
<td>11.01</td>
<td>10.28</td>
<td>29344</td>
<td>100.0</td>
<td>35669</td>
<td>82.00</td>
<td>...</td>
<td>21.7</td>
<td>11.6</td>
<td>16</td>
<td>0</td>
<td>5.00</td>
<td>44.77</td>
<td>36.60</td>
<td>61.26</td>
<td>82.85</td>
<td>218.59</td>
</tr>
<tr>
<th>3</th>
<td>16656</td>
<td>2.40</td>
<td>12.55</td>
<td>25.20</td>
<td>12.19</td>
<td>17.57</td>
<td>0</td>
<td>0.0</td>
<td>20580</td>
<td>68.15</td>
<td>...</td>
<td>20.6</td>
<td>14.5</td>
<td>0</td>
<td>0</td>
<td>2.04</td>
<td>88.71</td>
<td>56.70</td>
<td>90.17</td>
<td>96.24</td>
<td>306.64</td>
</tr>
<tr>
<th>5</th>
<td>140494</td>
<td>2.45</td>
<td>18.09</td>
<td>32.89</td>
<td>20.04</td>
<td>13.26</td>
<td>140494</td>
<td>100.0</td>
<td>21577</td>
<td>75.78</td>
<td>...</td>
<td>17.3</td>
<td>11.7</td>
<td>327</td>
<td>4</td>
<td>1.49</td>
<td>64.35</td>
<td>42.29</td>
<td>70.61</td>
<td>85.66</td>
<td>442.95</td>
</tr>
</tbody>
</table>
<p>5 rows × 89 columns</p>
</div></div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [28]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">y</span> <span class="o">=</span> <span class="n">crime</span><span class="p">[</span><span class="s1">'ViolentCrimesPerPop'</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [29]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">X</span> <span class="o">=</span> <span class="n">crime</span><span class="o">.</span><span class="n">drop</span><span class="p">(</span><span class="s1">'ViolentCrimesPerPop'</span><span class="p">,</span> <span class="n">axis</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [30]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">train_test_split</span><span class="p">(</span><span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [31]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">scaler</span> <span class="o">=</span> <span class="n">MinMaxScaler</span><span class="p">()</span>
<span class="n">X_train_scaled</span> <span class="o">=</span> <span class="n">scaler</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">X_train</span><span class="p">)</span>
<span class="n">X_test_scaled</span> <span class="o">=</span> <span class="n">scaler</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [32]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">lm</span> <span class="o">=</span> <span class="n">LinearRegression</span><span class="p">()</span>
<span class="n">lm</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train_scaled</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
<span class="n">predictions</span> <span class="o">=</span> <span class="n">lm</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">)</span>
<span class="n">rmse</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">mean_squared_error</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">predictions</span><span class="p">))</span>
<span class="n">score</span> <span class="o">=</span> <span class="n">lm</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">,</span> <span class="n">y_test</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'The r2 value is : </span><span class="si">{:.4f}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">score</span><span class="p">),</span> <span class="s1">'</span><span class="se">\n</span><span class="s1">The RMSE value is </span><span class="si">{:.4f}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">rmse</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
The r2 value is : 0.4786
The RMSE value is 415.6595
</pre></div></div>
</div>
</div>
<div class="section" id="Ridge-Regression">
<h2>Ridge Regression<a class="headerlink" href="#Ridge-Regression" title="Permalink to this headline">¶</a></h2>
<div class="math">
\[RSS(w, b) = \sum_{i = 1} ^ N (y_i - (wx_i + b))^2 + \alpha \sum_{j = 1}^p w_j^2\]</div>
<p>Many feature coefficients will be determined with small values. Larger
<span class="math">\(\alpha\)</span> means larger penalty, zero is base LinearRegression, and
the default for sklearn’s implementation is 1.0.</p>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [33]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="k">import</span> <span class="n">Ridge</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [34]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">ridge_reg</span> <span class="o">=</span> <span class="n">Ridge</span><span class="p">(</span><span class="n">alpha</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [35]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">ridge_reg</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train_scaled</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[35]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>Ridge(alpha=1, copy_X=True, fit_intercept=True, max_iter=None,
normalize=False, random_state=None, solver='cholesky', tol=0.001)
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [36]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rpred</span> <span class="o">=</span> <span class="n">ridge_reg</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [37]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rmse</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">mean_squared_error</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">rpred</span><span class="p">))</span>
<span class="n">score</span> <span class="o">=</span> <span class="n">ridge_reg</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">,</span> <span class="n">y_test</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'The r2 value is : </span><span class="si">{:.4f}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">score</span><span class="p">),</span> <span class="s1">'</span><span class="se">\n</span><span class="s1">The RMSE value is </span><span class="si">{:.4f}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">rmse</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
The r2 value is : 0.4757
The RMSE value is 416.7998
</pre></div></div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [38]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">ridge_reg</span><span class="o">.</span><span class="n">coef_</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[38]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>88
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [39]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">crime</span><span class="o">.</span><span class="n">shape</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[39]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>(1994, 89)
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [40]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">ridge_reg</span> <span class="o">=</span> <span class="n">Ridge</span><span class="p">(</span><span class="n">alpha</span> <span class="o">=</span> <span class="mi">20</span><span class="p">)</span>
<span class="n">ridge_reg</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train_scaled</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
<span class="n">rpred</span> <span class="o">=</span> <span class="n">ridge_reg</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">)</span>
<span class="n">rmse</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">mean_squared_error</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">rpred</span><span class="p">))</span>
<span class="n">score</span> <span class="o">=</span> <span class="n">ridge_reg</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">,</span> <span class="n">y_test</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'The r2 value is : </span><span class="si">{:.4f}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">score</span><span class="p">),</span> <span class="s1">'</span><span class="se">\n</span><span class="s1">The RMSE value is </span><span class="si">{:.4f}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">rmse</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
The r2 value is : 0.5295
The RMSE value is 394.8400
</pre></div></div>
</div>
</div>
<div class="section" id="Lasso-Regression">
<h2>Lasso Regression<a class="headerlink" href="#Lasso-Regression" title="Permalink to this headline">¶</a></h2>
<div class="math">
\[RSS(w, b) = \sum_{i = 1} ^ N (y_i - (wx_i + b))^2 + \alpha \sum_{j = 1}^p |w_j|\]</div>
<p>Now, we end up in effect setting variables with low influence to a
coefficient of zero. Compared to Ridge, we would use Lasso if there are
only a few variables with substantial effects.</p>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [41]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="k">import</span> <span class="n">Lasso</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [42]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">lasso_reg</span> <span class="o">=</span> <span class="n">Lasso</span><span class="p">(</span><span class="n">alpha</span> <span class="o">=</span> <span class="mf">2.0</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [43]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">lasso_reg</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train_scaled</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[43]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>Lasso(alpha=2.0, copy_X=True, fit_intercept=True, max_iter=1000,
normalize=False, positive=False, precompute=False, random_state=None,
selection='cyclic', tol=0.0001, warm_start=False)
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [44]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">lpred</span> <span class="o">=</span> <span class="n">lasso_reg</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [45]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rmse</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">mean_squared_error</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">lpred</span><span class="p">))</span>
<span class="n">score</span> <span class="o">=</span> <span class="n">ridge_reg</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">,</span> <span class="n">y_test</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'The r2 value is : </span><span class="si">{:.4f}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">score</span><span class="p">),</span> <span class="s1">'</span><span class="se">\n</span><span class="s1">The RMSE value is </span><span class="si">{:.4f}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">rmse</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
The r2 value is : 0.5295
The RMSE value is 423.7267
</pre></div></div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [46]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">np</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">lasso_reg</span><span class="o">.</span><span class="n">coef_</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[46]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>18
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [47]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="nb">sorted</span> <span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">X</span><span class="p">),</span> <span class="n">lasso_reg</span><span class="o">.</span><span class="n">coef_</span><span class="p">)),</span>
<span class="n">key</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">e</span><span class="p">:</span> <span class="o">-</span><span class="nb">abs</span><span class="p">(</span><span class="n">e</span><span class="p">[</span><span class="mi">1</span><span class="p">])):</span>
<span class="k">if</span> <span class="n">e</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="se">\t</span><span class="si">{}</span><span class="s1">, </span><span class="si">{:.3f}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">e</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">e</span><span class="p">[</span><span class="mi">1</span><span class="p">]))</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
PctKidsBornNeverMar, 1987.236
PctKids2Par, -842.249
PctVacantBoarded, 343.748
PctHousOccup, -331.982
PctForeignBorn, 328.357
MalePctDivorce, 292.700
NumInShelters, 248.496
MedOwnCostPctIncNoMtg, -192.645
PctWorkMom, -141.906
pctWInvInc, -136.523
pctUrban, 123.742
PctEmplManu, -113.120
MedYrHousBuilt, 82.142
pctWPubAsst, 71.706
agePct12t29, -59.647
RentQrange, 47.841
PctSameCity85, 45.718
OwnOccHiQuart, 15.365
</pre></div></div>
</div>
</div>
<div class="section" id="Elastic-Net">
<h2>Elastic Net<a class="headerlink" href="#Elastic-Net" title="Permalink to this headline">¶</a></h2>
<div class="math">
\[RSS(w, b) = \sum_{i = 1} ^ N (y_i - (wx_i + b))^2 + r\alpha\sum_{i = 1}^n |w_j| + \frac{1-r}{2} \alpha \sum_{j = 1}^p w_j^2\]</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [48]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="k">import</span> <span class="n">ElasticNet</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [49]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">elastic_reg</span> <span class="o">=</span> <span class="n">ElasticNet</span><span class="p">(</span><span class="n">alpha</span> <span class="o">=</span> <span class="o">.</span><span class="mi">05</span><span class="p">,</span> <span class="n">l1_ratio</span><span class="o">=</span><span class="mf">0.4</span><span class="p">)</span>
<span class="n">elastic_reg</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train_scaled</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
<span class="n">epred</span> <span class="o">=</span> <span class="n">elastic_reg</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">)</span>
<span class="n">rmse</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">mean_squared_error</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">epred</span><span class="p">))</span>
<span class="n">rmse</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[49]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>395.9689402572352
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [50]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">ridge_score</span> <span class="o">=</span> <span class="n">ridge_reg</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">,</span> <span class="n">y_test</span><span class="p">)</span>
<span class="n">lasso_score</span> <span class="o">=</span> <span class="n">lasso_reg</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">,</span> <span class="n">y_test</span><span class="p">)</span>
<span class="n">elastic_score</span> <span class="o">=</span> <span class="n">elastic_reg</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">X_test_scaled</span><span class="p">,</span> <span class="n">y_test</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [51]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="nb">print</span><span class="p">(</span><span class="s2">"Ridge: </span><span class="si">{:.4f}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">ridge_score</span><span class="p">),</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">Lasso: </span><span class="si">{:.4f}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">lasso_score</span><span class="p">),</span>
<span class="s2">"</span><span class="se">\n</span><span class="s2">Elastic Net: </span><span class="si">{:.4f}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">elastic_score</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
Ridge: 0.5295
Lasso: 0.4582
Elastic Net: 0.5268
</pre></div></div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [ ]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">scaled</span><span class="p">,</span> <span class="n">columns</span> <span class="o">=</span> <span class="n">cols</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="PROBLEM">
<h2>PROBLEM<a class="headerlink" href="#PROBLEM" title="Permalink to this headline">¶</a></h2>
<p>Return to your Ames Data. We have covered a lot of ground today, so
let’s summarize the things we could do to improve the performance of our
original model that compared the Above Ground Living Area to the
Logarithm of the Sale Price.</p>
<div class="alert alert-info" role="alert"><ol class="arabic simple">
<li>Clean data, drop missing values</li>
<li>Transform data, code variables using either ordinal values or
OneHotEncoder methods</li>
<li>Create more features from existing features</li>
<li>Split our data into testing and training sets</li>
<li>Normalize quantitative features</li>
<li>Use Regularized Regression methods and Polynomial regression to
improve performance of model</li>
</ol>
</div><p>Can you use some or all of these ideas to improve upon your initial
model?</p>
</div>
<div class="section" id="Additional-Resources">
<h2>Additional Resources<a class="headerlink" href="#Additional-Resources" title="Permalink to this headline">¶</a></h2>
<p>The last two lessons have pulled heavily from these resources. I
recommend them all strongly as excellent resources:</p>
<ul class="simple">
<li>SciKitLearn documentation on Regression:
<a class="reference external" href="http://scikit-learn.org/stable/supervised_learning.html#supervised-learning">http://scikit-learn.org/stable/supervised_learning.html#supervised-learning</a></li>
<li><NAME>, <em>Hands on Machine Learning with SciKitLearn and
TensorFlow</em></li>
<li>James et. al, <em>An Introduction to Statistical Learning: With
Applications in R</em></li>
<li><NAME>, <em>Data Analysis with OpenSource Tools</em></li>
<li>University of Michigan Coursera Class on Machine Learning with
SciKitLearn: <a class="reference external" href="https://www.coursera.org/learn/python-machine-learning">https://www.coursera.org/learn/python-machine-learning</a></li>
<li>Stanford University course on Machine Learning:
<a class="reference external" href="https://www.coursera.org/learn/machine-learning">https://www.coursera.org/learn/machine-learning</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper"><div class="relations">
<h3>Related Topics</h3>
<ul>
<li><a href="../index.html">Documentation overview</a><ul>
</ul></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
©2018, <NAME>.
|
Powered by <a href="http://sphinx-doc.org/">Sphinx 1.6.6</a>
& <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a>
|
<a href="../_sources/.ipynb_checkpoints/03-L5-checkpoint.ipynb.txt"
rel="nofollow">Page source</a>
</div>
</body>
</html><file_sep>/data-design/build/html/_sources/index.rst.txt
.. Data and Design documentation master file, created by
sphinx-quickstart on Sun Jan 14 15:53:16 2018.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Data and Design's documentation!
===========================================
.. toctree::
:maxdepth: 2
:caption: Contents:
0.0_overview
0.1_Pandas_and_Seaborn
0.2_Pandas_Seaborn_WorldBank
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
<file_sep>/Pipelines-and-Pickles/README.md
# Pipelines-and-Pickles
<file_sep>/data-design/build/html/11-django-intro.html
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Django Introduction — Data and Design version 7150b89</title>
<link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
<link rel="index" title="Index"
href="genindex.html"/>
<link rel="search" title="Search" href="search.html"/>
<link rel="top" title="Data and Design version 7150b89" href="index.html"/>
<link rel="next" title="Templates and Bootstrap" href="12-Django-templates.html"/>
<link rel="prev" title="Decision Tree Classifiers" href="010-Decision-Trees.html"/>
<script src="_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="index.html">
<img src="_static/logo.svg" class="logo" />
</a>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="03-datafiles.html">Data Accession</a></li>
<li class="toctree-l1"><a class="reference internal" href="04-ProjectA.html">Project A</a></li>
<li class="toctree-l1"><a class="reference internal" href="05-intro_to_scraping_I.html">Introduction to Web Scraping</a></li>
<li class="toctree-l1"><a class="reference internal" href="07-scraping-jumpstreet.html">Scraping the Street</a></li>
<li class="toctree-l1"><a class="reference internal" href="08_scraping_and_nltk.html">Webscraping and Natural Language Processing</a></li>
<li class="toctree-l1"><a class="reference internal" href="09-Machine-Learning-Intro.html">Introduction to Machine Learning</a></li>
<li class="toctree-l1"><a class="reference internal" href="09_ML_Intro.html">Intro to Machine Learning</a></li>
<li class="toctree-l1"><a class="reference internal" href="010-Decision-Trees.html">Decision Tree Classifiers</a></li>
<li class="toctree-l1 current"><a class="current reference internal" href="#">Django Introduction</a><ul>
<li class="toctree-l2"><a class="reference internal" href="#A-First-Django-Project">A First Django Project</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#Set-up-Directory-and-Virtual-Environment">Set up Directory and Virtual Environment</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Start-a-Django-Project">Start a Django Project</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Starting-an-App">Starting an App</a></li>
<li class="toctree-l3"><a class="reference internal" href="#Django-Views">Django Views</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="12-Django-templates.html">Templates and Bootstrap</a></li>
<li class="toctree-l1"><a class="reference internal" href="13-Django-Models-Blogs.html">Django Models: Building a Blog</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="index.html">Data and Design</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="index.html">Docs</a> »</li>
<li>Django Introduction</li>
<li class="wy-breadcrumbs-aside">
<a href="_sources/11-django-intro.ipynb" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<style>
/* CSS overrides for sphinx_rtd_theme */
/* 24px margin */
.nbinput.nblast,
.nboutput.nblast {
margin-bottom: 19px; /* padding has already 5px */
}
/* ... except between code cells! */
.nblast + .nbinput {
margin-top: -19px;
}
/* nice headers on first paragraph of info/warning boxes */
.admonition .first {
margin: -12px;
padding: 6px 12px;
margin-bottom: 12px;
color: #fff;
line-height: 1;
display: block;
}
.admonition.warning .first {
background: #f0b37e;
}
.admonition.note .first {
background: #6ab0de;
}
.admonition > p:before {
margin-right: 4px; /* make room for the exclamation icon */
}
</style>
<div class="section" id="Django-Introduction">
<h1>Django Introduction<a class="headerlink" href="#Django-Introduction" title="Permalink to this headline">¶</a></h1>
<p>In this initial project, we will be introduced to formal use of the
shell to create our first Django Project. As discussed, if you are using
a Mac, you have a terminal available by looking in the search bar. The
terminal is a place to interact with and create and edit programs. We
will use the following commands:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">cd</span></code> (change directory)</li>
<li><code class="docutils literal"><span class="pre">pwd</span></code> (print working directory)</li>
<li><code class="docutils literal"><span class="pre">ls</span></code> (list files)</li>
<li><code class="docutils literal"><span class="pre">mkdir</span></code> (make directory)</li>
<li><code class="docutils literal"><span class="pre">touch</span></code> (create file)</li>
</ul>
<p>For example, I have a folder on my desktop where I keep all my files for
this semester. I can open a new terminal and type</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>cd Desktop spring_18
</pre></div>
</div>
<p>and I will now be located in this folder. If I wanted to see the files
here, I can write</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>ls -F
</pre></div>
</div>
<p>where the <code class="docutils literal"><span class="pre">-F</span></code> flags directories.</p>
<p>If we wanted to make a new directory named <code class="docutils literal"><span class="pre">images</span></code>, we can use</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>mkdir images
</pre></div>
</div>
<p>To create a new file, for example <code class="docutils literal"><span class="pre">home.html</span></code>, we would use</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>touch home.html
</pre></div>
</div>
<hr class="docutils" />
<p>Finally, we will be using virtual environments for this project and will
use <code class="docutils literal"><span class="pre">pipenv</span></code> to do this. In our terminal we can type</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>pip install pipenv
</pre></div>
</div>
<div class="section" id="A-First-Django-Project">
<h2>A First Django Project<a class="headerlink" href="#A-First-Django-Project" title="Permalink to this headline">¶</a></h2>
<p>To begin, we will create an empty project with Django to get a feel for
using the virtual environment in the shell. We need to check that we
have git working, and that we can open SublimeText (or another text
editor) on our computers.</p>
<div class="section" id="Set-up-Directory-and-Virtual-Environment">
<h3>Set up Directory and Virtual Environment<a class="headerlink" href="#Set-up-Directory-and-Virtual-Environment" title="Permalink to this headline">¶</a></h3>
<p>Let’s create a folder for our project on our desktop called django, and
navigate into this folder by typing:</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>mkdir django
cd django
</pre></div>
</div>
<p>Now we will create a virtual environment where we install django.</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>pipenv install django
</pre></div>
</div>
<p>and activate it with</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>pipenv shell
</pre></div>
</div>
</div>
<div class="section" id="Start-a-Django-Project">
<h3>Start a Django Project<a class="headerlink" href="#Start-a-Django-Project" title="Permalink to this headline">¶</a></h3>
<p>Now, we can start a project to test our new django installation. Let’s
create a project called <code class="docutils literal"><span class="pre">mysite</span></code> by typing the following in the
terminal:</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>django-admin startproject mysite .
</pre></div>
</div>
<p>We can now examine the structure of the directory we have created with</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>tree
</pre></div>
</div>
<div class="figure">
<img alt="" src="_images/django_tree.png" />
</div>
<p>This is the standard django project structure. A <code class="docutils literal"><span class="pre">manage.py</span></code> python
file, and a directory named <code class="docutils literal"><span class="pre">mysite</span></code> containing four files:
<code class="docutils literal"><span class="pre">__init__.py</span></code>, <code class="docutils literal"><span class="pre">settings.py</span></code>, <code class="docutils literal"><span class="pre">urls.py</span></code>, and <code class="docutils literal"><span class="pre">wsgi.py</span></code>. To see
the blank project in action, we will use the built in server, located in
the <code class="docutils literal"><span class="pre">manage.py</span></code> file. To use this, we write</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>python manage.py runserver
</pre></div>
</div>
<p>We should see the project launched on our local computer at
<a class="reference external" href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>. When we go to this page, we should see the
following:</p>
<div class="figure">
<img alt="" src="_images/django_home.png" />
</div>
<p>Now that we’ve started our project, we will add some content to it.</p>
</div>
<div class="section" id="Starting-an-App">
<h3>Starting an App<a class="headerlink" href="#Starting-an-App" title="Permalink to this headline">¶</a></h3>
<p>Similar to how we made use of the default Django project structure,
within our project we will create an app named pages with the command</p>
<div class="highlight-none"><div class="highlight"><pre><span></span>python manage.py startapp pages
</pre></div>
</div>
<p>Now, we have a directory with the following structure</p>
<div class="figure">
<img alt="" src="_images/app_tree.png" />
</div>
<p>We now will link this application to the Django project by opening the
<code class="docutils literal"><span class="pre">settings.py</span></code> file located in the main <code class="docutils literal"><span class="pre">mysite</span></code> directory in a text
editor. Find <code class="docutils literal"><span class="pre">INSTALLED_APPS</span></code>, and we will add our app <code class="docutils literal"><span class="pre">pages</span></code> to
the list as shown.</p>
<div class="figure">
<img alt="" src="_images/pages_app.png" />
</div>
</div>
<div class="section" id="Django-Views">
<h3>Django Views<a class="headerlink" href="#Django-Views" title="Permalink to this headline">¶</a></h3>
<p>Now, we want to add some content to our app, and establish some
connections that allow the content to be seen. In Django, the views
determing the content displayed. We then have to use the urlconfs to
decide where the content goes.</p>
<p>Starting with the views file, lets add the following code:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span>
<span class="c1"># Create your views here.</span>
<span class="k">def</span> <span class="nf">homepageview</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">"<h3>It's So Wonderful to see you Jacob!</h3>"</span><span class="p">)</span>
</pre></div>
</div>
<p>This view will accept a request, and return the HTML header that I’ve
placed in <code class="docutils literal"><span class="pre">HttpResponse()</span></code>. Now, we have to establish the location for
the file using a <code class="docutils literal"><span class="pre">urls</span></code> file. We create a new file in our pages
directory named <code class="docutils literal"><span class="pre">urls.py</span></code>. Here, will use the urlpatterns call and
provide a path to our page. If we want it to be at a page called
<code class="docutils literal"><span class="pre">home</span></code>, we could write the following:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">path</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">views</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">path</span><span class="p">(</span><span class="s1">''</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">homepageview</span><span class="p">,</span> <span class="n">name</span> <span class="o">=</span> <span class="s1">'home'</span><span class="p">)</span>
<span class="p">]</span>
</pre></div>
</div>
<p>This establishes the link within the application, and we need to connect
this to the larger project within the base <code class="docutils literal"><span class="pre">urls.py</span></code> file. This was
already created with our project, and we want it to read as follows:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib</span> <span class="kn">import</span> <span class="n">admin</span>
<span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">path</span><span class="p">,</span> <span class="n">include</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
<span class="n">path</span><span class="p">(</span><span class="s1">'admin/'</span><span class="p">,</span> <span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">urls</span><span class="p">),</span>
<span class="n">path</span><span class="p">(</span><span class="s1">''</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s1">'pages.urls'</span><span class="p">)),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>Now, if we run our server again and navigate to <a class="reference external" href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>
we should see the results of our work.</p>
<div class="figure">
<img alt="" src="_images/wonderfuls.png" />
</div>
</div>
</div>
</div>
</div>
<div class="articleComments">
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="12-Django-templates.html" class="btn btn-neutral float-right" title="Templates and Bootstrap" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
<a href="010-Decision-Trees.html" class="btn btn-neutral" title="Decision Tree Classifiers" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2017, <NAME>.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'./',
VERSION:'7150b89',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: ''
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html><file_sep>/data-design/source/gutenbergplot.py
import matplotlib.pyplot as plt
import requests
import nltk
from bs4 import BeautifulSoup
from nltk.tokenize import RegexpTokenizer
def gutenberg_plot(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
words = soup.get_text()
lowered = []
for word in words:
lowered.append(word.lower())
text = nltk.Text(lowered)
fdist = nltk.FreqDist(text)
fdist.plot(30)
<file_sep>/sphinx_dat/build/html/03-L6.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Completing the Workflow — GA-DAT-3-20 1 documentation</title>
<link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="stylesheet" href="_static/custom.css" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
</head>
<body>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<style>
/* CSS for nbsphinx extension */
/* remove conflicting styling from Sphinx themes */
div.nbinput,
div.nbinput div.prompt,
div.nbinput div.input_area,
div.nbinput div[class*=highlight],
div.nbinput div[class*=highlight] pre,
div.nboutput,
div.nbinput div.prompt,
div.nbinput div.output_area,
div.nboutput div[class*=highlight],
div.nboutput div[class*=highlight] pre {
background: none;
border: none;
padding: 0 0;
margin: 0;
box-shadow: none;
}
/* avoid gaps between output lines */
div.nboutput div[class*=highlight] pre {
line-height: normal;
}
/* input/output containers */
div.nbinput,
div.nboutput {
display: -webkit-flex;
display: flex;
align-items: flex-start;
margin: 0;
width: 100%;
}
@media (max-width: 540px) {
div.nbinput,
div.nboutput {
flex-direction: column;
}
}
/* input container */
div.nbinput {
padding-top: 5px;
}
/* last container */
div.nblast {
padding-bottom: 5px;
}
/* input prompt */
div.nbinput div.prompt pre {
color: #303F9F;
}
/* output prompt */
div.nboutput div.prompt pre {
color: #D84315;
}
/* all prompts */
div.nbinput div.prompt,
div.nboutput div.prompt {
min-width: 8ex;
padding-top: 0.4em;
padding-right: 0.4em;
text-align: right;
flex: 0;
}
@media (max-width: 540px) {
div.nbinput div.prompt,
div.nboutput div.prompt {
text-align: left;
padding: 0.4em;
}
div.nboutput div.prompt.empty {
padding: 0;
}
}
/* disable scrollbars on prompts */
div.nbinput div.prompt pre,
div.nboutput div.prompt pre {
overflow: hidden;
}
/* input/output area */
div.nbinput div.input_area,
div.nboutput div.output_area {
padding: 0.4em;
-webkit-flex: 1;
flex: 1;
overflow: auto;
}
@media (max-width: 540px) {
div.nbinput div.input_area,
div.nboutput div.output_area {
width: 100%;
}
}
/* input area */
div.nbinput div.input_area {
border: 1px solid #cfcfcf;
border-radius: 2px;
background: #f7f7f7;
}
/* override MathJax center alignment in output cells */
div.nboutput div[class*=MathJax] {
text-align: left !important;
}
/* override sphinx.ext.pngmath center alignment in output cells */
div.nboutput div.math p {
text-align: left;
}
/* standard error */
div.nboutput div.output_area.stderr {
background: #fdd;
}
/* ANSI colors */
.ansi-black-fg { color: #3E424D; }
.ansi-black-bg { background-color: #3E424D; }
.ansi-black-intense-fg { color: #282C36; }
.ansi-black-intense-bg { background-color: #282C36; }
.ansi-red-fg { color: #E75C58; }
.ansi-red-bg { background-color: #E75C58; }
.ansi-red-intense-fg { color: #B22B31; }
.ansi-red-intense-bg { background-color: #B22B31; }
.ansi-green-fg { color: #00A250; }
.ansi-green-bg { background-color: #00A250; }
.ansi-green-intense-fg { color: #007427; }
.ansi-green-intense-bg { background-color: #007427; }
.ansi-yellow-fg { color: #DDB62B; }
.ansi-yellow-bg { background-color: #DDB62B; }
.ansi-yellow-intense-fg { color: #B27D12; }
.ansi-yellow-intense-bg { background-color: #B27D12; }
.ansi-blue-fg { color: #208FFB; }
.ansi-blue-bg { background-color: #208FFB; }
.ansi-blue-intense-fg { color: #0065CA; }
.ansi-blue-intense-bg { background-color: #0065CA; }
.ansi-magenta-fg { color: #D160C4; }
.ansi-magenta-bg { background-color: #D160C4; }
.ansi-magenta-intense-fg { color: #A03196; }
.ansi-magenta-intense-bg { background-color: #A03196; }
.ansi-cyan-fg { color: #60C6C8; }
.ansi-cyan-bg { background-color: #60C6C8; }
.ansi-cyan-intense-fg { color: #258F8F; }
.ansi-cyan-intense-bg { background-color: #258F8F; }
.ansi-white-fg { color: #C5C1B4; }
.ansi-white-bg { background-color: #C5C1B4; }
.ansi-white-intense-fg { color: #A1A6B2; }
.ansi-white-intense-bg { background-color: #A1A6B2; }
.ansi-default-inverse-fg { color: #FFFFFF; }
.ansi-default-inverse-bg { background-color: #000000; }
.ansi-bold { font-weight: bold; }
.ansi-underline { text-decoration: underline; }
</style>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [1]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="o">%</span><span class="k">matplotlib</span> inline
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="kn">import</span> <span class="nn">seaborn</span> <span class="k">as</span> <span class="nn">sns</span>
<span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="k">import</span> <span class="n">LinearRegression</span>
<span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="k">import</span> <span class="n">train_test_split</span>
<span class="kn">from</span> <span class="nn">sklearn</span> <span class="k">import</span> <span class="n">cross_validation</span>
<span class="kn">from</span> <span class="nn">sklearn.metrics</span> <span class="k">import</span> <span class="n">mean_squared_error</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="stderr output_area docutils container">
<div class="highlight"><pre>
/anaconda3/lib/python3.6/site-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
"This module will be removed in 0.20.", DeprecationWarning)
</pre></div></div>
</div>
<div class="section" id="Completing-the-Workflow">
<h1>Completing the Workflow<a class="headerlink" href="#Completing-the-Workflow" title="Permalink to this headline">¶</a></h1>
<ul class="simple">
<li>Load and prepare data</li>
<li>Split train and test sets</li>
<li>Build the model</li>
<li>Addition of Cross Validation</li>
<li>Tune the Parameters</li>
<li>Add <code class="docutils literal"><span class="pre">GridSearchCV</span></code></li>
<li>Reflect on the Model</li>
</ul>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [2]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">bikeshare</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span><span class="s1">'data/bikeshare.csv'</span><span class="p">)</span>
<span class="n">weather</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">get_dummies</span><span class="p">(</span><span class="n">bikeshare</span><span class="o">.</span><span class="n">weathersit</span><span class="p">,</span> <span class="n">prefix</span><span class="o">=</span><span class="s1">'weather'</span><span class="p">)</span>
<span class="n">modeldata</span> <span class="o">=</span> <span class="n">bikeshare</span><span class="p">[[</span><span class="s1">'temp'</span><span class="p">,</span> <span class="s1">'hum'</span><span class="p">]]</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">weather</span><span class="p">[[</span><span class="s1">'weather_1'</span><span class="p">,</span> <span class="s1">'weather_2'</span><span class="p">,</span> <span class="s1">'weather_3'</span><span class="p">]])</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">bikeshare</span><span class="o">.</span><span class="n">casual</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [3]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="c1">#split train-test set</span>
<span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">train_test_split</span><span class="p">(</span><span class="n">modeldata</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [7]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="c1">#instantiate, fit, and evaluate the model</span>
<span class="n">lm</span> <span class="o">=</span> <span class="n">LinearRegression</span><span class="p">()</span>
<span class="n">lm</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
<span class="n">predictions</span> <span class="o">=</span> <span class="n">lm</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_train</span><span class="p">)</span>
<span class="n">mse</span> <span class="o">=</span> <span class="n">mean_squared_error</span><span class="p">(</span><span class="n">y_train</span><span class="p">,</span> <span class="n">predictions</span><span class="p">)</span>
<span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">mse</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[7]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>40.78627724056598
</pre></div>
</div>
</div>
<div class="section" id="Cross-Validation">
<h2>Cross-Validation<a class="headerlink" href="#Cross-Validation" title="Permalink to this headline">¶</a></h2>
<p>Rather than using a single training set, we can iterate through a number
of splits of the larger training set itself. One approach is called
K-folds, where we take a separate fold each time through. For example,
if we perform a cross-validation with 5 folds, we would split the
training data 5 times, each time fitting and evaluating a model.</p>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [8]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="k">import</span> <span class="n">cross_val_score</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [9]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">scores</span> <span class="o">=</span> <span class="n">cross_val_score</span><span class="p">(</span><span class="n">lm</span><span class="p">,</span> <span class="n">X_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">scoring</span> <span class="o">=</span> <span class="s2">"neg_mean_squared_error"</span><span class="p">,</span> <span class="n">cv</span> <span class="o">=</span> <span class="mi">5</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [10]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rmse_scores</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="o">-</span><span class="n">scores</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [11]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rmse_scores</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[11]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>array([40.19954311, 40.73731378, 43.32350538, 41.00108099, 38.6145071 ])
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [12]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rmse_scores</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[12]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>40.77519007065239
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [13]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rmse_scores</span><span class="o">.</span><span class="n">std</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[13]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>1.5196244631240068
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [14]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">kf</span> <span class="o">=</span> <span class="n">cross_validation</span><span class="o">.</span><span class="n">KFold</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">modeldata</span><span class="p">),</span> <span class="n">n_folds</span> <span class="o">=</span> <span class="mi">5</span><span class="p">,</span> <span class="n">shuffle</span> <span class="o">=</span> <span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [15]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">mse_values</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">scores</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">n</span><span class="o">=</span> <span class="mi">0</span>
<span class="nb">print</span><span class="p">(</span> <span class="s2">"~~~~ CROSS VALIDATION each fold ~~~~"</span><span class="p">)</span>
<span class="k">for</span> <span class="n">train_index</span><span class="p">,</span> <span class="n">test_index</span> <span class="ow">in</span> <span class="n">kf</span><span class="p">:</span>
<span class="n">lm</span> <span class="o">=</span> <span class="n">LinearRegression</span><span class="p">()</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">modeldata</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="n">train_index</span><span class="p">],</span> <span class="n">y</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="n">train_index</span><span class="p">])</span>
<span class="n">mse_values</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">mean_squared_error</span><span class="p">(</span><span class="n">y</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="n">test_index</span><span class="p">],</span> <span class="n">lm</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">modeldata</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="n">test_index</span><span class="p">])))</span>
<span class="n">scores</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">lm</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">modeldata</span><span class="p">,</span> <span class="n">y</span><span class="p">))</span>
<span class="n">n</span><span class="o">+=</span><span class="mi">1</span>
<span class="nb">print</span><span class="p">(</span> <span class="s1">'Model'</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span> <span class="s1">'MSE:'</span><span class="p">,</span> <span class="n">mse_values</span><span class="p">[</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
<span class="nb">print</span><span class="p">(</span> <span class="s1">'R2:'</span><span class="p">,</span> <span class="n">scores</span><span class="p">[</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
<span class="nb">print</span><span class="p">(</span> <span class="s2">"~~~~ SUMMARY OF CROSS VALIDATION ~~~~"</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span> <span class="s1">'Mean of MSE for all folds:'</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">mse_values</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span> <span class="s1">'Mean of R2 for all folds:'</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">scores</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
~~~~ CROSS VALIDATION each fold ~~~~
Model 1
MSE: 1754.7045797988867
R2: 0.31188643384642
Model 2
MSE: 1767.3528941413747
R2: 0.31188966283358266
Model 3
MSE: 1465.3852307219188
R2: 0.3117009152440636
Model 4
MSE: 1580.3106085711643
R2: 0.31192485666305736
Model 5
MSE: 1803.0062403519232
R2: 0.3119135551998975
~~~~ SUMMARY OF CROSS VALIDATION ~~~~
Mean of MSE for all folds: 1674.1519107170534
Mean of R2 for all folds: 0.3118630847574042
</pre></div></div>
</div>
</div>
<div class="section" id="Grid-Search">
<h2>Grid Search<a class="headerlink" href="#Grid-Search" title="Permalink to this headline">¶</a></h2>
<p>Now, suppose we are using our regularized methods here. We want to be
able to also experiment with parameters and determine something like our
ideal value for <span class="math">\(\alpha\)</span> in the <code class="docutils literal"><span class="pre">Ridge()</span></code> model. We can feed a
list of values to the <code class="docutils literal"><span class="pre">GridSearchCV</span></code> and it will run through the
possible combinations of these using cross validation.</p>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [17]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="k">import</span> <span class="n">Ridge</span>
<span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="k">import</span> <span class="n">GridSearchCV</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [18]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">param_grid</span> <span class="o">=</span> <span class="p">[</span>
<span class="p">{</span><span class="s1">'alpha'</span><span class="p">:</span> <span class="p">[</span><span class="n">alpha</span> <span class="k">for</span> <span class="n">alpha</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">40</span><span class="p">]],</span>
<span class="s1">'fit_intercept'</span><span class="p">:</span> <span class="p">[</span><span class="kc">True</span><span class="p">,</span> <span class="kc">False</span><span class="p">]</span>
<span class="p">}</span>
<span class="p">]</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [19]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">ridge</span> <span class="o">=</span> <span class="n">Ridge</span><span class="p">()</span>
<span class="n">grid</span> <span class="o">=</span> <span class="n">GridSearchCV</span><span class="p">(</span><span class="n">ridge</span><span class="p">,</span> <span class="n">param_grid</span><span class="p">,</span> <span class="n">cv</span> <span class="o">=</span> <span class="mi">5</span><span class="p">,</span> <span class="n">scoring</span> <span class="o">=</span> <span class="s1">'neg_mean_squared_error'</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [20]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">grid</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">modeldata</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[20]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>GridSearchCV(cv=5, error_score='raise',
estimator=Ridge(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=None,
normalize=False, random_state=None, solver='auto', tol=0.001),
fit_params=None, iid=True, n_jobs=1,
param_grid=[{'alpha': [1, 5, 10, 40], 'fit_intercept': [True, False]}],
pre_dispatch='2*n_jobs', refit=True, return_train_score='warn',
scoring='neg_mean_squared_error', verbose=0)
</pre></div>
</div>
</div>
</div>
<div class="section" id="Best-Fit-and-Parameters">
<h2>Best Fit and Parameters<a class="headerlink" href="#Best-Fit-and-Parameters" title="Permalink to this headline">¶</a></h2>
<p>Now, we can investigate the model performance. The <code class="docutils literal"><span class="pre">best_params_</span></code> will
give us the ideal parameters from the search, <code class="docutils literal"><span class="pre">best_estimator_</span></code> gives
the full model information, and <code class="docutils literal"><span class="pre">cv_results_</span></code> will give us full
information including performance for each individual model attempt.</p>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [21]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">grid</span><span class="o">.</span><span class="n">best_params_</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[21]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>{'alpha': 40, 'fit_intercept': False}
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [22]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">grid</span><span class="o">.</span><span class="n">best_estimator_</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[22]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>Ridge(alpha=40, copy_X=True, fit_intercept=False, max_iter=None,
normalize=False, random_state=None, solver='auto', tol=0.001)
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [23]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">results</span> <span class="o">=</span> <span class="n">grid</span><span class="o">.</span><span class="n">cv_results_</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [25]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">results</span> <span class="o">=</span> <span class="nb">zip</span><span class="p">(</span><span class="n">results</span><span class="p">[</span><span class="s1">'mean_test_score'</span><span class="p">],</span> <span class="n">results</span><span class="p">[</span><span class="s1">'params'</span><span class="p">])</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [26]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="k">for</span> <span class="n">mean_score</span><span class="p">,</span> <span class="n">param</span> <span class="ow">in</span> <span class="n">results</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="o">-</span><span class="n">mean_score</span><span class="p">),</span> <span class="n">param</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
42.19907472429994 {'alpha': 1, 'fit_intercept': True}
42.206081583932566 {'alpha': 1, 'fit_intercept': False}
42.18885870516342 {'alpha': 5, 'fit_intercept': True}
42.18488903631506 {'alpha': 5, 'fit_intercept': False}
42.177685282479935 {'alpha': 10, 'fit_intercept': True}
42.162559420472945 {'alpha': 10, 'fit_intercept': False}
42.15168131166849 {'alpha': 40, 'fit_intercept': True}
42.10058388779278 {'alpha': 40, 'fit_intercept': False}
</pre></div></div>
</div>
</div>
<div class="section" id="Split,-Search,-Evaluate">
<h2>Split, Search, Evaluate<a class="headerlink" href="#Split,-Search,-Evaluate" title="Permalink to this headline">¶</a></h2>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [27]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="c1">#train test split</span>
<span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">train_test_split</span><span class="p">(</span><span class="n">modeldata</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [28]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="c1">#Grid Search</span>
<span class="n">grid</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[28]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>GridSearchCV(cv=5, error_score='raise',
estimator=Ridge(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=None,
normalize=False, random_state=None, solver='auto', tol=0.001),
fit_params=None, iid=True, n_jobs=1,
param_grid=[{'alpha': [1, 5, 10, 40], 'fit_intercept': [True, False]}],
pre_dispatch='2*n_jobs', refit=True, return_train_score='warn',
scoring='neg_mean_squared_error', verbose=0)
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [29]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="c1">#Examine results</span>
<span class="n">results</span> <span class="o">=</span> <span class="n">grid</span><span class="o">.</span><span class="n">cv_results_</span>
<span class="n">results</span> <span class="o">=</span> <span class="nb">zip</span><span class="p">(</span><span class="n">results</span><span class="p">[</span><span class="s1">'mean_test_score'</span><span class="p">],</span> <span class="n">results</span><span class="p">[</span><span class="s1">'params'</span><span class="p">])</span>
<span class="k">for</span> <span class="n">mean_score</span><span class="p">,</span> <span class="n">param</span> <span class="ow">in</span> <span class="n">results</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="o">-</span><span class="n">mean_score</span><span class="p">),</span> <span class="n">param</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
40.98472272735398 {'alpha': 1, 'fit_intercept': True}
40.993051745843275 {'alpha': 1, 'fit_intercept': False}
40.98670862275685 {'alpha': 5, 'fit_intercept': True}
40.99515030170469 {'alpha': 5, 'fit_intercept': False}
40.99117397282172 {'alpha': 10, 'fit_intercept': True}
41.0014927424939 {'alpha': 10, 'fit_intercept': False}
41.06618466313504 {'alpha': 40, 'fit_intercept': True}
41.100071639455365 {'alpha': 40, 'fit_intercept': False}
</pre></div></div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [30]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">grid</span><span class="o">.</span><span class="n">best_estimator_</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[30]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>Ridge(alpha=1, copy_X=True, fit_intercept=True, max_iter=None,
normalize=False, random_state=None, solver='auto', tol=0.001)
</pre></div>
</div>
</div>
</div>
<div class="section" id="Fit-on-Test">
<h2>Fit on Test<a class="headerlink" href="#Fit-on-Test" title="Permalink to this headline">¶</a></h2>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [31]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">model</span> <span class="o">=</span> <span class="n">Ridge</span><span class="p">(</span><span class="n">alpha</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">copy_X</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">fit_intercept</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">max_iter</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="n">normalize</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">random_state</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">solver</span><span class="o">=</span><span class="s1">'auto'</span><span class="p">,</span> <span class="n">tol</span><span class="o">=</span><span class="mf">0.001</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [32]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">model</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_test</span><span class="p">,</span> <span class="n">y_test</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[32]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>Ridge(alpha=1, copy_X=True, fit_intercept=True, max_iter=None,
normalize=False, random_state=None, solver='auto', tol=0.001)
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [33]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">model</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">X_test</span><span class="p">,</span> <span class="n">y_test</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[33]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>0.3130531123834813
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [34]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">predictions</span> <span class="o">=</span> <span class="n">model</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
<span class="n">mse</span> <span class="o">=</span> <span class="n">mean_squared_error</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">predictions</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [35]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rmse</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">mse</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [36]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">rmse</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>Out[36]:
</pre></div>
</div>
<div class="output_area highlight-none"><div class="highlight"><pre>
<span></span>40.65424810846637
</pre></div>
</div>
</div>
</div>
<div class="section" id="California-Housing">
<h2>California Housing<a class="headerlink" href="#California-Housing" title="Permalink to this headline">¶</a></h2>
<p>The dataset comes from sklearn’s dataset library. We want to perform an
end to end modeling project where we predict the median house value in a
district. You should follow a workflow similar to what we’ve encountered
to this point, and may go something like:</p>
<ul class="simple">
<li>Investigate variable types and distributions</li>
<li>Transformations?</li>
<li>Collinearity?</li>
<li>New Features?</li>
<li>Perhaps something like Rooms per Household, Bedrooms per Room,
Population per Household</li>
<li>Missing Values?</li>
<li>Examine total bedrooms; drop the districts, delete the attribute, or
fill values with sensible number (like median) <code class="docutils literal"><span class="pre">.fillna()</span></code></li>
<li>Encode any Categorical Variables</li>
<li>Feature Scaling? (<code class="docutils literal"><span class="pre">MaxMinScaler</span></code> or <code class="docutils literal"><span class="pre">StandardScaler</span></code>)</li>
<li>Prepare numerical data</li>
<li>Split Train and Test Set</li>
<li>Use Cross Validation and Grid Search to explore models on training
set</li>
<li>Determine best model and evaluate on Test set</li>
<li>Communicate your results including a visualization of the locations
of the houses, colored by their median house value and sized by
population (<code class="docutils literal"><span class="pre">plt.scatter</span></code>)</li>
</ul>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [51]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">cali_houses</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span><span class="s1">'data/cali_housing.csv'</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [52]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">cali_houses</span><span class="o">.</span><span class="n">info</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 20640 entries, 0 to 20639
Data columns (total 11 columns):
Unnamed: 0 20640 non-null int64
longitude 20640 non-null float64
latitude 20640 non-null float64
housing_median_age 20640 non-null float64
total_rooms 20640 non-null float64
total_bedrooms 20433 non-null float64
population 20640 non-null float64
households 20640 non-null float64
median_income 20640 non-null float64
median_house_value 20640 non-null float64
ocean_proximity 20640 non-null object
dtypes: float64(9), int64(1), object(1)
memory usage: 1.7+ MB
</pre></div></div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [57]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">cali_houses</span> <span class="o">=</span> <span class="n">cali_houses</span><span class="o">.</span><span class="n">fillna</span><span class="p">(</span><span class="n">cali_houses</span><span class="o">.</span><span class="n">median</span><span class="p">())</span>
</pre></div>
</div>
</div>
<div class="nbinput nblast docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [55]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">cali_houses</span><span class="p">[</span><span class="s1">'bed_something'</span><span class="p">]</span> <span class="o">=</span> <span class="n">cali_houses</span><span class="p">[</span><span class="s1">'total_rooms'</span><span class="p">]</span> <span class="o">*</span> <span class="n">cali_houses</span><span class="p">[</span><span class="s1">'total_bedrooms'</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="nbinput docutils container">
<div class="prompt highlight-none"><div class="highlight"><pre>
<span></span>In [56]:
</pre></div>
</div>
<div class="input_area highlight-ipython3"><div class="highlight"><pre>
<span></span><span class="n">cali_houses</span><span class="o">.</span><span class="n">info</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="nboutput nblast docutils container">
<div class="prompt empty docutils container">
</div>
<div class="output_area docutils container">
<div class="highlight"><pre>
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 20640 entries, 0 to 20639
Data columns (total 12 columns):
Unnamed: 0 20640 non-null int64
longitude 20640 non-null float64
latitude 20640 non-null float64
housing_median_age 20640 non-null float64
total_rooms 20640 non-null float64
total_bedrooms 20640 non-null float64
population 20640 non-null float64
households 20640 non-null float64
median_income 20640 non-null float64
median_house_value 20640 non-null float64
ocean_proximity 20640 non-null object
bed_something 20640 non-null float64
dtypes: float64(10), int64(1), object(1)
memory usage: 1.9+ MB
</pre></div></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper"><div class="relations">
<h3>Related Topics</h3>
<ul>
<li><a href="index.html">Documentation overview</a><ul>
</ul></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
©2018, <NAME>.
|
Powered by <a href="http://sphinx-doc.org/">Sphinx 1.6.6</a>
& <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a>
|
<a href="_sources/03-L6.ipynb.txt"
rel="nofollow">Page source</a>
</div>
</body>
</html><file_sep>/GA/GA-02-Modeling/README.md
# Lesson Materials and Topic
### [Lesson 3: Introduction to Pandas and Matplotlib](https://github.com/jfkoehler/GA-errata)
**GOALS**:
- Use Pandas to explore data
- Use Plots to explore data
- Perform basic descriptive statistics on data
### [Lesson 4: Introduction to Linear Regression](https://github.com/jfkoehler/GA-regression)
**GOALS**:
- Introduce predictive modeling with Least Squares Models
- Implement Linear Regression with StatsModels and Numpy
- Transform non-linear data to linear models with logarithmic transformations and perform linear fit
### [Lesson 5: Improving the Model](https://github.com/jfkoehler/GA-02-Modeling)
**GOALS**:
- Examine multiple features with regression
- Code categorical variables and interpret with regression
- Examine polynomial regression
- Understand Collinearity
- Assess model using Train/Test split
- Scale features with `MaxMinScaler` and `StandardScaler`
- Use `Lasso`, 'Ridge`, and `ElasticNet` models
**Resources**:
- [<NAME> Lectures on Regularized Methods]()
- [University of Michigan Lectures on Regularized Methods]()
- [An Introduction to Statistical Learning](): chapter on linear regression
- [SciKitLearn Documentation on Regression]()
- [JVDP on Regression]()
### [Lesson 6: Cross Validation and Grid Search](https://github.com/jfkoehler/GA-Cross-Validation)
**GOALS**:
- Use cross validation to build models on training data
- Use grid search to tune hyperparameters of models
- Determine best model based on grid search results
**Resources**:
- [An Introduction to Statistical Learning](): Chapter on Cross-Validation
- [Hands on Machine Learning](): Jupyter Notebook covering Cross-Validation and Grid Search
- [<NAME> on Cross Validation]()
- [University of Michigan Lecture on Cross-Validation]()
- [SciKitLearn Documentation on Cross-Validation]()
### [Lesson 7: Introduction to Classification: KMeans and KNN](https://github.com/jfkoehler/GA-Clustering-I)
**GOALS**:
- Understand the nature of Classification Problems with Clustering
- Use `KNearestNeighbors` to understand classification of data
- Evaluate model with accuracy
### [Lesson 8: Classification with Logistic Regression](https://github.com/jfkoehler/GA-Logistic-Regression)
**GOALS**
- Understand Logistic Regression and binary classification
- Use `LogisticRegression` to examine probability of class inclusion
- Introduce metrics for model evaluation from `confusion_matrix`
**Resources**
- [An Introduction to Statistical Learning](): Chapter on Logistic Regression
- [JVDP on CLassification]()
- [<NAME> on Classification]()
- [<NAME>-Mustafa of CalTech](https://www.youtube.com/watch?v=FIbVs5GbBlQ&hd=1): Lecture on Linear models.
### [Lesson 9: Model Evaluation and Interpretation](https://github.com/jfkoehler/GA-Classification-Evaluation)
**GOALS**:
- Review evaluation metrics for Classification
- Introduce ROC and AUC plots
- Presentations and Assignment 4
### [Lesson 10: Gradient Descent in Regression and Classification](https://github.com/jfkoehler/GA-Model-Selection)
**GOALS**
- Investigate Regression Evaluation and compare methods
- Understand the difference between gradient descent and closed form solutions to optimization problems
- Compare scenarios for using Gradient Descent and evaluate implementation in sklearn
- Review Cross-Validation and Grid Search: Select Best Model
### [Lesson 11: Web Scraping API's](https://github.com/jfkoehler/GA-scrape-NLTK)
**GOALS**
- Use Requests and BeautifulSoup to extract data from the web
- Use API's to access data
[notebook link II](https://github.com/ga-students/DAT-NYC-3.20.18/tree/master/lessons/working-with-api-data)
**Resources**:
- [Requests Documentation](http://docs.python-requests.org/en/master/)
- [Beautiful Soup Documentation](https://www.crummy.com/software/BeautifulSoup/)
- [Webscraping Trump](https://www.youtube.com/watch?v=r_xb0vF1uMc): <NAME>'s tutorial on scraping and structuring a New York Times article on Donald Trump.
- [PythonProgramming.net Tutorial](https://pythonprogramming.net/introduction-scraping-parsing-beautiful-soup-tutorial/)
### [Lesson 12: NLP and Text Classification](https://github.com/jfkoehler/GA-NLP)
**GOALS**
- Use advanced NLTK strategies to investigate product reviews
- Use and understand Naive Bayes for text classification
- Use Twitter API to investigate tweet content
**Resources**:
- [NLTK Book]()
- [NLTK Lectures from University of Michigan]()
- [<NAME>' Notebook on Naive Bayes]()
- []()
### [Lesson 13: Decision Trees](https://github.com/jfkoehler/GA-DecisionTrees/blob/master/README.md)
**GOALS**
- Use Decision Trees to investigate classification and regression problems
### [Lesson 14: Random Forest Models and Ensemble Methods](https://github.com/jfkoehler/GA-Ensembles)
**GOALS**
- Use Random Forrest models to ensemble methods
### [Lesson 15: Timeseries I](https://github.com/jfkoehler/GA-Time-Series)
### [Lesson 16: Working with Databases](https://github.com/jfkoehler/GA-Database-FeatureSelect)
### [Lesson 17: Feature Selection, Pipelines, and Evaluation](https://github.com/jfkoehler/Pipelines-and-Pickles)
### [Lesson 18: Introduction to Neural Networks](https://github.com/jfkoehler/GA-FLASK)
## Additional Resources
For more information on this topic, check out:
- [The Flask Documentation](http://flask.pocoo.org/docs/0.11/)
- [A Flask tutorial to follow along with](https://github.com/miguelgrinberg/flask-pycon2014)
- [Another tutorial that gets into CSS styling](https://code.tutsplus.com/tutorials/an-introduction-to-pythons-flask-framework--net-28822)
- [The Flask mega tutorial](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates)
- [Flask's development server is not for production](https://stackoverflow.com/questions/12269537/is-the-server-bundled-with-flask-safe-to-use-in-production)
- [Setting up Flask on AWS EC2](http://bathompso.com/blog/Flask-AWS-Setup/). This should be your next step if you want to share your model with the world!
- [A great guide to those weird "decorators"](http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/).
### Production coding
- Add [logging](https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/) to your code; you'll be very glad you did.
- Think ahead and include [error handling](https://eli.thegreenplace.net/2008/08/21/robust-exception-handling/), via [try/except clauses](https://jeffknupp.com/blog/2013/02/06/write-cleaner-python-use-exceptions/)
- Get more comfortable with git, including [feature branching](https://www.atlassian.com/git/tutorials/comparing-workflows/feature-branch-workflow).
- Include [unit tests](http://www.diveintopython.net/unit_testing/index.html); the [pytest module](http://pythontesting.net/framework/pytest/pytest-introduction/) is great.
- [Integrate databases](http://zetcode.com/db/sqlitepythontutorial/)!
- Beware technical debt, especially [machine learning technical debt](https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43146.pdf).
## In Course Projects
- [Project I](https://github.com/ga-students/DAT-NYC-3.20.18/tree/master/projects/unit-projects/project-1)
- [Project II](https://github.com/jfkoehler/GA-regression)
- [Project III: Final Project Part I](https://github.com/jfkoehler/GA-Cross-Validation/blob/master/Final-Project-1.ipynb)
- [Project IV: Modeling Project I](projectIII.md)
<file_sep>/GA/GA-errata/README.md
## Extra Materials for GA-DAT-3.20
In case you wanted more.
### Weekly Extras
- **Week I**:
- [Introduction to NumPy and Matplotlib](): Numpy Cheatsheet
- [Introduction to Pandas](): Pandas Cheatsheet
- [Customizing Matplotlib](): Matplotlib Cheatsheet
<file_sep>/GA/GA-Cross-Validation/README.md
### Day 6: Searching for the Best Model
Today we fill out our conversations on the `LinearRegression` model and regularized
methods.
<file_sep>/GA/GA-DecisionTrees/README.md
# Project EDA
Exploratory data analysis is a crucial step in any data workflow. Create a Jupyter Notebook that explores your data mathematically and visually. Explore features, apply descriptive statistics, look at distributions, and determine how to handle sampling or any missing values.
Requirements:
1. Create an exploratory data analysis notebook.
2. Perform statistical analysis, along with any visualizations.
3. Determine how to handle sampling or missing values.
4. Clearly identify shortcomings, assumptions, and next steps.
Submission:
Due Tuesday May 8.
|
2302024eed4169ab161e4205f8acfa4c8ba50b65
|
[
"Markdown",
"Python",
"HTML",
"reStructuredText"
] | 17
|
reStructuredText
|
YStrano/ds_jk
|
ca4aab143b0574b623ba59c32700f355302d66e5
|
73fb0ef6a3846f3221909a1e7b486acf930532aa
|
refs/heads/main
|
<file_sep>server.port=8081
spring.application.name=user-service
eureka.instance.hostname=localhost<file_sep>package org.snapdeal.spring_boot_CRUD.controller;
import java.util.List;
import org.snapdeal.spring_boot_CRUD.entity.StudentEntity;
import org.snapdeal.spring_boot_CRUD.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("/home")
public String home()
{
return "this is my home page";
}
@RequestMapping(value="/search/{roll}",method=RequestMethod.GET)
public String search(@PathVariable int roll)
{
return "You have entered roll = "+roll;
}
@RequestMapping(value="/find",method=RequestMethod.POST)
public String findByName(@RequestBody String name)
{
return "You have entered name = "+name;
}
@RequestMapping("/all")
public List<StudentEntity> getStudents()
{
return studentService.getStudents(null);
}
@PostMapping("/add")
public String addStudent(@RequestBody StudentEntity studentEntity)
{
return studentService.addStudent(studentEntity);
}
@PostMapping("/bulkAdd")
public String addStudents(@RequestBody List<StudentEntity> studentEntities)
{
return studentService.addStudents(studentEntities);
}
@DeleteMapping("/del/{roll}")
public String deleteStudent(@PathVariable int roll)
{
return studentService.deleteStudent(roll);
}
@PutMapping("/update")
public String updateStudent(@RequestBody StudentEntity studentEntity)
{
return studentService.updateStudent(studentEntity);
}
@RequestMapping("/get/{roll}")
public StudentEntity getStudent(@PathVariable int roll)
{
return studentService.getStudent(roll);
}
}
<file_sep>package org.snapdeal.spring_boot_CRUD.controller;
import java.util.List;
import org.snapdeal.spring_boot_CRUD.entity.StudentEntity;
import org.snapdeal.spring_boot_CRUD.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping("/add")
public String addStudent(@RequestBody StudentEntity studentEntity)
{
return studentService.addStudent(studentEntity);
}
@PostMapping("/bulkAdd")
public String addStudents(@RequestBody List<StudentEntity> studentEntities)
{
return studentService.addStudents(studentEntities);
}
@DeleteMapping("/del/{roll}")
public String deleteStudent(@PathVariable int roll)
{
return studentService.deleteStudent(roll);
}
@PutMapping("/update")
public String updateStudent(@RequestBody StudentEntity studentEntity)
{
return studentService.updateStudent(studentEntity);
}
@RequestMapping("/get/{roll}")
public StudentEntity getStudent(@PathVariable int roll)
{
return studentService.getStudent(roll);
}
}
<file_sep>package org.snapdeal.spring_boot_CRUD.dao;
import org.snapdeal.spring_boot_CRUD.entity.StudentEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentDAO extends JpaRepository<StudentEntity,Integer>
{
}
<file_sep>spring.datasource.url = jdbc:mysql://localhost:3306/youtube
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
<file_sep>package com.user.userservice.service;
import com.user.userservice.entity.User;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
@Service
public class UserServiceImpl implements UserService{
List<User> list= List.of(
new User(101L,"Kamal","1234"),
new User(102L,"Raj","1235"),
new User(103L,"Dinkar","1236")
);
@Override
public User getUser(Long id) {
for(int i=0;i<list.size();i++)
{
if(list.get(i).getUserId()==id)
{
return list.get(i);
}
}
return null;
}
}
<file_sep>package org.demo.hostel_project_spring_boot.controller;
import org.demo.hostel_project_spring_boot.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class HostelController {
@Bean
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}
@Autowired
private RestTemplate restTemplate;
static final String STUDENT_URL_MS="http://localhost:8085/";
@GetMapping("/find/{roll}")
public String fetchStudent(@PathVariable int roll)
{
ResponseEntity<Student> student=restTemplate.exchange(STUDENT_URL_MS+"get/"+roll,HttpMethod.GET,null,Student.class);
System.out.println("Student from Student Report Project "+student);
//return restTemplate.exchange(STUDENT_URL_MS+"get/"+roll, HttpMethod.GET,null,String.class).getBody();
return restTemplate.getForObject(STUDENT_URL_MS+"get/"+roll,String.class);
}
@GetMapping("/findAll")
public String fetchStudent()
{
return restTemplate.exchange(STUDENT_URL_MS+"all",HttpMethod.GET,null,String.class).getBody();
}
@PostMapping("/addStudent")
public String addStudent(@RequestBody Student student)
{
return restTemplate.postForObject(STUDENT_URL_MS+"add", student, String.class);
}
//localhost:8085/get/1111
}
<file_sep>server.port=8082
spring.application.name=contact-service
eureka.instance.hostname=localhost<file_sep>package com.contact.contactservice.service;
import com.contact.contactservice.entity.Contact;
import java.util.List;
public interface ContactService {
public List<Contact> getContactsOfUser(Long userId);
}
|
fd21712111e3e338904e8c8da0aff7c73afcfaa6
|
[
"Java",
"INI"
] | 9
|
INI
|
krdinkar15/SpringBoot
|
2cd2e1fb8292678ee11cb6fdfe4e6d8a4a3e03c5
|
90a0f1baf8dfea88262cb57f092dc28163e73cf8
|
refs/heads/master
|
<file_sep><body>
<header><h1><NAME></h1></header>
<main>
<h1>About Me</h1>
<img src="/plandemo/images/logo.png" alt="This is my logo" width="150" height="150"><h1><NAME></h1>
<aside>
<?php
echo "<h2>Family</h2>";
echo "I have 4 beautiful children and a very hard working husband<br>";
echo "<h2>Career</h2>";
echo "I work at an insurance software company called Xactware<br>";
echo "<h2>Hobbies</h2>";
echo "I like to play the guitar";
?>
</main>
<footer>
</footer>
</body>
</html>
|
f39cd91dae416e2e73e21da584f4df8fec7559f0
|
[
"PHP"
] | 1
|
PHP
|
OgdenStephanie/CS313StephOgden
|
689a2e5c7ecc3b539257f7bbe39639cfeee756f6
|
8ae59dcc4dd2e66f427d436c959d7a17cc61efa5
|
refs/heads/master
|
<repo_name>radoslav-petrov/Shop_Products<file_sep>/Shop_Products/Shop_Products/MySQL/procedure.sql
DELIMITER $$
DROP PROCEDURE IF EXISTS `shop`.`setFinalPrice` $$
CREATE PROCEDURE `shop`.`setFinalPrice` (IN mult DOUBLE)
BEGIN
DECLARE a, c DOUBLE;
DECLARE b INT;
DECLARE cur1 CURSOR FOR SELECT a_price FROM data;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1;
OPEN cur1;
SET b = 0;
WHILE b = 0 DO
FETCH cur1 INTO a;
IF b = 0 THEN
SET c = a * mult;
UPDATE data SET f_price = c WHERE a_price = a;
END IF;
END WHILE;
CLOSE cur1;
END $$
DELIMITER ;
|
16535d472469592cb4e5a4c127750f9a1e96cb52
|
[
"SQL"
] | 1
|
SQL
|
radoslav-petrov/Shop_Products
|
bb618c9e640f277d48ef6bd8d37749bccf1cb014
|
b94f3b64d9e5082f814c118460682b84a7b9fbd9
|
refs/heads/main
|
<repo_name>Zubs/Efico<file_sep>/app/Http/Controllers/AdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\User;
use App\Models\News;
use App\Models\Training;
use App\Models\Trainee;
use App\Notifications\NewAdmin;
class AdminController extends Controller
{
// Requires authentication to view the pages
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return redirect()->route('home');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function all()
{
$admins = User::all();
return view('admin.index')->with('admins', $admins);
}
public function news()
{
$news = News::all();
return view('admin.news')->with('news', $news);
}
public function trainings()
{
$news = Training::all();
return view('admin.trainings')->with('news', $news);
}
public function trainees()
{
$news = Trainee::all();
return view('admin.trainees')->with('news', $news);
}
/**
* Show the form for creating a new admin.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'email' => 'required',
'role' => 'required',
]);
$admin = new Admin;
$admin->uuid = (string) Str::uuid();
$admin->email = $request->email;
$admin->role = $request->role;
$admin->save();
// I'd be writing a mail to the admin to let them know they've been made admin, and also to make them set password;
$admin->notify(new NewAdmin($admin->role));
return redirect()->route('admin.index')->with('success', 'Admin Added Successfully');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$admin = Admin::find($id);
$admin->delete();
return redirect('admin.index')->with('success', 'Admin Removed Successfully');
}
}
<file_sep>/app/Http/Controllers/TraineeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Trainee;
use App\Models\Training;
class TraineeController extends Controller
{
// Requires authentication to view the pages
public function __construct()
{
$this->middleware('auth')->except(['register']);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$trainees = Trainee::orderBy('created_at', 'desc')->paginate(30);
return view('trainee.index');
}
/**
* Show the form for creating a new resource by an admin.
*
* @return \Illuminate\Http\Response
*/
public function register()
{
$trainings = Training::all();
return view('trainee.register')->with('trainings', $trainings);
}
/**
* Show the form for creating a new resource by the user.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('trainee.create');
}
/**
* Store a newly created resource, by the admin in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'training_id' => 'required',
]);
$trainee = new Trainee;
$trainee->name = $request->name;
$trainee->email = $request->email;
$trainee->training_id = $request->training_id;
$trainee->save();
// The trainee should get a mail of successful registration with link to set password
return redirect()->route('trainee.index');
}
/**
* Store a newly created resource, by the user in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function postRegister(Request $request)
{
// return [$request->name, $request->email, $request->training_id];
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'training_id' => 'required',
]);
$trainee = new Trainee;
$trainee->name = $request->name;
$trainee->email = $request->email;
$trainee->training_id = $request->training_id;
$trainee->save();
// The trainee should get a mail of successful registration with link to set password
return redirect()->route('admin.trainees');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/public/js/index.js
var icon = document.getElementById("nav-icon");
var nav = document.getElementById("nav");
icon.addEventListener("click", function(){
nav.classList.toggle("open")
})
const carouselImages = document.querySelector('.carousel_images');
const carouselButtons = document.querySelectorAll('.carousel_button');
const numberOfImages = document.querySelectorAll('.carousel_images img').length;
const splash = document.querySelector('.splash');
let imageIndex = 1;
let translateX = 0;
document.addEventListener('DOMContentLoaded', (e)=>{
setTimeout(()=>{
splash.classList.add('display-none');
}, 2000);
})
setInterval(() =>{
if(imageIndex !== numberOfImages) {
imageIndex++;
translateX -= 300;
}else{
if(imageIndex === numberOfImages) {
imageIndex++;
translateX += (numberOfImages - 1) * 300;
}
}
// let translateX = translateX + 300;
carouselImages.style.transform = `translateX(${translateX}px)`;
}, 30000);
carouselButtons.forEach(button => {
button.addEventListener('click', event => {
if(event.target.id === 'previous') {
if(imageIndex !== 1){
imageIndex--;
translateX += 300;
}
}
else{
if(imageIndex !== numberOfImages) {
imageIndex++;
translateX -= 300;
}
}
carouselImages.style.transform = `translateX(${translateX}px)`;
});
})
<file_sep>/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\NewsController;
use App\Http\Controllers\PagesController;
use App\Http\Controllers\TraineeController;
use App\Http\Controllers\TrainingController;
use App\Http\Controllers\SubscribersController;
use App\Http\Controllers\CommentsController;
/*
|--------------------------------------------------------------------------
| 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!
|
*/
// Static routes
Route::get('/', [PagesController::class, 'index'])->name('index');
Route::get('/about', [PagesController::class, 'about'])->name('about');
Route::get('/contact', [PagesController::class, 'contact'])->name('contact');
Route::post('/contact', [PagesController::class, 'submitContact'])->name('submitContact');
Route::get('/faqs', [PagesController::class, 'faqs'])->name('faqs');
Route::get('/services', [PagesController::class, 'services'])->name('services');
Route::get('/trainings', [PagesController::class, 'trainings'])->name('trainings');
Route::post('/subscribe', [SubscribersController::class, 'store'])->name('subscribe');
// Admin routes
Route::group([
'prefix' => '/admin',
'as' => 'admin.',
], function () {
Route::get('/', [AdminController::class, 'index'])->name('index');
Route::post('/', [AdminController::class, 'store'])->name('store');
Route::get('/all', [AdminController::class, 'all'])->name('all');
Route::get('/news', [AdminController::class, 'news'])->name('news');
Route::get('/trainings', [AdminController::class, 'trainings'])->name('trainings');
Route::get('/trainees', [AdminController::class, 'trainees'])->name('trainees');
Route::get('/delete/{uuid}', [AdminController::class, 'delete'])->name('delete');
});
// News routes
Route::group([
'prefix' => '/news',
'as' => 'news.',
], function () {
Route::get('/', [NewsController::class, 'index'])->name('index');
Route::post('/', [NewsController::class, 'store'])->name('store');
Route::get('/new', [NewsController::class, 'create'])->name('new');
Route::get('/{slug}', [NewsController::class, 'show'])->name('show');
Route::get('/update/{uuid}', [NewsController::class, 'edit'])->name('edit');
Route::post('/update/{uuid}', [NewsController::class, 'update'])->name('update');
Route::get('/delete/{uuid}', [NewsController::class, 'delete'])->name('delete');
});
// Comments routes
Route::group([
'prefix' => '/comments',
'as' => 'comments.',
], function () {
Route::post('/store', [CommentsController::class, 'store'])->name('store');
});
// Trainee routes
Route::group([
'prefix' => '/trainee',
'as' => 'trainee.',
], function () {
Route::get('/', [TraineeController::class, 'index'])->name('index');
Route::get('/new', [TraineeController::class, 'create'])->name('new');
Route::post('/', [TraineeController::class, 'store'])->name('store');
Route::get('/register', [TraineeController::class, 'register'])->name('register');
Route::post('/register', [TraineeController::class, 'postRegister'])->name('postRegister');
});
// Training routes
Route::group([
'prefix' => '/training',
'as' => 'training.',
], function () {
Route::get('/', [TrainingController::class, 'index'])->name('index');
Route::post('/', [TrainingController::class, 'store'])->name('store');
Route::get('/new', [TrainingController::class, 'create'])->name('new');
Route::get('/{id}', [TrainingController::class, 'show'])->name('show');
Route::get('/update/{id}', [TrainingController::class, 'edit'])->name('edit');
Route::post('/update/{id}', [TrainingController::class, 'update'])->name('update');
Route::get('/delete/{uuid}', [TrainingController::class, 'delete'])->name('delete');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
<file_sep>/app/Http/Controllers/PagesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Training;
use App\Notifications\NewMessage;
class PagesController extends Controller
{
/**
* Displays the landing page sha
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('static.index');
}
/**
* Displays the faqs page
*
* @return \Illuminate\Http\Response
*/
public function faqs()
{
return view('static.faq');
}
/**
* Displays the services page
*
* @return \Illuminate\Http\Response
*/
public function services()
{
return view('static.service');
}
public function trainings()
{
$trainings = Training::orderBy('created_at', 'asc')->get();
return view('static.trainings')->with('trainings', $trainings);
}
/**
* Display the about page
*
* @return \Illuminate\Http\Response
*/
public function about()
{
return view('static.about');
}
/**
* Displays the contact page
*
* @return \Illuminate\Http\Response
*/
public function contact()
{
return view('static.contact');
}
/**
* Saves the data from the contact page and returns a thank you page
*
* @return \Illuminate\Http\Response
*/
public function submitContact(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'message' => 'required',
]);
$message = [
'name' => $request->name,
'email' => $request->email,
'message' => $request->message,
];
// David should get both a notification and a mail sha, from the guest
$admin = User::first();
$admin->notify(new NewMessage($message));
return view('static.thanks');
}
}
<file_sep>/app/Http/Controllers/TrainingController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Training;
use App\Models\Trainee;
use App\Models\Subscribers;
use Illuminate\Support\Str;
class TrainingController extends Controller
{
// Requires authentication to view the pages
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$trainings = Training::orderBy('created_at', 'desc')->paginate(15);
return view('training.index')->with('trainings', $trainings);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('training.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'price' => 'required',
'description' => 'required',
'cover_image' => 'image|max:2999',
]);
// Check if training name isn't taken, to avoid errors
$test = Training::where('name', $request->name)->first();
if ($test) {
return back()->with('danger', 'Training Name Is Taken');
}
/*
Image process here, kinda seems like it's being repeated through the app.
*/
//Get uploaded image name
$cover_image = $request->file('cover_image')->getClientOriginalName();
//Get just name, without the extension
$image_name = pathinfo($cover_image, PATHINFO_FILENAME);
//Get just extension, without the name
$image_extension = $request->file('cover_image')->getClientOriginalExtension();
//How it'll be stored
$final_image = $image_name.'_'.time().'.'.$image_extension;
//Upload image
$path = $request->file('cover_image')->storeAs('public/images/training/cover_images', $final_image);
$training = new Training;
$training->name = $request->name;
$training->uuid = (string) Str::uuid();
$training->price = $request->price;
$training->description = $request->description;
$training->cover_image = $final_image;
$training->save();
// All trainees and subscribers should get a mail to let them know of the new training
$trainees = Trainee::all();
$subscribers = Subscribers::all();
// foreach ($trainees as $key) {
// $key->notify(new NewTraining());
// }
// foreach ($subscribers as $key) {
// $key->notify(new NewTraining());
// }
return redirect()->route('trainings');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$training = Training::find($id);
return view('training.show')->with('training', $training);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
return view('training.edit');
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
return redirect()->route('training.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function delete($uuid)
{
$training = Training::where('uuid', $uuid)->first();
$training->delete($uuid);
return redirect()->route('admin.trainings')->with('success', 'Training Deleted Successfully');
}
}
<file_sep>/README.md
# Efico
## Some Simple Rules
* An admin, the director or whoever else he makes an admin, can make add new people to the site and assign roles to them.
* A writer can only write, edit and delete articles.
* The PM, Mike or whoever else is made a PM, can create new trainings and and new trainees.
* The admin can perform all tasks on the site.
## Tech Stacks
* HTML
* CSS
* Laravel
* Flask
## Contributors
* [<NAME>](https://github.com/Zubs)
* [<NAME>](https://github.com/Harithmetic1)
* [<NAME>](https://github.com/Babatunde13)<file_sep>/app/Models/Trainee.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class Trainee extends Model
{
use HasFactory, Notifiable;
public function training() {
return $this->belongsTo('App\Models\Training');
}
}
<file_sep>/app/Http/Controllers/CommentsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comments;
class CommentsController extends Controller
{
// Only an authenticated admin can delete comments
// public function __construct()
// {
// $this->middleware('auth')->except(['store']);
// }
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'message' => 'required',
'name' => 'required',
'id' => 'required',
]);
$comment = new Comments;
$comment->name = $request->name;
$comment->message = $request->message;
$comment->news_id = $request->id;
$comment->save();
return back();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Comments::delete($id);
return back();
}
}
<file_sep>/app/Http/Controllers/SubscribersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Subscribers;
use App\Notifications\WelcomeToEfico;
class SubscribersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'email' => ['required', 'string', 'email', 'max:255',],
]);
$user = new Subscribers;
$user->email = $request->email;
$user->save();
// // Write Mail To Users;
if($user->notify(new WelcomeToEfico())) {
return back();
}
return $user->email;
}
}
<file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Training;
use App\Models\Trainee;
use App\Models\News;
use App\Models\Comments;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$trainings = Training::all();
if (Auth::user()->role == 'admin') {
$trainings = Training::withCount('trainee')->orderBy('trainee_count', 'DESC')->take(4)->get();
return view('admin.home')->with('trainings', $trainings);
} elseif (Auth::user()->role == 'writer') {
$posts = News::all();
$comments = Comments::all();
return view('admin.writer')->with([
'posts' => $posts,
'comments' => $comments,
]);
} elseif (Auth::user()->role == 'pm') {
return view('admin.pm');
} else {
return redirect()->route('index');
};
}
}
<file_sep>/app/Models/Training.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class Training extends Model
{
use HasFactory, Notifiable;
public function trainee() {
return $this->hasMany('App\Models\Trainee');
}
}
|
b80d27db72c42118bfe4abe3d0f21f48bf5a1bce
|
[
"JavaScript",
"Markdown",
"PHP"
] | 12
|
PHP
|
Zubs/Efico
|
a0c45c35f631e316e3033721665a8be58438b59d
|
554a456b3d42b32e57d1018710dbe46ad4c3c236
|
refs/heads/master
|
<repo_name>Gor027/Poset<file_sep>/docs/notes.txt
-1pt for "ignoring globals in C interface?"
to avoid? there's something on moodle for that, I guess
-1pt for storing in posets more than 1 instance of specific string??
to avoid? ..
interface file:
include guards (seem. actual, not #pragma once)
name mangling? -> extern "C" in include for a proper C interface
namespaces?
bool: different in C and C++, like #ifdef _cplusplus??
also, different libraries (like <cstdlib> and <stdlib.h>)
also,
use .find instead of .at, if used .find prev.
anonymous namespaces -> allows to hide stuff from "meta-global" namespace
:: NDEBUG need only toggle cerr? and assert, nothing more
on unordered containers: yes?
no pollution in .h, like using namespace;
<file_sep>/makefile/Makefile
poset.o: ../src/poset.cc
g++ -Wall -Wextra -O2 -std=c++17 -c ../src/poset.cc -o poset.o
poset_example1.o: ../src/poset_example1.c
gcc -Wall -Wextra -O2 -std=c11 -c ../src/poset_example1.c -o poset_example1.o
poset_example2.o: ../src/poset_example2.cc
g++ -Wall -Wextra -O2 -std=c++17 -c ../src/poset_example2.cc -o poset_example2.o
poset_example1: poset_example1.o poset.o
g++ poset_example1.o poset.o -o poset_example1
poset_example2: poset_example2.o poset.o
g++ poset_example2.o poset.o -o poset_example2
.PHONY: all
all: poset_example1 poset_example2
.PHONY: clean
clean:
rm -rf *.o
rm -rf poset_example{1,2}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.15)
project(Poset LANGUAGES C CXX)
function(make_target name file)
add_executable(${name})
target_sources(${name}
PRIVATE
src/poset.cc
src/${file}
PUBLIC
src/poset.h)
set_property(TARGET ${name} PROPERTY CXX_STANDARD 17)
target_compile_options(${name}
PRIVATE
-Wall -Wextra)
endfunction()
make_target(example1 poset_example1.c)
make_target(example2 poset_example2.cc)<file_sep>/src/poset.cc
#include "poset.h"
#include <unordered_set>
#include <unordered_map>
#include <string>
#include <tuple>
// We shall start with the interface types, namely ids and values; since char const* cannot be stored in the usual
// way, we shall store proxies for them (in this case, STL strings).
using poset_id_t = unsigned long;
using persistent_value_t = std::string;
// Now, onto the overall structure of the project.
// We shall maintain some "program state" variable, i.e. posets_t for all stored posets and auxiliary stuff. Given
// how we need to come up with poset id's from essentially thin air in poset_new, we need a method for generating
// unique poset_id_t's. I propose following scheme: to store a counter of some type convertable to poset_id_t, and when
// adding new posets we would yield the counter's value and increment it - of course, then the generated id's are unique.
// That, however, presents an issue: what to do when counter reaches its max value? Then, I suppose, we could reassign
// ids - practically, however, if the counter is uint64_t, then we'd have to insert ~1.8*10^19 items to reach the
// max, so it may be altogether unnecessary of us to even concern ourselves with reassignments etc. We may discuss whether
// we want theoretical correctness or practical convenience later on.
// So, posets_t is essentially counter + map from poset ids' to posets. We are, clearly, lacking structure for a
// poset. In general, we could consider it to be a graph of some sort, i.e. something corresponding to a map from node
// id to a store of successors' ids, and merely ensure that the operations modifying the poset preserve its "posetness"
// Naively, we could just consider ids to be persistent_value_t's. We are, however, given an explicit requirement for
// storing the values only once across the program. My idea, then, is to represent values by some other type (by setting
// node id's type to that type and introducing a map from values to the representatives. We encounter, once again, a
// problem of taking representatives from thin air, but we can again utilise the counter system. Therefore, have:
using value_repr_t = uint64_t;
using names_assoc_t = std::unordered_map<persistent_value_t, value_repr_t>;
value_repr_t value_repr_gen = 0;
names_assoc_t names_assoc = {};
using poset_t = std::unordered_map<value_repr_t, std::unordered_set<value_repr_t>>;
using posets_t = std::unordered_map<poset_id_t, poset_t>;
poset_id_t poset_id_gen = 0;
posets_t posets = {};
unsigned long jnp1::poset_new(void) {
return 0;
}
void jnp1::poset_delete(unsigned long id) {
}
size_t jnp1::poset_size(unsigned long id) {
return 0;
}
bool jnp1::poset_insert(unsigned long id, char const* value) {
return false;
}
bool jnp1::poset_remove(unsigned long id, char const* value) {
return false;
}
bool jnp1::poset_add(unsigned long id, char const* value1, char const* value2) {
return false;
}
bool jnp1::poset_del(unsigned long id, char const* value1, char const* value2) {
return false;
}
bool jnp1::poset_test(unsigned long id, char const* value1, char const* value2) {
return false;
}
void jnp1::poset_clear(unsigned long id) {
}
|
82862ed4e2eb599a4d8a7da337000a9727f1e744
|
[
"Makefile",
"Text",
"CMake",
"C++"
] | 4
|
Text
|
Gor027/Poset
|
d8d92e6a79b5dc9c78d88d51ad106ec3319fce6b
|
b0370551721d21fc21c6f9056e6e64ffb3e9b950
|
refs/heads/master
|
<repo_name>ThisETboy/ElasticSearch<file_sep>/es-demo/src/main/java/com/itcast/create/App01_matchAllQuery.java
package com.itcast.create;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import sun.rmi.transport.Transport;
import java.net.InetAddress;
/**
* @Author YY
* @Date 2019/11/17 15:56
* @Version 1.0
* ES搜索 - 查询所有文档
*/
public class App01_matchAllQuery {
private TransportClient client;
@Test
public void test() {
// QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
// QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("java web开发");
/**
* 参数一: Field的名称
* 参数二:词条的名称
*/
// QueryBuilder queryBuilder = QueryBuilders.termQuery("bookname","java");
/**
* 参数一: 需要查询的id值(多个)
*/
// QueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("5","3");
/**
* rangeQuery: 指定需要搜索的Field
*
* 常用的比较方法:
* gt(): 大于
* lt(): 小于
* gte(): 大于等于
* lte(): 小于等于
*/
QueryBuilder queryBuilder = QueryBuilders.rangeQuery("price").gt(80).lt(100);
search(queryBuilder);
}
/**
* 查询所有文档
*/
public void search(QueryBuilder queryBuilder) {
//执行查询,返回结果
/**
* prepareSearch(索引):设置需要查询的索引(相当于数据库)
* setType(类型)设置需要查询的类型(相当于表)
* setQuery(查询条件)设置查询条件(不同的查询会着这里变化
*
* QueryBuilders.matchAllQuery查询所有文档
*/
SearchResponse response = client.prepareSearch("yy_index")
.setTypes("book")
.setQuery(queryBuilder)
.get();
//遍历结果SearchHits: 查询到的词条列表
SearchHits hits = response.getHits();
//获取命中的文档数量
System.out.println("命中的文档数量" + hits.totalHits);
SearchHit[] searchHits = hits.getHits();
//遍历所有词条列表数据
for (SearchHit searchHit : searchHits) {
System.out.println("=============================");
System.out.println(searchHit.getSourceAsMap().get("id"));
System.out.println(searchHit.getSourceAsMap().get("bookname"));
System.out.println(searchHit.getSourceAsMap().get("price"));
System.out.println(searchHit.getSourceAsMap().get("pic"));
System.out.println(searchHit.getSourceAsMap().get("bookdesc"));
}
}
/**
* 初始化工作
*/
@Before
public void init() throws Exception {
//1、创建一个Settings对象,相当于一个配置信息。主要配置集群的名称。
/**
* 参数一:集群key,固定不变的
* 参数二:集群环境的名称。默认的ES的集群环境名称为 "elasticsearch"
*/
Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
//创建一个客户端client对象
//传入setting参数
client = new PreBuiltTransportClient(settings);
//2.1 设置连接参数
/**
* 参数一:ES的连接主机
* 参数二:ES的连接端口。注意:ES和Java通讯端口为9300
*/
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
}
/**
* 释放资源
*/
@After
public void clear() {
client.close();
}
}
<file_sep>/es-demo/src/main/java/com/itcast/create/App06_create_mapping.java
package com.itcast.create;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.net.InetAddress;
/**
* @Author YY
* @Date 2019/11/17 15:43
* @Version 1.0
* 创建映射
*/
public class App06_create_mapping {
//操作es的客户端
private TransportClient client;
@Test
public void test() throws Exception {
String mappingJson = "{\"book\":{\"properties\":{\"price\":{\"type\":\"long\",\"store\":true},\"bookdesc\":{\"type\":\"text\",\"index\":true,\"store\":false,\"analyzer\":\"ik_max_word\"},\"id\":{\"type\":\"long\",\"index\":true,\"store\":true},\"pic\":{\"type\":\"text\",\"index\":false,\"store\":true},\"bookname\":{\"type\":\"text\",\"index\":true,\"store\":true,\"analyzer\":\"ik_max_word\"}}}}";
//创建映射
client.admin()
.indices()
.preparePutMapping("yy_index").setType("book")
.setSource(mappingJson, XContentType.JSON)
.get();
}
//给客户端赋值
@Before
public void init() throws Exception {
//创建一个settings对象,相当于一个配置信息,主要配置集群的名称
Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
client = new PreBuiltTransportClient(settings);
//使用client对象创建一个索引库
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
}
@After
public void close() {
client.close();
}
}
|
85fc865e9184897f14d74ea26ebaa9008c371306
|
[
"Java"
] | 2
|
Java
|
ThisETboy/ElasticSearch
|
56d106639f0a27f92bc0fdca0c35ff3cfcb9d17d
|
6e386fbb4b49edad677a2aefa7cfe2d8f9136a81
|
refs/heads/master
|
<repo_name>evargas1/Eat-to-Heal<file_sep>/README.md
# Eat to Heal
A website that was created to practice user authentication and forms. Book an appointment with a nutritionist via zoom. Login or register to view client dashboard.
Eat To Heal is a fully functioning webiste were visitors can book an appointment or get in contact with a certificated nutritionist. You can also navigate to the
Login and Signup button to create and accound with us or login to see upcoming appointments. The webpage also includes a small Eat Local section that teaches
vistors how to eat foods that are in season.
<file_sep>/tutorial/try/urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('contact/', views.contact, name='contact'),
path('signup/', views.signup, name='signup'),
path('aboutus/', views.aboutus, name='aboutus'),
path('dashboard/', views.dashboard, name='dashboard'),
path('login/', views.login, name='login'),
]
<file_sep>/tutorial/try/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
# from .models import Contact
from django.forms import ModelForm
# class SignUpForm(UserCreationForm):
# first_name = forms.CharField(max_length=30)
# last_name = forms.CharField(max_length=30)
# email = forms.EmailField(max_length=254)
# class Meta:
# model = User
# fields = ('username', 'first_name', 'last_name', 'email', 'password1', '<PASSWORD>')
# def save(self, commit=True):
# # Save the provided password in hashed format
# user = super(SignUpForm, self).save(commit=False)
# user.username(self.cleaned_data['username'])
# user.email(self.cleaned_data['email'])
# user.set_password(self.cleaned_data["<PASSWORD>"])
# if commit:
# user.save()
# return user
# class SignUpForm()
class LoginForm(forms.Form):
username = forms.CharField()
# typically used on senstieve data
password = forms.CharField(
widget=forms.PasswordInput
)
def clean(self):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
def clean_username(self):
username = self.cleaned_data.get("username")
qs = User.objects.filter(username__iexact=username)
if not qs.exists():
raise forms.ValidationError("This is an invalid error")
return username
# class SignUpForm(forms.Form):
# username = forms.CharField()
# email = forms.EmailField()
# password1 = forms.CharField(label='<PASSWORD>')
# password2 = forms.CharField(label='Confirm Password')
# def clean_username(self):
# username = self.cleaned_data.get("username")
# qs = User.objects.filter(username__iexact=username)
# # qs.save()
# if qs.exists():
# raise forms.ValidationError("This is an invalid username")
# return username
# def clean_email(self):
# email = self.cleaned_data.get("email")
# qs = User.objects.filter(email__iexact=email)
# # qs.save()
# if qs.exists():
# raise forms.ValidationError("This is an invalid email")
# return email
# def save(self, *args, **kwargs):
# u = self.instance.user
# u.first_name = self.cleaned_data['username']
# u.last_name = self.cleaned_data['<PASSWORD>']
# u.save()
# return super(SignUpForm, self).save(*args, **kwargs)
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.EmailField(max_length=254)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', '<PASSWORD>', '<PASSWORD>')
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["<PASSWORD>"])
if commit:
user.save()
return user<file_sep>/tutorial/try/templates/try/dashboard.html
{% extends 'try/main.html' %}
{% load static %}
{% block content %}
{% comment %} <h2>Welcome back {{ request.user|title }} !</h2> {% endcomment %}
<div class="dashboard" style="height: 80vh;">
<div class="small-container">
<div class="name-w" style="text-align: center;">
<h1 style="padding-bottom: 50px;" style="padding-top: 80px;" >Welcome {{ request.user|title }} </h1>
<form method="post" action="">
{% csrf_token %}
<input style="padding-top: 20px;" style="padding-bottom: 20px;" class="submit-butt" type="submit" value="Logout">
{% comment %} <input type="submit" value="Logout"> {% endcomment %}
</form>
</div>
</div>
</div>
{% endblock content %}
<file_sep>/tutorial/try/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
# from .forms import SignUpForm
from django.core.mail import send_mail
from django.urls import reverse
from django.http import HttpResponseRedirect
# from .models import Contact, ContactForm, Blog
import requests
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import get_user_model
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import LoginForm, SignUpForm
from .models import Contact, ContactForm
User = get_user_model()
def index(request):
context = {}
return render(request, 'try/index.html', context)
# def login(request):
# form = LoginForm(request.POST or None)
# if form.is_valid():
# username = form.cleaned_data.get("username")
# password = form.cleaned_data.get("<PASSWORD>")
# user = authenticate(request, username=username, password=<PASSWORD>)
# if user == None:
# # attempt = request.session.get("attemplt") or 0
# # request.session['attempt'] += 1
# request.session['invalid_user'] = 1
# return render(request, "try/login.html", {"form": form})
# auth_login(request, user)
# return HttpResponseRedirect('/dashboard/')
# return render(request, 'try/login.html', {"form": form})
def aboutus(request):
context = {}
return render(request, 'try/about-us.html', context)
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
# some sort of action needs to be performed here
# (1) save data
# (2) send an email ####
# (3) return search result
# (4) upload a file
return HttpResponseRedirect(reverse('aboutus'))
else:
form = ContactForm()
context = {}
return render(request, 'try/contact.html', context)
def login(request):
context = {}
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
# form = AuthenticationForm()
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
# check if user is in database
user = authenticate(username=username, password=password)
if user is not None:
auth_login(request, user)
return redirect('/dashboard/')
else:
messages.info(request, "username or password is incorrect")
return render(request, 'try/login.html', context)
# def signup(request):
# form = SignUpForm(request.POST or None)
# if form.is_valid():
# print("is valid")
# username = form.cleaned_data.get("username")
# email = form.cleaned_data.get("email")
# password = form.cleaned_data.get("<PASSWORD>")
# password2 = form.cleaned_data.get("<PASSWORD>")
# try:
# user = User.objects.create_user(username, email, password)
# form.save()
# except:
# user = None
# if user != None:
# auth_login(request, user)
# form.save()
# # form.save(commit=false)
# # attempt = request.session.get("attemplt") or 0
# # request.session['attempt'] += 1
# return HttpResponseRedirect('/dashboard/')
# else:
# request.session['register_error'] = 1
# return render(request, 'try/login.html', {"form": form})
def signup(request):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('<PASSWORD>')
user = authenticate(username=username, password=<PASSWORD>)
auth_login(request, user)
return HttpResponseRedirect(reverse('dashboard'))
else:
form = SignUpForm
context = {}
return render(request, 'try/register.html', {})
@login_required(login_url='/login/')
def dashboard(request):
if request.method == 'POST':
auth_logout(request)
return redirect('/login/')
context = {}
return render(request, 'try/dashboard.html', context)
<file_sep>/tutorial/try/models.py
from django.db import models
from django.forms import ModelForm
from django.utils.translation import gettext_lazy as _
# Create your models here.
SUBJECT_CHOICES = [
('Questions', 'Questions'),
('Book Consulation', 'Book Consulation'),
('Request More Reviews', 'Request More Reviews'),
('Contact a Specialist', 'Contact a Specialist'),
('Bussiness Inquery', 'Bussiness Inquery')
]
class Contact(models.Model):
name = models.CharField(max_length=50)
subject = models.CharField(max_length=50, choices=SUBJECT_CHOICES)
sender = models.EmailField()
def __str__(self):
return self.name
class ContactForm(ModelForm):
class Meta:
model= Contact
fields = ('name', 'subject', 'sender')
help_texts = {
'sender':_('We will contact you soon'),
}
error_messages = {
'name': {
'max_length':_("Just you first name will suffice!"),
},
}
|
8734e8e2f1c5489bcd8301b6ef101dd17a350a99
|
[
"Markdown",
"Python",
"HTML"
] | 6
|
Markdown
|
evargas1/Eat-to-Heal
|
7b4efc146f6ceede570d4b005d9aa0a96d309f8a
|
520dc51bb83b95725e0c9add3c1e396ab04828d2
|
refs/heads/master
|
<repo_name>ddolewski/STM32F429_Disco_FreeRTOS<file_sep>/stm32_freertos/STM32F429_FreeRTOS/src/main.c
#include "global.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stm32f429i_discovery.h"
#include "uart.h"
#define TERMINAL_USART USART1
#define TERMINAL_TX GPIO_Pin_9
#define TERMINAL_RX GPIO_Pin_10
#define TERMINAL_GPIO GPIOA
#define mainLED_TASK_PRIORITY ( tskIDLE_PRIORITY )
static void vhToggleLED(uint16_t xLedType);
static void vhLed_Init(void);
static void vTaskLED_Green(void * pvParameters);
static void vhButton_Init(void);
static void vHardwareSetup (void);
typedef enum
{
FRAME_BASIC_MEAS,
FRAME_PH_WATER,
FRAME_PH_SOIL
}frame_type_t;
int main (void)
{
vHardwareSetup();
vTaskStartScheduler();
return 0;
}
static void vHardwareSetup (void)
{
SystemInit();
SystemCoreClockUpdate();
vhLed_Init();
vhButton_Init();
vhUartInit();
}
void HardFault_Handler (void)
{
while (TRUE)
{
// USART_SendData(TERMINAL_USART, 'H');
// puts("HARD FAULT...\n\r");
}
}
static void vhButton_Init(void)
{
RCC_AHB1PeriphClockCmd(USER_BUTTON_GPIO_CLK, ENABLE);
GPIO_InitTypeDef GPIO_InitDef;
GPIO_InitDef.GPIO_Pin = USER_BUTTON_PIN;
GPIO_InitDef.GPIO_OType = GPIO_OType_PP;
GPIO_InitDef.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitDef.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitDef.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Init(USER_BUTTON_GPIO_PORT, &GPIO_InitDef);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource0);
EXTI_InitTypeDef EXTI_InitDef;
EXTI_InitDef.EXTI_Line = EXTI_Line0;
EXTI_InitDef.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitDef.EXTI_Trigger = EXTI_Trigger_Rising;
EXTI_InitDef.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitDef);
NVIC_PriorityGroupConfig( NVIC_PriorityGroup_4 );
NVIC_InitTypeDef NVIC_EXTI_InitDef;
NVIC_EXTI_InitDef.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_EXTI_InitDef.NVIC_IRQChannelPreemptionPriority = configLIBRARY_LOWEST_INTERRUPT_PRIORITY;
NVIC_EXTI_InitDef.NVIC_IRQChannelSubPriority = 0;
NVIC_EXTI_InitDef.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_EXTI_InitDef);
}
static void vhLed_Init (void)
{
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOG, ENABLE);
GPIO_InitTypeDef GPIO_InitDef;
GPIO_InitDef.GPIO_Pin = LED3_PIN | LED4_PIN;
GPIO_InitDef.GPIO_OType = GPIO_OType_PP;
GPIO_InitDef.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitDef.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitDef.GPIO_Speed = GPIO_Speed_100MHz;
//Initialize pins
GPIO_Init(GPIOG, &GPIO_InitDef);
xTaskCreate(vTaskLED_Green, (portCHAR *) "LED_GREEN", configMINIMAL_STACK_SIZE, NULL, mainLED_TASK_PRIORITY, NULL );
}
void EXTI0_IRQHandler(void){
long xHigherPriorityTaskWoken = pdFALSE;
if(EXTI_GetITStatus(EXTI_Line0) != RESET){
vhToggleLED(LED3_PIN);
EXTI_ClearITPendingBit(EXTI_Line0);
}
portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
}
static void vTaskLED_Green (void * pvParameters)
{
portTickType xLastFlashTime;
xLastFlashTime = xTaskGetTickCount();
frame_type_t frameFlag = FRAME_BASIC_MEAS;
while (TRUE)
{
vTaskDelayUntil(&xLastFlashTime, 1000/portTICK_RATE_MS);
vhToggleLED(LED4_PIN);
switch (frameFlag)
{
case FRAME_BASIC_MEAS:
//STA PRIMARYMEAS hum lux temp1 temp2 temp3 soil END
vSerialPutString((char*)"STA PRIMARYMEAS 47 15426 24.3 25.1 24.6 WET END ");
frameFlag = FRAME_PH_SOIL;
break;
case FRAME_PH_WATER:
//STA PHW waterPh END
vSerialPutString((char*)"STA PHW 6.78 END ");
frameFlag = FRAME_PH_WATER;
break;
case FRAME_PH_SOIL:
//STA PHS soilPh END
vSerialPutString((char*)"STA PHS 4.89 END ");
frameFlag = FRAME_BASIC_MEAS;
break;
default:
vSerialPutString((char*)"NONE FRAME!\r\n");
break;
}
}
}
static void vhToggleLED (uint16_t xLedType)
{
GPIO_ToggleBits(GPIOG, xLedType);
}
void vApplicationMallocFailedHook( void )
{
/* vApplicationMallocFailedHook() will only be called if
configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h. It is a hook
function that will get called if a call to pvPortMalloc() fails.
pvPortMalloc() is called internally by the kernel whenever a task, queue,
timer or semaphore is created. It is also called by various parts of the
demo application. If heap_1.c or heap_2.c are used, then the size of the
heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in
FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used
to query the size of free heap space that remains (although it does not
provide information on how the remaining heap might be fragmented). */
taskDISABLE_INTERRUPTS();
for( ;; );
}
/*-----------------------------------------------------------*/
void vApplicationIdleHook( void )
{
/* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set
to 1 in FreeRTOSConfig.h. It will be called on each iteration of the idle
task. It is essential that code added to this hook function never attempts
to block in any way (for example, call xQueueReceive() with a block time
specified, or call vTaskDelay()). If the application makes use of the
vTaskDelete() API function (as this demo application does) then it is also
important that vApplicationIdleHook() is permitted to return to its calling
function, because it is the responsibility of the idle task to clean up
memory allocated by the kernel to any task that has since been deleted. */
}
/*-----------------------------------------------------------*/
void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
{
( void ) pcTaskName;
( void ) pxTask;
/* Run time stack overflow checking is performed if
configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook
function is called if a stack overflow is detected. */
taskDISABLE_INTERRUPTS();
for( ;; );
}
<file_sep>/stm32_freertos/STM32F429_FreeRTOS/inc/global.h
#ifndef GLOBAL_H_
#define GLOBAL_H_
//-----------------------STANDARD C LIBS--------------------------//
#include "stdint.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
//-----------------------KERNEL FreeRTOS--------------------------//
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#include "croutine.h"
//-----------------------STM32F4xx LIBS--------------------------//
#include "system_stm32f4xx.h"
#include "stm32f4xx.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_usart.h"
#include "tm_stm32f4_disco.h"
#define DEBUG_MODE
#ifdef DEBUG_MODE
// wlasne definy
#else
// #define GLOBAL_FLASH_PROTECT
// #define WATCHDOG_ON
#endif
//#define NULL 0
#define ALWAYS 1
#define True 1
#define False 0
#define Other 2
typedef enum {FALSE, TRUE, OTHER} bool_t;
typedef void (*fun_ptr_t)(void);
#define ASSERT(ARG)
#define ARRAY_LEN(X) (sizeof(X) / sizeof(X[0])) //liczba elementow tabeli
#define SETIO(PORT, PIN) GPIOx_SetPin(PORT, PIN)
#define CLRIO(PORT, PIN) GPIOx_ResetPin(PORT, PIN)
//Timer systemowy
#define SYSTIMER SysTick
#define SYSTIME_HANDLER SysTick_Handler
#define UC (uint8_t *)
#define PACK_STRUCT_BEGIN
#define PACK_STRUCT_STRUCT __attribute__ ((__packed__))
#define PACK_STRUCT_END
#define PACK_STRUCT_FIELD(x) x
#define SIZEOF_TAB(x) (sizeof(x)/sizeof(x[0]))
#define ASM_REV32 __REV
#define ASM_REV16 __REV16
#define MAX(X,Y) ((X)>(Y)?(X):(Y))
#define MIN(X,Y) ((X)<(Y)?(X):(Y))
#define ABS_DIF(X,Y) (MAX(X,Y) - MIN(X,Y))
#define ABS(X) (((X) < 0) ? -(X) : (X))
#endif
<file_sep>/stm32_freertos/STM32F429_FreeRTOS/inc/uart.h
/*
* uart.h
*
* Created on: Dec 28, 2016
* Author: <NAME>
*/
#ifndef INC_UART_H_
#define INC_UART_H_
#include "stdint.h"
#include "stddef.h"
#include "FreeRTOS.h"
#include "queue.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_usart.h"
#define TERMINAL_USART USART1
#define TERMINAL_TX GPIO_Pin_9
#define TERMINAL_RX GPIO_Pin_10
#define TERMINAL_GPIO GPIOA
void vhUartInit(void);
signed portBASE_TYPE xSerialPutChar(signed char cOutChar);
signed portBASE_TYPE xSerialGetChar(signed char *pcRxedChar);
void vSerialPutString(char * xString);
extern QueueHandle_t xRxedChars;
extern QueueHandle_t xCharsForTx;
#endif /* INC_UART_H_ */
<file_sep>/stm32_freertos/STM32F429_FreeRTOS/src/uart.c
/*
* uart.c
*
* Created on: Dec 28, 2016
* Author: <NAME>
*/
#include "uart.h"
QueueHandle_t xRxedChars = NULL;
QueueHandle_t xCharsForTx = NULL;
void vhUartInit(void)
{
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_PinAFConfig(TERMINAL_GPIO, GPIO_PinSource9, GPIO_AF_USART1); //Tx
GPIO_PinAFConfig(TERMINAL_GPIO, GPIO_PinSource10, GPIO_AF_USART1); //Rx
GPIO_InitTypeDef gpioUsart;
gpioUsart.GPIO_Mode = GPIO_Mode_AF;
gpioUsart.GPIO_OType = GPIO_OType_PP;
gpioUsart.GPIO_Pin = TERMINAL_TX | TERMINAL_RX;
gpioUsart.GPIO_Speed = GPIO_Speed_50MHz;
gpioUsart.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(TERMINAL_GPIO, &gpioUsart);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No ;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
//Write USART1 parameters
USART_Init(USART1, &USART_InitStructure);
//Enable USART1
USART_Cmd(USART1, ENABLE);
NVIC_PriorityGroupConfig( NVIC_PriorityGroup_4 );
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = configLIBRARY_LOWEST_INTERRUPT_PRIORITY;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
xRxedChars = xQueueCreate( 64, ( unsigned portBASE_TYPE ) sizeof( signed char ) );
xCharsForTx = xQueueCreate( 64 + 1, ( unsigned portBASE_TYPE ) sizeof( signed char ) );
}
signed portBASE_TYPE xSerialGetChar(signed char *pcRxedChar)
{
if( xQueueReceive( xRxedChars, pcRxedChar, (TickType_t)0 ) )
{
return pdTRUE;
}
else
{
return pdFALSE;
}
}
void vSerialPutString(char * xString)
{
signed char *pxNext;
/* Send each character in the string, one at a time. */
pxNext = ( signed char * ) xString;
while ( *pxNext )
{
xSerialPutChar( *pxNext );
pxNext++;
}
}
signed portBASE_TYPE xSerialPutChar(signed char cOutChar)
{
signed portBASE_TYPE xReturn;
if ( xQueueSend( xCharsForTx, &cOutChar, ( TickType_t ) 0 ) == pdPASS )
{
xReturn = pdPASS;
USART_ITConfig( USART1, USART_IT_TXE, ENABLE );
}
else
{
xReturn = pdFAIL;
}
return xReturn;
}
void USART1_IRQHandler(void)
{
portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
char cChar;
if( USART_GetITStatus( USART1, USART_IT_TXE ) == SET )
{
if( xQueueReceiveFromISR( xCharsForTx, &cChar, &xHigherPriorityTaskWoken ) == pdTRUE )
{
USART_SendData( USART1, cChar );
}
else
{
USART_ITConfig( USART1, USART_IT_TXE, DISABLE );
}
USART_ClearITPendingBit(USART1, USART_IT_TXE);
}
if( USART_GetITStatus( USART1, USART_IT_RXNE ) == SET )
{
cChar = USART_ReceiveData( USART1 );
xQueueSendFromISR( xRxedChars, &cChar, &xHigherPriorityTaskWoken );
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
}
portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
}
<file_sep>/README.md
# STM32F429_Disco_FreeRTOS
Rozwojowy projekt FreeRTOS z wykorzystaniem różnych peryferiów mikrokontrolera STM32F429ZIT6 (STM32F429I-DISC1)
- FreeRTOS v9.0.0
- ST Periph V1.6.1 / 21-October-2015
- Discovery board drivers V1.0.1 / 28-October-2013
Program zawiera task odpowiadający za miganie diodą LED z f=1Hz oraz przełączanie buttonem stanu diody w przerwaniu EXTI0 (PA0)
W celu prawidłowego działania konfiguracji OpenOCD należy:
1) zainstalować plugin GNU ARM Eclipse OpenOCD z pakietu GNU ARM Eclipse Plug-ins
oraz pliki binarne OpenOCD z linków poniżej:
http://gnuarmeclipse.github.io/openocd/ - instalacja oraz konfiguracja
http://gnuarmeclipse.sourceforge.net/updates - plugin eclipse
2) Skonfigurować poprawnie ustawienia Eclipse dla danego systemu operacyjnego (Linux/Windows/MacOS)
tzn. wskazać ścieżkę openocd i jego zależności oraz gdb (Window->Preferences->Run/Debug->String Substitution):
openocd_path
openocd_executable
gdb_path
gdp_executable
openocd_boards
|
80e9bc28966a73962802169b6d2590969c8b4472
|
[
"Markdown",
"C"
] | 5
|
C
|
ddolewski/STM32F429_Disco_FreeRTOS
|
144acbeb45f40e84497c19758d5bf3f477c1a8c9
|
79624432beced39c374b84ae7d44bb8baa925594
|
refs/heads/master
|
<repo_name>aruizca/docker-confluence-for-testing<file_sep>/scripts/features/install-app-license.sh
#!/usr/bin/env bash
CONFLUENCE_BASE_URL="http://localhost:8090/confluence"
CONFLUENCE_USERNAME="admin"
CONFLUENCE_PASSWORD="<PASSWORD>"
APP_KEY=""
APP_LICENCE="<KEY>"
help () {
echo
echo "Usage: install-app.sh APP_KEY [-b CONFLUENCE_BASE_URL] [-u CONFLUENCE_USERNAME] [-p CONFLUENCE_PASSWORD] [-l APP_LICENCE]"
echo
echo "Install the license for the provided app key in a Confluence instance."
echo
echo "APP_KEY Key for the app to be licensed"
echo "[-b CONFLUENCE_BASE_URL] Default -> http://localhost:8090/confluence"
echo "[-u CONFLUENCE_USERNAME] Default -> admin"
echo "[-p CONFLUENCE_PASSWORD] Default -> <PASSWORD>"
echo "[-l APP_LICENCE] Default -> standard 3 hours timebomb license"
echo
exit
}
if [[ ! -z "$1" ]]
then
APP_KEY=$1
else
help
fi
while [ $# -gt 0 ]
do
case "$1" in
"-b")
CONFLUENCE_BASE_URL=$2
shift 2;;
"-u")
CONFLUENCE_USERNAME=$2
shift 2;;
"-p")
CONFLUENCE_PASSWORD=$2
shift 2;;
"-l")
APP_LICENSE=$2
shift 2;;
"-?" | "-h" | "--help" | "-help" | "help")
help;;
*)
shift 1
esac
done
LICENSE_URL="${CONFLUENCE_BASE_URL}/rest/plugins/latest/${APP_KEY}-key/license"
echo "Installing plugin license to ${LICENSE_URL}"
curl -u ${CONFLUENCE_USERNAME}:${CONFLUENCE_PASSWORD} -v -X PUT -d "{\"rawLicense\": \"${APP_LICENCE}\"}" -H "Content-Type: application/vnd.atl.plugins+json" ${LICENSE_URL}<file_sep>/scripts/confluence-setup-app.sh
#!/usr/bin/env bash
# Version Selection
VERSION=$( zenity --title "Select Confluence Version" --list --ok-label "Submit" --cancel-label "I wanna set my own" \
--column="Confluence Version" \
"7.20.1" \
"7.20.0" \
"7.19.2" \
"7.19.1" \
"7.19.0" \
"7.18.3" \
"7.18.2" \
"7.18.1" \
"7.18.0" \
"7.17.5" \
"7.17.4" \
"7.17.3" \
"7.17.2" \
"7.17.1" \
"7.17.0" \
"7.16.5" \
"7.16.4" \
"7.16.3" \
"7.16.2" \
"7.16.1" \
"7.16.0" \
"7.15.3" \
"7.15.2" \
"7.15.1" \
"7.15.0" \
"7.14.4" \
"7.14.3" \
"7.14.2" \
"7.14.1" \
"7.14.0" \
"7.13.11"\
"7.13.9" \
"7.13.8" \
"7.13.7" \
"7.13.6" \
"7.13.5" \
"7.13.4" \
"7.13.3" \
"7.13.2" \
"7.13.1" \
"7.13.0" \
"7.12.5" \
"7.12.4" \
"7.12.3" \
"7.12.2" \
"7.12.1" \
"7.12.0" \
"7.11.6" \
"7.11.3" \
"7.11.2" \
"7.11.1" \
"7.11.0" \
"7.10.2" \
"7.10.1" \
"7.10.0" \
"7.9.3" \
"7.9.1" \
"7.9.0" \
)
if [ $? = 0 ] && [ -n "$VERSION" ] # check if ok or cancel clicked or var is empty
then
VERSION_FLAG="-v $VERSION"
echo "Selected version is: $VERSION"
else
# Manual Version Selection
VERSION=$( zenity --title "Select Confluence Version" --entry --text "Introduce a valid Confluence version in the 'x.y.z' format:" --ok-label "Submit" --cancel-label "Set default 7.9.0 version")
if [ $? = 0 ] && [ -n "$VERSION" ] # check if ok or cancel clicked or var is empty
then
VERSION_FLAG="-v $VERSION"
echo "Selected version is: $VERSION"
else
VERSION_FLAG="-v 7.9.0"
echo "Default version will be used"
fi
fi
# Custom Name
ALIAS=$( zenity --title "Select an Alias" --entry --text "Set a name to your Confluence (e.g. 'testing1') to easily identify it (one word only without special characters):" --ok-label "Submit" --cancel-label "Ignore")
if [ $? = 0 ] && [ -n "$ALIAS" ] # check if ok or cancel clicked or var is empty
then
ALIAS_FLAG="-a $ALIAS"
echo "Selected alias: $ALIAS"
else
ALIAS_FLAG=""
echo "No alias selected"
fi
# Confluence Setup
zenity --title "Confluence Set up" --question --text "Would you like to get your Confluence automatically set up? This includes the following main steps: License setup, Database configuration, Admin user configuration, Disabling on boarding module, User directory configuration" --ok-label "Yes" --cancel-label "No"
if [ $? = 0 ] # check if ok or cancel clicked
then
ENV_FLAG="-e"
ENV_FLAG="$ENV_FLAG PPTR_LDAP_CONFIG=true"
echo "Confluence set up selected"
LICENSE=$( zenity --title "Confluence License" --entry --text "Provide a valid Confluence license. It can either be a Server or DC license. If none is provided the default Atlassian 3h DC timebomb license will be used" --ok-label "Submit license" --cancel-label "Use default")
if [ $? = 0 ] && [ -n "$LICENSE" ] # check if ok or cancel clicked or var is empty
then
ENV_FLAG="$ENV_FLAG PPTR_CONFLUENCE_LICENSE=$LICENSE"
echo "Provided Confluence license: $LICENSE"
else
echo "No Confluence license provided, default will be used"
fi
COMMAND="${BASH_SOURCE%/*}/run-confluence-container.sh $VERSION_FLAG $ALIAS_FLAG $ENV_FLAG"
else
echo "Confluence set up not chosen"
COMMAND="${BASH_SOURCE%/*}/run-confluence-container-no-setup.sh $VERSION_FLAG $ALIAS_FLAG"
fi
# Confirmation
CONFIRMATION=$(zenity --title "Configuration Ready" --question --text "Everything ready, your Confluence will be started, running the following command, do you wish to proceed? $COMMAND" --ok-label "Start up Confluence" --cancel-label "Cancel")
if [ $? = 0 ] # check if ok or cancel clicked
then
echo "command to run: $COMMAND"
source $COMMAND
else
echo "Confluence launch cancelled"
fi<file_sep>/scripts/features/install-app.sh
#!/usr/bin/env bash
APP_LOCATION=""
APP_FILE_PATH="./app-to-install.jar"
CONFLUENCE_BASE_URL="http://localhost:8090/confluence"
CONFLUENCE_USERNAME="admin"
CONFLUENCE_PASSWORD="<PASSWORD>"
help () {
echo
echo "Usage: install-app.sh APP_LOCATION [-b CONFLUENCE_BASE_URL] [-u CONFLUENCE_USERNAME] [-p CONFLUENCE_PASSWORD]"
echo
echo "Install the provided app in a Confluence instance."
echo
echo "APP_LOCATION URL or file path to the app JAR file"
echo "[-b CONFLUENCE_BASE_URL] Default -> http://localhost:8090/confluence"
echo "[-u CONFLUENCE_USERNAME] Default -> admin"
echo "[-p CONFLUENCE_PASSWORD] Default -> <PASSWORD>"
echo
exit
}
if [[ ! -z "$1" ]]
then
APP_LOCATION=$1
else
help
fi
while [ $# -gt 0 ]
do
case "$1" in
"-b")
CONFLUENCE_BASE_URL=$2
shift 2;;
"-u")
CONFLUENCE_USERNAME=$2
shift 2;;
"-p")
CONFLUENCE_PASSWORD=$2
shift 2;;
"-?" | "-h" | "--help" | "-help" | "help")
help;;
*)
shift 1
esac
done
## Download app if required
if [[ $APP_LOCATION == http* ]]
then
echo "Downloading from web"
curl -k -L -o ${APP_FILE_PATH} ${APP_LOCATION}
else
echo "Using file system"
APP_FILE_PATH=$APP_LOCATION
fi
## Get UPM token
UPM_TOKEN=$(curl -I --user $CONFLUENCE_USERNAME:$CONFLUENCE_PASSWORD -H 'Accept: application/vnd.atl.plugins.installed+json' $CONFLUENCE_BASE_URL'/rest/plugins/1.0/?os_authType=basic' 2>/dev/null | grep 'upm-token' | cut -d " " -f 2 | tr -d '\r')
## Install the App
curl --user ${CONFLUENCE_USERNAME}:${CONFLUENCE_PASSWORD} -H 'Accept: application/json' ${CONFLUENCE_BASE_URL}'/rest/plugins/1.0/?token='${UPM_TOKEN} -F plugin=@${APP_FILE_PATH}<file_sep>/Dockerfile
FROM ubuntu:18.04
LABEL MAINTAINER @aruizca - <NAME>
ENV JAVA_HOME /opt/jre
ENV PATH $JAVA_HOME/bin:$PATH
# https://confluence.atlassian.com/doc/confluence-home-and-other-important-directories-590259707.html
ENV CONFLUENCE_HOME /var/atlassian/application-data/confluence
ENV CONFLUENCE_INSTALL_DIR /opt/atlassian/confluence
ARG CONFLUENCE_VERSION
ARG JAVA_VERSION
# Install some utilse
RUN apt-get update \
&& apt-get install -yq wget curl bash jq ttf-dejavu ca-certificates tzdata locales locales-all fontconfig \
&& update-ca-certificates \
&& rm -rf /var/lib/{apt,dpkg,cache,log}/ /tmp/* /var/tmp/*
# Use jabba JVM Manger to install Zulu JRE 1.8
RUN curl -sL https://github.com/shyiko/jabba/raw/master/install.sh | JABBA_COMMAND="install ${JAVA_VERSION} -o ${JAVA_HOME}" bash
# If no Confluence version provided via command line argument, the last available version will be installed
# Expose HTTP, Synchrony ports and Debug ports
EXPOSE 8090 8091 5005
WORKDIR $CONFLUENCE_HOME
RUN mkdir scripts
COPY scripts/features/entrypoint.sh /scripts/features/entrypoint.sh
# Download required Confluence version
RUN [ -n "${CONFLUENCE_VERSION}" ] || export CONFLUENCE_VERSION=$(curl -s https://marketplace.atlassian.com/rest/2/applications/confluence/versions/latest | jq -r '.version') \
&& export DOWNLOAD_URL="http://www.atlassian.com/software/confluence/downloads/binary/atlassian-confluence-${CONFLUENCE_VERSION}.tar.gz" \
&& mkdir -p ${CONFLUENCE_INSTALL_DIR} \
&& curl -L ${DOWNLOAD_URL} | tar -xz --strip-components=1 -C "$CONFLUENCE_INSTALL_DIR"
# Perform settings modifications
RUN sed -i -e 's/-Xms\([0-9]\+[kmg]\) -Xmx\([0-9]\+[kmg]\)/-Xms\${JVM_MINIMUM_MEMORY:=\1} -Xmx\${JVM_MAXIMUM_MEMORY:=\2} \${JVM_SUPPORT_RECOMMENDED_ARGS} -Dconfluence.home=\${CONFLUENCE_HOME} -Dsynchrony.proxy.healthcheck.disabled=true/g' ${CONFLUENCE_INSTALL_DIR}/bin/setenv.sh \
&& sed -i -e 's/<Context path=""/<Context path="\/confluence"/g' ${CONFLUENCE_INSTALL_DIR}/conf/server.xml \
&& sed -i -e 's/\${confluence.context.path}/\/confluence/g' ${CONFLUENCE_INSTALL_DIR}/conf/server.xml
CMD ["/scripts/features/entrypoint.sh", "-fg"]<file_sep>/README.md
# Docker-confluence-for-testing (WIP)
Script that provides a one-off command to locally run any Atlassian Confluence version using an Oracle JRE on a Docker container.
It's purpose is just for quickly spin up any standalone version of Confluence to perform tests on it.
⚠️Important! This is not intended to be used in a production system.
## Requirements
The only requirement is to have [Docker installed](https://www.docker.com/products/docker-desktop).
Adjusting the available RAM for the Docker engine to at least 4GB is also required. You can find the settings in Docker -> Preferences -> Advanced.
## Before starting
##⚠️ <span style="color:Orange"> Important! Rename the ".env.sample" file to ".env" in which all the default values for the used environment variables are set.</span>
## Usage
Its main usage includes a container which will make use of the [puppeteer-confluence-setup image at Docker Hub](https://hub.docker.com/repository/docker/aruizca/puppeteer-confluence-setup) to automate also the initial setup process. For more info go to the [puppeteer-confluence-setup GitHub repo](https://github.com/aruizca/puppeteer-confluence-setup).
```bash
./scripts/run-confluence-container.sh
```
If you want to perform the setup process manually you could use the next flags:
### Version flag -v
```bash
./scripts/run-confluence-container-no-setup.sh -v [x.y.z]
```
-v [x.y.z] is an optional flag that follows with the Confluence version number you want to run.
Otherwise, the default version that appears on the .env file will be used.
### Alias flag -a
Using -a flag, you can add an alias to your docker container.
```bash
./scripts/run-confluence-container-no-setup.sh -a [alias]
```
This way, the container name will add the alias to the actual container name.
So if we run the script without any flag:
```bash
./scripts/run-confluence-container-no-setup.sh
```
The container name will be: 7-9-0--8090
But if you run it with an alias:
```bash
./scripts/run-confluence-container-no-setup.sh -a aliasName
```
The container name will be: 7-9-0--8090--aliasName
### Environment variables flag -e
You also can set your own environment variables by using the "-e" flag.
```bash
./scripts/run-confluence-container-no-setup.sh -e "ENV=VALUE ENV2=VALUE"
```
This way the environment variables passed in the flag will override the actual ones and will be used in the script.
Note that if you want to set more than one environment variable, you will have to write them within the "" quotes.
## Default Confluence Build
The docker container will be generated using the ports showed below.
| ENV_VARIABLE | | | | | | |
|-----------------------|------|:----:|-----|-----|-----|-----|
| CONFLUENCE_PORTS_LIST | 8090 | 9010 | 9020 | 9030 | 9040 | 9050 |
| LDAP_PORTS_LIST | 388 | 389 | 387 | 386 | 385 | 384 |
| POSTGRES_PORTS_LIST | 5543 | 5432 | 5654 | 5765 | 5876 | 5987 |
| DEBUG_PORTS_LIST | 5007 | 5006 | 5008 | 5009 | 5010 | 5011 |
For each Confluence instance we try to start up, it will check if the port is being used, if so, it will use the next one according to the table.
This way, the first Confluence instance we create will be listening on <http://localhost:8090/confluence>, the second one <http://localhost:9010/confluence> and so on.
If you prefer using your own port lists, you can set them in your environment variables separating the ports with "," for example:
```bash
export CONFLUENCE_PORTS_LIST=7980,7970,7960,7950,7940,7930
```
or pass the value in the -e flag:
```bash
./scripts/run-confluence-container-no-setup.sh -e CONFLUENCE_PORTS_LIST=7980,7970,7960,7950,7940,7930
```
## Confluence Volume
This script will also create a volume connected to the home path of the conflunce server in your machine to easily access the data of the server.
This way you can open the files using your favorite text editor.
The path of the directory is allocated in the same path of the project, but it can be modified by changing the "VOLUME_PATH" environment variable.
eg:
```bash
./scripts/run-confluence-container-no-setup.sh -v 7.20.0 -a volumeContainer
```
The created folder will have the next name: 7-20-0--9010--volumeContainer
## Other useful scripts
- `install-app.sh`: script to install an app via URL or file path. `install-app.sh -h` for details.
- `install-app-license.sh`: script to add licensing to a previously installed app. `install-app-license.sh -h` for details.
- `full-app-setup-example.sh`: this example shows the full cycle of installing Confluence, set it up, install an app, and add a license. This is useful to prepare the environment to execute e2e tests.
## Zenity based GUI script
### Description
In order to ease starting Confluence instances to users that are not familiar with the command line and are not familiar with the different available options to run the Confluence instance, there is a script that has a Graphic User Interface (GUI) guiding the user through them.
Once the selection of the options through the graphic interface is completed, then the right script with the right parameters will be run automatically.
### Requirements
This script was tested using [this custom Zenity implementation](https://github.com/ncruces/zenity) as a dependency. You can obtain the `zenity` command to make this script work, as follows:
On macOS/WSL using [Homebrew](https://brew.sh/) 🍺:
brew install ncruces/tap/zenity
On Windows using [Scoop](https://scoop.sh/) 🍨:
scoop install https://ncruces.github.io/scoop/zenity.json
### How to run it
This script can be run normally by running the following in a command console:
./scripts/confluence-setup-app.sh
Or if you are in macOS you could simply rename `confluence-setup-app.sh` to `confluence-setup-app.command` which is an executable you can double-click on from your desktop.
Both options will prompt a window where you can start selecting the different options you wish your Confluence instance to have.
### Zenity Documentation
If you wish to know more about how this script with Zenity works and modify it to suit your needs, here you have some of the documentation used:
- https://manpages.ubuntu.com/manpages/trusty/man1/zenity.1.html
- https://help.gnome.org/users/zenity/stable/index.html.en
## Java JDK
You can choose with version of java is going to be installed in container.
To use this feature, you need to set JAVA_VERSION variable when runing the container.
Java version should be in the format vendor@version, as used in JABBA.
If no JAVA_VERSION is set, by default, version to be installed is: `zulu@1.8.232`
For example , to run a container with confluece 5.4.4 (which need java 7) and the zulu 1.7.95 version (which is supportorted by JABBA):
```bash
./scripts/run-confluence-container.sh -v 5.4.4 -e JAVA_VERSION=zulu@1.7.95
```
You can check available vendor/version
> <https://github.com/shyiko/jabba/blob/master/index.json>
## Database selection
By default, it uses postgres, but to make it easier to test with, now the script can also run diferent databases.
This databases are ready to work, and already configured to work with confluence, so there is no need to
do any modification (althouh you many need to install the driver into confluence)
These are the new supported databases:
mysql:
- version: 5.6
- db: confluence
- user: confluenceUser
- pass: <PASSWORD>
- root pass: <PASSWORD>
oracle
- version: 2017
- b: confluence
- user: confluenceUser
- pass: <PASSWORD>
- root pass: <PASSWORD>
sqlserver
- version: 12C
- db: CONFLUENCE_TS
- user: confluence
- pass: <PASSWORD>
- sid: xe
For example to run the oracle database jsut do the following:
```bash
./scripts/run-confluence-container.sh -v [x.y.z] -e DATABASE=oracle
```
## Debugging port
By default debugging port from host is 5006 but you can customise
```bash
DEBUG_PORT=5006
```
## Change container localization and timezone
```bash
TZ=America/Los_Angeles
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
LANGUAGE=en_US.UTF-8
```
## Runtime Environment Setup
Several other services are started up along with the Confluence instance to customize your setup:
## Database
Instead of using the embedded H2 DB, you can configure your Confluence instance to use a proper DB engine. In fact this is really advisable if you want to run a Confluence version >= 6.x and use collaborative editing.
At the moment only PostgreSQL is available but we plan to support other DB engines in the future.
### PostgreSQL
By default a container named "postgres" is up using version 9.6, which seems to be the minimum version to run collaborative editing service "Synchrony" without issues.
#### Details
- Container name and hostname: postgres
- DB name: confluence
- DB username: postgres
- DB password: <PASSWORD>
- JDBC connection URL: jdbc:postgresql://postgres:5432/confluence
#### Changing version
You can change the default PostgreSQL version (9.6) by adding the environment variable `POSTGRESQL_VERSION`. Eg:
```bash
./scripts/run-confluence-container.sh -v 6.15.1 -e POSTGRESQL_VERSION=10.2
```
You can use any of the versions available in [the official PostgreSQL Docker repository](https://hub.docker.com/_/postgres)
⚠️Important! Versions earlier that 9.6 present problems with Collaborative Editing feature.
#### DB recommended version
| Confluence Version | PostgreSQL version |
|--------------------|:------------------:|
| 7.9.0 - 7.20.0 | 9.6 |
|
## External user directory
Most companies use an external directory services to manage users authentication and authorization. To test that scenario I have forked and customized a [Docker image with OpenLDAP in this repository](https://github.com/aruizca/docker-test-openldap), so it can be used out of the box for that purpose.
A container using this image will be run along with Confluence and available if needed.
That repo contains also the setting to configure it inside Confluence.
## Troubleshooting
### After setting up Confluence everything is slow
This might be due to the synchrony server (collaborative editing) failing to start up correctly. You can disable synchrony via REST API using the following GET request:
> <http://localhost:8090/confluence/rest/synchrony-interop/disable?os_username=admin&os_password=admin>
Also makes sure that in the Advanced Docker preferences the amount of RAM available for the Docker engine is at least 4GB.
### Windows 10
When cloning this repo to a Windows machine, file endings won't be the same as in Unix. To avoid this,
you can either clone the repo specifying this option:
````bash
git clone <EMAIL>:aruizca/docker-confluence-for-testing.git --config core.autocrlf=input
````
Or modify the entrypoint.sh file to use Unix file ending (LF) instead of Windows file ending (CRLF).<file_sep>/scripts/features/full-app-setup-example.sh
#!/usr/bin/env bash
## Set path to the foler where this script is
cd "$(dirname "$0")"
## Spin up and setup Confluence standalone instance
./run-confluence-container-no-logs.sh 7.4.1
## Install app (Comala Boards 2.3.1 as example)
./install-app.sh https://marketplace.atlassian.com/download/apps/1177667/version/983
## Instal app license
./install-app-license.sh com.comalatech.adhoccanvas
<file_sep>/scripts/run-confluence-container-no-setup.sh
#!/usr/bin/env bash
source ${BASH_SOURCE%/*}/features/run-confluence-container-common.sh $@
docker-compose -p ${PACKAGE_NAME} up -d ${DATABASE} confluence
docker logs -f confluence_${PACKAGE_NAME}<file_sep>/scripts/features/run-confluence-container-common.sh
#!/usr/bin/env bash
#-e Exit immediately if a command exits with a non-zero status.
set -e
function usage {
echo " "
local scriptName=$(basename "$0")
echo "Usage: ${scriptName} -a alias -v x.y.z -e \"[ENV=VALUE ENV2=VALUE]\""
echo " "
echo " Set configuration parameters one after another to personalize the docker container"
echo " example ${scriptName} -v 9.10.0 -e DEBUG_PORT=5006 will set the Confluence version to 9.10.0 opening the 5006 port for debugging"
echo " If no parameters are set , .env file parameters will be set "
echo " "
echo "FLAGS:"
echo " -v : Confluence version to use | eg: ${scriptName} -v 9.14.0"
echo " -a : Alias for the docker container | eg: ${scriptName} -a integrationTests"
echo " -e : Environment variables to set | eg: ${scriptName} -e \"CONFLUENCE_PORT=8094 DEBUG_PORT=5008\""
echo " -h : Shows this message"
}
##
function getConfluencePorts() {
# if you have ports lists set in your env variable uses those ports
if [[ ! -z "${CONFLUENCE_PORTS_LIST}" ]]; then
confluencePorts=($(echo ${CONFLUENCE_PORTS_LIST} | tr "," "\n"))
echo ${confluencePorts[*]}
else
confluencePorts=(8090 9010 9020 9030 9040 9050)
echo ${confluencePorts[*]}
fi
}
function getLdapPorts() {
# if you have ports lists set in your env variable uses those ports
if [[ ! -z "${LDAP_PORTS_LIST}" ]]; then
ldapPorts=($(echo ${LDAP_PORTS_LIST} | tr "," "\n"))
echo ${ldapPorts[*]}
else
ldapPorts=(389 388 387 386 385 384)
echo ${ldapPorts[*]}
fi
}
function getPostgresPorts() {
# if you have ports lists set in your env variable uses those ports
if [[ ! -z "${POSTGRES_PORTS_LIST}" ]]; then
postgresPorts=($(echo ${POSTGRES_PORTS_LIST} | tr "," "\n"))
echo ${postgresPorts[*]}
else
postgresPorts=(5432 5543 5654 5765 5876 5987)
echo ${postgresPorts[*]}
fi
}
function getDebugPorts() {
# if you have ports lists set in your env variable uses those ports
if [[ ! -z "${DEBUG_PORTS_LIST}" ]]; then
debugPorts=($(echo ${DEBUG_PORTS_LIST} | tr "," "\n"))
echo ${debugPorts[*]}
else
debugPorts=(5006 5007 5008 5009 5010 5011)
echo ${debugPorts[*]}
fi
}
## TODO oraclePorts, oracleListenerPorts, mysqlPorts, sqlServerPorts
## Creates a list of used docker confluence ports
function getDockerUsedPorts() {
dockerContainers=$(docker ps -a --format '{{.Names}}')
for container in $dockerContainers
do
if [[ $container == *"confluence_"* ]]; then
## As container name is 'confluence_X.Y.Z--PORT, we trim after the first encounter of '--'
untrimmedPort=${container#*--}
## Taking only the first 4 characters that matches the port
trimmedPort=${untrimmedPort:0:4}
dockerConfluencePorts=(${dockerConfluencePorts[@]} ${trimmedPort})
fi
done
echo ${dockerConfluencePorts[*]}
}
## Processes all flags available in this scripts
while getopts 'a:v:e:h:' OPTION; do
case "$OPTION" in
a)
alias="$OPTARG"
;;
v)
version="$OPTARG"
case "$version" in
[0123456789]*)
CONFLUENCE_RUN_VERSION=${version}
;;
*)
# If none the above then the first argument is an environment variable
args="${@:1}"
;;
esac
;;
e)
set -f # disable glob
IFS=' ' # split on spaces
env_variables=($OPTARG) ;; # use the split+glob operator
h)
usage
exit
;; # quit and show usage
?)
usage
exit 1
;;
esac
done
shift "$(($OPTIND -1))"
## load all ports lists
confluencePorts=$(getConfluencePorts)
ldapPorts=($(getLdapPorts))
postgresPorts=($(getPostgresPorts))
debugPorts=($(getDebugPorts))
## get list of ports used by Docker
dockerConfluencePorts=$(getDockerUsedPorts)
# Set current folder to parent
cd "$(dirname "$0")"/..
#load default env varibles from .env file
while read envLine; do
# skips all lines with '#' at the beginning
[[ $envLine = \#* ]] && continue
# checks if the user has VOLUME_PATH environment variable already set
if [[ ${envLine} == *"VOLUME_PATH"* && ! -z "${VOLUME_PATH}" ]]; then
echo "Using VOLUME_PATH environment variable with value: '${VOLUME_PATH}'"
else
export ${envLine}
fi
done <.env
iterator=0
for confluencePort in $confluencePorts
do
# Check if confluencePort is available in TCP ports
SERVER=localhost PORT=${confluencePort}
if (: < /dev/tcp/$SERVER/$PORT) 2>/dev/null
then # Port already used
echo "port ${confluencePort} already in use, trying another one"
else # Free port in TCP
# Checks if the free confluence port is not being used by Docker
if [[ ! " ${dockerConfluencePorts[*]} " =~ " ${confluencePort} " ]]
then
export "CONFLUENCE_PORT=${confluencePort}"
# confluence syncrony port value is the same as confluence port +2
confluenceSynchronyPort=`expr ${confluencePort} + 2`
export "CONFLUENCE_SYNCHRONY_PORT=${confluenceSynchronyPort}"
# taking the value of the array corresponding to the same position as the confluence port list at this time
export "LDAP_PORT=${ldapPorts[${iterator}]}"
export "POSTGRES_PORT=${postgresPorts[${iterator}]}"
export "DEBUG_PORT=${debugPorts[${iterator}]}"
# TODO oraclePorts, oracleListenerPorts, mysqlPorts, sqlServerPorts exports
break
else
echo "port ${confluencePort} already in use, trying another one"
fi
fi
iterator=`expr ${iterator} + 1`
done
if [[ ! -z "${CONFLUENCE_RUN_VERSION}" ]]; then
export "CONFLUENCE_VERSION=${CONFLUENCE_RUN_VERSION}"
fi
for env_variable in "${env_variables[@]}"
do
export ${env_variable}
echo "set environment variable -> ${env_variable}"
done
if [[ ! -z "${alias}" ]];
then
export "PACKAGE_NAME"="${CONFLUENCE_VERSION//./-}--${CONFLUENCE_PORT}--${alias}"
else
export "PACKAGE_NAME"="${CONFLUENCE_VERSION//./-}--${CONFLUENCE_PORT}"
fi
echo " "
echo "Container name = ${PACKAGE_NAME}"
echo " "
echo "running server in $(tput setaf 2)http://localhost:${CONFLUENCE_PORT}/confluence"
echo " "
echo "$(tput setaf 4)Starting Confluence version $CONFLUENCE_VERSION"
echo "---------------------------------"
<file_sep>/scripts/run-confluence-container-no-logs.sh
#!/usr/bin/env bash
source ${BASH_SOURCE%/*}/features/run-confluence-container-common.sh $@
docker-compose -p ${PACKAGE_NAME} up -d ${DATABASE} puppeteer-confluence-setup
docker logs -f puppeteer-confluence-setup_${PACKAGE_NAME}
<file_sep>/scripts/features/stop-confluence.sh
#!/usr/bin/env bash
#-e Exit immediately if a command exits with a non-zero status.
set -e
function usage() {
local scriptName=$(basename "$0")
echo "usage: ${scriptName} x.y.z ENV=VALUE ENV2=VALUE"
echo " "
echo " Set configuration parameters one after another to personalize the docker container"
echo " example ${scriptName} 6.1.0 DEBUG_PORT=5006 will set the Confluence version to 6.1.0 opening the 5006 port for debugging"
echo " If no parameters are set , .env file parameters will be set "
echo " "
echo " -h | --help : This message"
}
# By default we ignore the first argument
args="${@:2}"
case "$1" in
[0123456789]*)
CONFLUENCE_RUN_VERSION=$1
shift 1
;;
-h | --help)
usage
exit
;; # quit and show usage
*)
# If none the above then the first argument is an environment variable
args="${@:1}"
;;
esac
# Set current folder to parent
cd "$(dirname "$0")"/..
#load default env varibles
set -o allexport
[[ -f .env ]] && source .env
set +o allexport
if [[ ! -z "${CONFLUENCE_RUN_VERSION}" ]]; then
export "CONFLUENCE_VERSION=${CONFLUENCE_RUN_VERSION}"
fi
for env_variable in ${args}; do
export ${env_variable}
echo "set environment variable -> ${env_variable}"
done
echo "Stoping all containers for Confluence $CONFLUENCE_RUN_VERSION"
echo "---------------------------------"
#stop only specific version of confluence if it was specified on command
if [[ -z "${CONFLUENCE_RUN_VERSION}" ]]; then
docker-compose stop
else
PROJECT_NAME="${CONFLUENCE_RUN_VERSION//.}"
docker-compose -p "${PROJECT_NAME}" stop
fi<file_sep>/scripts/features/entrypoint.sh
#!/bin/bash
set -euo pipefail
#detect java version
JAVA_VER=$(java -version 2>&1 | sed -n ';s/.* version "\(.*\)\.\(.*\)\..*".*/\1\2/p;')
# Setup Catalina Opts
: ${CATALINA_CONNECTOR_PROXYNAME:=}
: ${CATALINA_CONNECTOR_PROXYPORT:=}
: ${CATALINA_CONNECTOR_SCHEME:=http}
: ${CATALINA_CONNECTOR_SECURE:=false}
: ${CATALINA_OPTS:=}
CATALINA_OPTS="${CATALINA_OPTS} -DcatalinaConnectorProxyName=${CATALINA_CONNECTOR_PROXYNAME}"
CATALINA_OPTS="${CATALINA_OPTS} -DcatalinaConnectorProxyPort=${CATALINA_CONNECTOR_PROXYPORT}"
CATALINA_OPTS="${CATALINA_OPTS} -DcatalinaConnectorScheme=${CATALINA_CONNECTOR_SCHEME}"
CATALINA_OPTS="${CATALINA_OPTS} -DcatalinaConnectorSecure=${CATALINA_CONNECTOR_SECURE}"
if [ "$JAVA_VER" -ge 90 ]; then
CATALINA_OPTS="${CATALINA_OPTS} -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005"
else
CATALINA_OPTS="${CATALINA_OPTS} -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
fi
export CATALINA_OPTS
echo "CATALINA_OPTS=$CATALINA_OPTS"
exec "$CONFLUENCE_INSTALL_DIR/bin/start-confluence.sh" "$@"
<file_sep>/scripts/features/test.sh
#!/usr/bin/env bash
export CONFLUENCE_VERSION=$(curl -s https://marketplace.atlassian.com/rest/2/applications/confluence/versions/latest | jq -r '.version')
echo "$CONFLUENCE_VERSION"
|
b97c6c4d40bcfdcf43b0f1d837892a115854cd10
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 12
|
Shell
|
aruizca/docker-confluence-for-testing
|
637771596daca8902f2760db75cffe7cf37bebe8
|
c13ead7001bf8853705d9fb9da08732017d6b816
|
refs/heads/main
|
<repo_name>carolinefsil/DesafioJpa-<file_sep>/src/main/java/NovaAvaliacao.java
import models.Alunos;
import models.Avaliacao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class NovaAvaliacao {
public static void main(String... args) {
EntityManagerFactory entityManagerFactory
= Persistence.createEntityManagerFactory("models.Alunos-PU");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Alunos aluno = entityManager.find(Alunos.class, 1);
Avaliacao avaliacao = new Avaliacao();
avaliacao.setTitulo("Titulo1");
avaliacao.setDescricao("Esta é uma descrição");
avaliacao.setAlunos(aluno);
entityManager.getTransaction().begin();
entityManager.merge(aluno);
entityManager.persist(avaliacao);
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
}
}
<file_sep>/src/main/java/NovaCorrecao.java
import models.Alunos;
import models.Avaliacao;
import models.Correcao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class NovaCorrecao {
public static void main(String... args) {
EntityManagerFactory entityManagerFactory
= Persistence.createEntityManagerFactory("models.Alunos-PU");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Alunos aluno = entityManager.find(Alunos.class, 1);
Avaliacao avaliacao = entityManager.find(Avaliacao.class, 1);
Correcao correcao = new Correcao();
correcao.setNota(5);
correcao.setAlunos(aluno);
correcao.setAvaliacao(avaliacao);
entityManager.getTransaction().begin();
entityManager.merge(aluno);
entityManager.merge(avaliacao);
entityManager.persist(correcao);
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
}
}
<file_sep>/src/main/java/NovaResposta.java
import models.Alunos;
import models.Avaliacao;
import models.Correcao;
import models.Resposta;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class NovaResposta {
public static void main(String... args) {
EntityManagerFactory entityManagerFactory
= Persistence.createEntityManagerFactory("models.Alunos-PU");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Alunos aluno = entityManager.find(Alunos.class, 1);
Avaliacao avaliacao = entityManager.find(Avaliacao.class, 1);
Resposta resposta = new Resposta();
resposta.setResposta("Está é uma resposta");
resposta.setAlunos(aluno);
resposta.setAvaliacao(avaliacao);
entityManager.getTransaction().begin();
entityManager.merge(aluno);
entityManager.merge(avaliacao);
entityManager.persist(resposta);
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
}
}
<file_sep>/src/main/java/models/Correcao.java
package models;
import javax.persistence.*;
@Entity
@Table
public class Correcao {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idCorrecao;
private Integer nota;
@OneToOne
private Alunos alunos;
@OneToOne
private Avaliacao avaliacao;
public Alunos getAlunos() {
return alunos;
}
public void setAlunos(Alunos alunos) {
this.alunos = alunos;
}
public Avaliacao getAvaliacao() {
return avaliacao;
}
public void setAvaliacao(Avaliacao avaliacao) {
this.avaliacao = avaliacao;
}
public Integer getIdCorrecao() {
return idCorrecao;
}
public void setIdCorrecao(Integer idCorrecao) {
this.idCorrecao = idCorrecao;
}
public Integer getNota() {
return nota;
}
public void setNota(Integer nota) {
this.nota = nota;
}
}<file_sep>/src/main/java/BuscaResposta.java
import models.Alunos;
import models.Avaliacao;
import models.Resposta;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class BuscaResposta {
public static void main(String... args) {
EntityManagerFactory entityManagerFactory
= Persistence.createEntityManagerFactory("models.Alunos-PU");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Alunos alunos = entityManager.find(Alunos.class, 1);
Resposta resposta = entityManager.find(Resposta.class, 1);
Avaliacao avaliacao = entityManager.find(Avaliacao.class, 1);
System.out.println(alunos.getNome()+" respondeu a seguinte resposta " + resposta.getResposta()+" na avaliação de tipo "+ avaliacao.getTitulo());
entityManager.close();
entityManagerFactory.close();
}
}
<file_sep>/src/main/java/models/Alunos.java
package models;
import javax.persistence.*;
@Entity
@Table
public class Alunos {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idAluno;
private String email;
private String nome;
private Integer idade;
public Integer getIdAluno() {
return idAluno;
}
public void setIdAluno(Integer idAluno) {
this.idAluno = idAluno;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Integer getIdade() {
return idade;
}
public void setIdade(Integer idade) {
this.idade = idade;
}
}
|
79f320d8fd144ad750250b74e7539cda39afd1e2
|
[
"Java"
] | 6
|
Java
|
carolinefsil/DesafioJpa-
|
f528bc991d7b59964fcef9bc29d6652a2a308ad3
|
61f59c8be6ed9acb2e1d6eaa0adb36e1c48f184a
|
refs/heads/master
|
<file_sep>angular.module('starter.directives', [])
.directive('backImg', function($window) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('backImg', function(url) {
if (url) {
element.css({
'background-image': 'url(' + url + ')',
'background-size': 'cover',
'height': $window.innerHeight + 'px',
'background-position': 'center'
});
}
})
}
}
})
<file_sep>var express = require('express');
var router = express.Router();
/* GET categories listing. */
router.get('/', function(req, res, next) {
var articleid = req.query.articleid;
// ignore what article id is for now.
res.send({
status: true,
data: [
{
type: "fill in the blank",
question: 'The cow was in the %blank',
options: [
"house",
"field",
"barn"
]
},
{
id: 2,
title: 'Art',
thumbnail: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQb4sxM2QW5rdHwIAeny0HCHDBwjtgoLIiYJ20fJOxi3FSoEtlhaA'
}
]
});
});
module.exports = router;
<file_sep>var mongoose = require('mongoose');
var Schema = mongoose.Scheme;
var CatagorySchema = new Schema({
})
mongoose.model('Catagory', CatagorySchema)<file_sep>angular.module('starter.services', [])
.factory('Chats', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var chats = [{
id: 0,
name: 'الفن',
face: 'img/paint.png',
color: '#CE40AB'
}, {
id: 1,
name: 'العلوم',
face: 'img/science.png',
color: '#FFB24F'
}, {
id: 2,
name: 'الرياضة',
face: 'img/summer.png',
color: '#4289BC'
}, {
id: 3,
name: 'الحيوانات',
face: 'img/animals.png',
color: '#CCF64C'
}];
return {
all: function() {
return chats;
},
remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
get: function(chatId) {
for (var i = 0; i < chats.length; i++) {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
}
return null;
}
};
})
// .factory('Stories', function() {
// var stories = [{
// id: 0,
// name: '<NAME>',
// lastText: 'You on your way?',
// face: 'img/ben.png'
// }, {
// id: 1,
// name: '<NAME>',
// lastText: 'Hey, it\'s me',
// face: 'img/max.png'
// }, {
// id: 2,
// name: '<NAME>',
// lastText: 'I should buy a boat',
// face: 'img/adam.jpg'
// }, {
// id: 3,
// name: '<NAME>',
// lastText: 'Look at my mukluks!',
// face: 'img/perry.png'
// }, {
// id: 4,
// name: '<NAME>',
// lastText: 'This is wicked good ice cream.',
// face: 'img/mike.png'
// }];
// return {
// all: function() {
// return stories;
// },
// get: function(id) {
// var article = $scope.getArticle();
// for (var i = 0; i < stories.length; i++) {
// if (stories[i].id === parseInt(storyId)) {
// return stories[i];
// }
// }
// return article;
// }
// };
// })
;
<file_sep>var story;
var firstStory = 2;
var lastStory = 7;
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, $http) {
var currentStory = firstStory;
// var stories = Stories.all();
getStory();
function getStory() {
var jsonStory = getJsonStory()
return jsonStory;
}
function getJsonStory() {
console.log("requesting article");
// alert("requesting");
$http.get("http://localhost:3000/api/articles", { params: { "id": currentStory} })
.success(function(data) {
console.log("success");
console.log(currentStory);
console.log(data.background);
$scope.story = data;
if (data.question) {
$scope.quiz = data.question.data;
}
story = data;
console.log($scope.quiz.question);
return data;
})
.error(function(data) {
console.log("error");
alert("ERROR")
return null;
});
}
$scope.nextStory = function() {
currentStory++;
if (currentStory > lastStory) {
currentStory = firstStory;
}
var story = getStory();
};
$scope.previousStory = function() {
currentStory--;
if (currentStory < firstStory){
currentStory = lastStory;
}
var story = getStory();
};
})
.controller('ChatsCtrl', function($scope, Chats) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
};
})
.controller('RequestCtrl', function($scope, $http) {
$scope.getArticle = function() {
console.log("requesting article");
alert("requesting");
$http.get("http://localhost/api/articles", { params: { "id": 1} })
.success(function(data) {
alert("working")
console.log("success");
$scope.article = data.article;
})
.error(function(data) {
console.log("error");
alert("ERROR");
});
}
})
.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})
.controller('AccountCtrl', function($scope) {
// {
// answers: ['Rome','London', 'Paris'],
// correct: 'Rome',
// question: 'Where did this story take place?'
// }
$scope.quiz = story.question.data;
console.log(story.question);
$scope.settings = {
answer: '',
enableFriends: true
};
$scope.createTask = function() {
if($scope.settings.answer == $scope.quiz.correct) {
window.alert("TRUE!");
}
else {
window.alert("FALSE!");
}
};
}
)
.controller('MainCtrl', function($scope, $sce) {
$scope.trustSrc = function(src) {
return $sce.trustAsResourceUrl(src);
}
})
.controller('StatsCtrl', function($scope) {
$scope.numberReadBooks = 9;
$scope.numberReadWords = 451;
$scope.numberDays = 24;
})
.controller('SplashCtrl', function($scope) {
})
// $scope.createTask = function(radio_value) {
// console.log("Submitting");
//window.alert("Submitting text");
//};
<file_sep>Hacker 1:
<NAME>
American University in Beirut
Lebanon
ashariri95
<EMAIL>
Hacker 2:
<NAME>
University of Khartoum
Sudan
alaadaff
<EMAIL>
Hacker 3:
<NAME>
Princeton University
USA
kdhillon
<EMAIL>
Hacker 4:
<NAME>
Ecole nationale Supérieure d'Informatique (Alger)
Algeria
Ryuukarin
<EMAIL>
Hacker 5:
<NAME>
university of jordan
jordan
jomanajamal
<EMAIL>
Hacker 6:
<NAME>
UAEU
UAE
salkendi
<EMAIL>
Hacker 7:
<NAME>
Birzeit
Palestine
Nadine-H
<EMAIL>
Hacker 8:
<NAME>
Khalifa University
UAE
alifareed
<EMAIL>
Mentor 1:
<NAME>
Software Engineer Lead
Microsoft
Lebanon
mohamedmansour
<EMAIL>
Mentor 2:
<NAME>
Software Engineer
Google
Argentina
fabriph
<EMAIL>
Presentation
https://docs.google.com/presentation/d/1_crAkSn_8euUE4n5t9mPI-xPHNRJ_ob2SygEzYdfi0k/edit#slide=id.g124c18b2b2_3_12
|
22f78efddb1cb25affab97da0b52fe116c3a486c
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
NYUAD-Hackathon-2016/maktabti-reading-app-for-kids
|
4a2acc9717050ed6af16ded5ff05c384abfca3c5
|
db1fac6076e7492124bab81b79a0f035a131b5db
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.