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/main | <repo_name>saintclairsrf/ECOMP<file_sep>/CR/sem título1.py
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 11 09:35:17 2020
@author: saint
"""
import numpy as np
import igraph
import pandas as pd
# get the row, col indices of the non-zero elements in your adjacency matrix
conn_indices = np.where(a_numpy)
import igraph
# get the row, col indices of the non-zero elements in your adjacency matrix
conn_indices = np.where(a_numpy)
# get the weights corresponding to these indices
weights = a_numpy[conn_indices]
# a sequence of (i, j) tuples, each corresponding to an edge from i -> j
edges = zip(*conn_indices)
# initialize the graph from the edge sequence
G = igraph.Graph(edges=edges, directed=True)
# assign node names and weights to be attributes of the vertices and edges
# respectively
G.vs['label'] = node_names
G.es['weight'] = weights
# I will also assign the weights to the 'width' attribute of the edges. this
# means that igraph.plot will set the line thicknesses according to the edge
# weights
G.es['width'] = weights
# plot the graph, just for fun
igraph.plot(G, layout="rt", labels=True, margin=80)<file_sep>/CR/.ipynb_checkpoints/sem título0-checkpoint.py
import numpy as np
import igraph as ig
from igraph import *
import time
# function to check if x is power of 2
def isPowerOfTwo( x ):
# First x in the below expression is
# for the case when x is 0
return x and (not(x & (x - 1)))
# function to check whether the two numbers
# differ at one bit position only
def differAtOneBitPos( a , b ):
return isPowerOfTwo(a ^ b)
#Função graph é lenta para n grandes, estimo que ela seja O(n²)
def graph(n):
vertices = 2 ** n
arestas = []
grafo = Graph()
grafo.add_vertices(vertices)
for x in range(vertices):
for y in range(vertices):
if (differAtOneBitPos(x, y)):
if (y,x) not in arestas:
arestas.append((x,y))
grafo.add_edges(arestas)
return grafo, arestas
grafo, arestas = graph(3)
print(grafo)
print("------")
print(arestas)
tempoExecucao = []
tabLayout=[]
tabLayout=["random","circle","star","grid","graphopt","kamada_kawai","fruchterman_reingold","davidson_harel","mds","lgl"]
tab=[]
i=1
for i in range(len(tabLayout)):
layout = grafo.layout(tabLayout[i])
inicio = time.time()
arquivoPDF=tabLayout[i]+".png"
plot(grafo,arquivoPDF,layout=layout)
fim=time.time()
tempoExecucao= fim - inicio
tab.append(tabLayout[i])
tab.append(tempoExecucao)
print(tab)
print("Number of vertices in the graph:", grafo.vcount())
print("Number of edges in the graph", grafo.ecount())
print("Is the graph directed:", grafo.is_directed())
print("Maximum degree in the graph:", grafo.maxdegree())
print("Adjacency matrix:\n", grafo.get_adjacency())
<file_sep>/CR/sem título0.py
import numpy as np
import igraph as ig
from igraph import *
import time
import matplotlib.pyplot as plt
# function to check if x is power of 2
def isPowerOfTwo( x ):
# First x in the below expression is
# for the case when x is 0
return x and (not(x & (x - 1)))
# function to check whether the two numbers
# differ at one bit position only
def differAtOneBitPos( a , b ):
return isPowerOfTwo(a ^ b)
#Função graph é lenta para n grandes, estimo que ela seja O(n²)
def graph(n):
vertices = 2 ** n
arestas = []
grafo = Graph()
grafo.add_vertices(vertices)
for x in range(vertices):
for y in range(vertices):
if (differAtOneBitPos(x, y)):
if (y,x) not in arestas:
arestas.append((x,y))
grafo.add_edges(arestas)
return grafo, arestas
grafo, arestas = graph(3)
print("\n")
a=[]
a=grafo
print(type(a))
print("---------------------------", a.Read_GML)
print("Grafo ",grafo)
#print("\n")
print("Arestas", arestas)
print("\n")
print("Quantidade de arestas ==> ", len(arestas))
print("\n")
print("===== ")
summary(grafo)
print("Grafo ",grafo)
print("===== ")
tempoExecucao = []
tempoExecucao = np.array(tempoExecucao)
print(type(tempoExecucao))
tabLayout=[]
tabLayout=["random","circle","star","grid","graphopt","kamada_kawai","fruchterman_reingold","davidson_harel","mds","lgl"]
v=[]
for i in range(len(arestas)):
v.append(i)
tab=[]
i=1
for i in range(len(tabLayout)):
layout = grafo.layout(tabLayout[i])
inicio = time.time()
arquivoPDF=tabLayout[i]+".png"
grafo = Graph(vertex_attrs={"label": v, "color": "Cyan", "size": "30", "label_size" : "20"}, edges=arestas, directed=False)
plot(grafo,arquivoPDF,layout=layout)
plot(grafo.get_adjacency(), "aa.png", layout=layout)
fim=time.time()
tempoExecucao = fim - inicio
tab.append(tabLayout[i])
tab.append(tempoExecucao)
print (tabLayout[i],tempoExecucao )
print("\n")
print("Number of vertices in the graph:", grafo.vcount())
print("Number of edges in the graph", grafo.ecount())
print("Is the graph directed:", grafo.is_directed())
print("Maximum degree in the graph:", grafo.maxdegree())
print("Adjacency matrix:\n", grafo.get_adjacency())
plt.barh (tabLayout, tempoExecucao, color="red")
plt.show()
# plot(grafo, layout=layout, vertex_label=alfabeto, vertex_color="Blue", **visual_style)
#grafo = Graph(vertex_attrs={"label": v, "color": "Cyan"}, edges=arestas, directed=False)
#plot(grafo, layout=layout)
######################################################
"""
tempos = np.array([0.2979471683502197, 0.21873712539672852, 0.2164618968963623, 0.14659905433654785, 0.1934821605682373,
0.17554640769958496, 0.19448590278625488, 0.22937893867492676, 0.18954062461853027, 0.21442580223083496])
grafos = tabLayout
#print(type(tempos))
#tempos = np.array(tempoExecucao)
cores=['gold', 'red', 'blue', 'magenta', 'green','lightskyblue', 'yellowgreen', 'yellow', 'cyan', 'gray']
# o atributo explode indica que fatia do gráfico será destacada. No exemplo abaixo, será a primeira fatia. A quantidade de valores é igual ao número de fatias do gráfico.
#explode = (0.1, 0, 0, 0, 0, 0, 0) # explode 1st slice
# Atribuindo um título ao gráfico
plt.title("Tempos de geração dos grafos em segundos pizza")
#plt.pie(tempos, explode=explode, labels=grafos, colors=cores, autopct='%1.1f%%', shadow=True, startangle=90)
#plt.pie(tempos, labels=grafos, colors=cores, autopct='%1.2f%', shadow=True, startangle=90)
#plt.pie(tempos, labels=grafos, colors=cores, autopct='%1.2f%', shadow=True)
#plt.pie(tempos, labels=grafos, colors=cores)
#Adiciona Legenda
#plt.legend(grafos, bbox_to_anchor=(1.0, 1.0),loc='upper right')
#Centraliza o gráfico
plt.axis('equal')
#Ajusta o espaçamento para evitar o recorte do rótulo
#plt.tight_layout()
#plt.show()
#summary(tempos)
plt.title("Tempos de geração dos grafos em segundos boxplot")
plt.boxplot(tempos, main="Boxplot: tempos", col="blue")
plt.show()
""" | 7bd8da09fc8837af7268302008ea83700153008b | [
"Python"
]
| 3 | Python | saintclairsrf/ECOMP | c258b3a45e1834c034ad36626ea6551c3253ff27 | 7c2612584521a3106f70045a6f4e9a102054c7bb |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public GameObject activeObjectsFolder;//GameObject parent of other GameObjects that move during play
public GameObject levelObjectsFolder;//GameObject parent of other GameObjects that are part of the level
public Route currentRoute { get; private set; } = null;
public Route finishedRoute { get; private set; } = null;
public RoutePath routePath;
public float spawnDelay = 1;
private float lastSpawnTime = 0;
public Collider2D spawnBounds;
public GameObject prototype;
public TMP_Text milesLeftText;
public Camera mainCamera;
private void Start()
{
showMap(true);
currentRoute = null;
}
public void startRoute(Route route)
{
prototype.transform.position = Vector2.zero;
prototype.GetComponent<ShipController>().restoreHP();
showMap(false);
//Destroy current level objects
//2010-04-28: copied from http://answers.unity.com/answers/717490/view.html
int childs = levelObjectsFolder.transform.childCount;
for (int i = childs - 1; i > 0; i--)
{
Destroy(levelObjectsFolder.transform.GetChild(i).gameObject);
}
lastSpawnTime = Time.time;
currentRoute = route;
}
private void Update()
{
if (currentRoute)
{
if (Time.time > lastSpawnTime + spawnDelay)
{
lastSpawnTime += spawnDelay;
GameObject spawnedObject = currentRoute.spawnObject(spawnBounds.bounds);
spawnedObject.transform.parent = levelObjectsFolder.transform;
}
float milesLeft = Mathf.Max(0, currentRoute.distance - prototype.transform.position.y);
milesLeft = Mathf.Floor(milesLeft * 10) / 10;
milesLeftText.text = "" + milesLeft;
if (prototype.transform.position.y >= currentRoute.distance)
{
showMap(true);
finishedRoute = currentRoute;
routePath.routes.Add(finishedRoute);
currentRoute = null;
}
}
}
public void showMap(bool show)
{
milesLeftText.enabled = !show;
activeObjectsFolder.SetActive(!show);
mainCamera.gameObject.SetActive(!show);
if (show)
{
Scene mapScene = SceneManager.GetSceneByName("MapScene");
if (!mapScene.isLoaded)
{
SceneManager.LoadScene("MapScene", LoadSceneMode.Additive);
}
}
else
{
SceneManager.UnloadSceneAsync("MapScene");
routePath.display(false);
}
}
public void cancelRoute()
{
showMap(true);
currentRoute = null;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WrapBounds : MonoBehaviour
{
private Collider2D coll;
private void Start()
{
coll = GetComponent<Collider2D>();
}
private void OnTriggerExit2D(Collider2D other)
{
Vector2 diff = other.transform.position - transform.position;
if (Mathf.Abs(diff.x) > coll.bounds.size.x/2)
{
Vector2 pos = other.transform.position;
pos.x = transform.position.x - diff.x;
other.transform.position = pos;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Put this on a grouping prefab to split it into individual objects upon spawning
/// </summary>
public class PrefabUnpacker : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Transform parent = transform.parent;
foreach(Transform t in transform)
{
t.parent = parent;
}
Destroy(gameObject);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Line : MonoBehaviour
{
private SpriteRenderer sr;
// Start is called before the first frame update
void Start()
{
sr = GetComponent<SpriteRenderer>();
}
public void setEndPoints(int startID, int destinationID)
{
setEndPoints(
MapPoint.FindByID(startID).transform.position,
MapPoint.FindByID(destinationID).transform.position
);
}
public void setEndPoints(MapPoint start, MapPoint end)
{
setEndPoints(
start.transform.position,
end.transform.position
);
}
public void setEndPoints(Vector2 start, Vector2 end)
{
sr = GetComponent<SpriteRenderer>();
Vector2 diff = end - start;
transform.position = start + diff / 2;
transform.right = diff.normalized;
Vector2 size = sr.size;
size.x = diff.magnitude;
sr.size = size;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : ShipController
{
protected override Vector2 movementInput()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
return new Vector2(horizontal, vertical);
}
protected override bool fireInput()
{
return Input.GetButton("Fire");
}
protected override void destroy()
{
FindObjectOfType<GameManager>().cancelRoute();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShipAttack : ShipAbility
{
public float fireDelay = 0.1f;
public Vector2 fireDirection = Vector2.up;//direction relative to ship's forward direction
public Vector2 firePosition = Vector2.up;//position relative to ship's position and forward direction
public GameObject firePrefab;
private float lastFireTime = 0;
public override void activate(bool active)
{
if (active)
{
if (Time.time > lastFireTime + fireDelay)
{
lastFireTime = Time.time;
GameObject fire = Instantiate(firePrefab);
//TODO: 2020-04-29: make up direction relative to ship's forward direction
fire.transform.up = fireDirection;
fire.transform.position = (Vector2)transform.position + firePosition;
fire.GetComponent<ShotController>().driftSpeed = this.GetComponent<Rigidbody2D>().velocity.y;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Diagnostics;
using UnityEditor;
using UnityEngine.SceneManagement;
using Debug = UnityEngine.Debug;
using UnityEditor.SceneManagement;
using System;
using System.Linq;
public class CustomMenu
{//2022-05-16: copied from DwarfTower.CustomMenu
//Find Missing Scripts
//2018-04-13: copied from http://wiki.unity3d.com/index.php?title=FindMissingScripts
static int go_count = 0, components_count = 0, missing_count = 0;
[MenuItem("SG7/Editor/Refactor/Find Missing Scripts")]
private static void FindMissingScripts()
{
go_count = 0;
components_count = 0;
missing_count = 0;
for (int i = 0; i < SceneManager.sceneCount; i++)
{
Scene s = SceneManager.GetSceneAt(i);
if (s.isLoaded)
{
foreach (GameObject go in s.GetRootGameObjects())
{
FindInGO(go);
}
}
}
Debug.Log($"Searched {go_count} GameObjects, {components_count} components, found {missing_count} missing");
}
private static void FindInGO(GameObject go)
{
go_count++;
Component[] components = go.GetComponents<Component>();
for (int i = 0; i < components.Length; i++)
{
components_count++;
if (components[i] == null)
{
missing_count++;
string s = go.name;
Transform t = go.transform;
while (t.parent != null)
{
s = $"{t.parent.name}/{s}";
t = t.parent;
}
Debug.Log(
$"{s} has an empty script attached in position: {i}",
go
);
}
}
// Now recurse through each child GO (if there are any):
foreach (Transform childT in go.transform)
{
FindInGO(childT.gameObject);
}
}
[MenuItem("SG7/Editor/Show or Hide All Colliders %&c")]
public static void showHideAllColliders()
{
Physics2D.alwaysShowColliders = !Physics2D.alwaysShowColliders;
}
[MenuItem("SG7/Build/Build Windows %w")]
public static void buildWindows()
{
build(BuildTarget.StandaloneWindows, "exe");
}
//[MenuItem("SG7/Build/Build Linux %l")]
//public static void buildLinux()
//{
// build(BuildTarget.StandaloneLinux, "x86");
//}
//[MenuItem("SG7/Build/Build Mac OS X %#l")]
//public static void buildMacOSX()
//{
// build(BuildTarget.StandaloneOSX, "");
//}
public static void build(BuildTarget buildTarget, string extension, bool openDialog = true)
{
string defaultPath = getDefaultBuildPath();
if (!System.IO.Directory.Exists(defaultPath))
{
System.IO.Directory.CreateDirectory(defaultPath);
}
//2017-10-19 copied from https://docs.unity3d.com/Manual/BuildPlayerPipeline.html
// Get filename.
string buildName = getBuildNamePath(extension);
if (openDialog)
{
buildName = EditorUtility.SaveFilePanel(
"Choose Location of Built Game",
defaultPath,
PlayerSettings.productName,
extension
);
}
// User hit the cancel button.
if (buildName == "")
return;
string path = buildName.Substring(0, buildName.LastIndexOf("/"));
Debug.Log($"BUILDNAME: {buildName}");
Debug.Log($"PATH: {path}");
//Add scenes to build
string[] levels = new string[EditorBuildSettings.scenes.Length];
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
if (EditorBuildSettings.scenes[i].enabled)
{
levels[i] = EditorBuildSettings.scenes[i].path;
}
else
{
break;
}
}
// Build player.
BuildPipeline.BuildPlayer(
levels,
buildName,
buildTarget,
BuildOptions.None
);
// Run the game (Process class from System.Diagnostics).
Process proc = new Process();
proc.StartInfo.FileName = buildName;
proc.Start();
}
[MenuItem("SG7/Run/Run Windows %#w")]
public static void runWindows()
{
string extension = "exe";
string buildName = getBuildNamePath(extension);
Debug.Log($"Launching: {buildName}");
// Run the game (Process class from System.Diagnostics).
Process proc = new Process();
proc.StartInfo.FileName = buildName;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
proc.Start();
}
[MenuItem("SG7/Run/Open Build Folder #w")]
public static void openBuildFolder()
{
string extension = "exe";
string buildName = getBuildNamePath(extension);
//Open the folder where the game is located
EditorUtility.RevealInFinder(buildName);
}
public static string getDefaultBuildPath()
{
return $"{Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)}" +
$"/Unity/{PlayerSettings.productName}/Builds/" +
$"{PlayerSettings.productName}_{PlayerSettings.bundleVersion.Replace(".", "_")}";
}
public static string getBuildNamePath(string extension, bool checkFolderExists = true)
{
string defaultPath = getDefaultBuildPath();
if (checkFolderExists && !System.IO.Directory.Exists(defaultPath))
{
throw new UnityException(
$"You need to build the {extension} for {PlayerSettings.productName} " +
$"(Version {PlayerSettings.bundleVersion}) first!");
}
string buildName = $"{defaultPath}/{PlayerSettings.productName}.{extension}";
return buildName;
}
[MenuItem("SG7/Session/Begin Session")]
public static void beginSession()
{
Debug.Log("=== Beginning session ===");
string oldVersion = PlayerSettings.bundleVersion;
string[] split = oldVersion.Split('.');
string versionName = System.Text.RegularExpressions.Regex
.Replace(split[1], "[^0-9.]", "");
int versionNumber = int.Parse(versionName) + 1;
string newVersion = split[0] + "."
+ ((versionNumber < 100) ? "0" : "")
+ versionNumber;
PlayerSettings.bundleVersion = newVersion;
//Save and Log
EditorSceneManager.SaveOpenScenes();
Debug.LogWarning($"Updated build version number from {oldVersion} to {newVersion}");
}
[MenuItem("SG7/Session/Finish Session")]
public static void finishSession()
{
Debug.Log("=== Finishing session ===");
EditorSceneManager.SaveOpenScenes();
buildWindows();
//Open folders
openBuildFolder();
}
[MenuItem("SG7/Upgrade/Force save all assets")]
public static void forceSaveAllAssets()
{
AssetDatabase.ForceReserializeAssets();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeleteBounds : MonoBehaviour
{
private Collider2D coll;
private void Start()
{
coll = GetComponent<Collider2D>();
}
private void OnTriggerExit2D(Collider2D other)
{
if (gameObject.activeInHierarchy)
{
if (other.transform.position.y < coll.bounds.min.y)
{
Destroy(other.gameObject);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AsteroidController : ShipController
{
protected override Vector2 movementInput()
{
return Vector2.zero;
}
protected override bool fireInput()
{
return false;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class MapPoint : MonoBehaviour
{
public string locationName;
public MapArea mapArea;
public int id = 0;//unique id to distinguish between other MapPoints
public TMP_Text text;
private Collider2D coll;
// Start is called before the first frame update
void Start()
{
coll = GetComponent<Collider2D>();
}
public void highlight(bool show)
{
text.enabled = show;
if (show)
{
if (transform.localScale.x < 1)
{
transform.localScale *= 2;
}
}
else
{
if (transform.localScale.x >= 1)
{
transform.localScale /= 2;
}
}
}
public static MapPoint FindByID(int id)
{
foreach(MapPoint mp in FindObjectsOfType<MapPoint>())
{
if (mp.id == id)
{
return mp;
}
}
return null;
}
}
<file_sep>
using System.Collections.Generic;
using UnityEngine;
public class Route
{
public float distance;
public List<GameObject> objectPrefabs;
public int startID;
public int destinationID;
public Route(float distance, int startID, int destinationID, List<GameObject> objectPrefabs)
{
this.distance = distance;
this.startID = startID;
this.destinationID = destinationID;
this.objectPrefabs = objectPrefabs;
}
public GameObject spawnObject(Bounds bounds)
{
int randIndex = Random.Range(0, objectPrefabs.Count);
GameObject spawnedObject = GameObject.Instantiate(objectPrefabs[randIndex]);
spawnedObject.transform.position =
new Vector2(
Random.Range(bounds.min.x, bounds.max.x),
Random.Range(bounds.min.y, bounds.max.y)
);
return spawnedObject;
}
public static implicit operator bool(Route r)
=> r != null && !ReferenceEquals(r, null);
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class ShipController : MonoBehaviour
{
public float moveSpeed = 2;//how fast the ship can freely move
public float driftSpeed = 0;//how fast the ship is floating thru space
public int maxHP = 100;
private int _hp = 0;
public int HP
{
get => _hp;
set
{
_hp = Mathf.Clamp(value, 0, maxHP);
if (_hp == 0)
{
destroy();
}
}
}
public void restoreHP()
{
HP = maxHP;
}
public List<ShipAbility> abilities;
private Rigidbody2D rb2d;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
restoreHP();
}
// Update is called once per frame
void Update()
{
//Movement
Vector2 input = movementInput();
rb2d.velocity = (transform.up * input.y + transform.right * input.x).normalized * moveSpeed;
rb2d.velocity += Vector2.up * driftSpeed;
//Abilities
if (abilities.Count > 0)
{
if (fireInput())
{
foreach(ShipAbility ability in abilities)
{
ability.activate(true);
}
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
ShipController other = collision.gameObject.GetComponent<ShipController>();
if (other)
{
HP -= other.maxHP;
}
}
/// <summary>
/// The direction the ship wants to go
/// Does not include drift direction
/// </summary>
/// <returns></returns>
protected abstract Vector2 movementInput();
/// <summary>
/// Whether the ship is attacking using its attack
/// </summary>
/// <returns></returns>
protected abstract bool fireInput();
/// <summary>
/// Called when the ship's healthPoints reaches 0
/// </summary>
protected virtual void destroy()
{
Destroy(gameObject);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoutePath : MonoBehaviour
{
public List<Route> routes = new List<Route>();
public GameObject pathPrefab;
public void display(bool show)
{
//Destroy currently shown lines
int childs = transform.childCount;
for (int i = childs - 1; i > 0; i--)
{
Destroy(transform.GetChild(i).gameObject);
}
if (show)
{
//Make new line objects
foreach (Route route in routes)
{
GameObject line = Instantiate(pathPrefab);
line.transform.parent = transform;
line.GetComponent<Line>().setEndPoints(route.startID, route.destinationID);
Color color = line.GetComponent<SpriteRenderer>().color;
color.a = 0.5f;
line.GetComponent<SpriteRenderer>().color = color;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class ShipAbility : MonoBehaviour
{
public abstract void activate(bool active);
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapArea : MonoBehaviour
{
public string areaName;
public List<GameObject> objectPrefabs;
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.U2D;
using UnityEditor.SceneManagement;
[CanEditMultipleObjects]
[CustomEditor(typeof(MapPoint))]
public class MapPointEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
GUI.enabled = !EditorApplication.isPlaying;
if (GUILayout.Button("Default Location Name"))
{
foreach (Object obj in targets)
{
MapPoint mp = (MapPoint)obj;
mp.locationName = mp.gameObject.name;
mp.text.text = mp.locationName;
EditorUtility.SetDirty(mp);
EditorUtility.SetDirty(mp.text);
EditorSceneManager.MarkSceneDirty(mp.gameObject.scene);
}
}
if (GUILayout.Button("Default MapArea"))
{
foreach (Object obj in targets)
{
MapPoint mp = (MapPoint)obj;
foreach (MapArea ma in FindObjectsOfType<MapArea>())
{
if (ma.GetComponent<Collider2D>().OverlapPoint(mp.transform.position))
{
mp.mapArea = ma;
mp.GetComponent<SpriteRenderer>().color =
Color.Lerp(
ma.GetComponent<SpriteShapeRenderer>().color,
Color.white,
0.7f
);
EditorUtility.SetDirty(mp);
EditorSceneManager.MarkSceneDirty(mp.gameObject.scene);
break;
}
}
}
}
if (GUILayout.Button("Default ID"))
{
//Clear current ids
foreach (Object obj in targets)
{
MapPoint mp = (MapPoint)obj;
mp.id = 0;
}
//Find max id
int maxID = 0;
foreach (MapPoint mp in FindObjectsOfType<MapPoint>())
{
maxID = Mathf.Max(maxID, mp.id);
}
//Set current ids
foreach (Object obj in targets)
{
maxID++;
MapPoint mp = (MapPoint)obj;
mp.id = maxID;
EditorUtility.SetDirty(mp);
EditorSceneManager.MarkSceneDirty(mp.gameObject.scene);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MapManager : MonoBehaviour
{
public MapPoint currentMapPoint;//the map point where the ship is currently at
public MapPoint highlightMapPoint;//the map point the player is looking at
public MapPoint targetMapPoint;//the map point the player has selected to travel to next
public GameObject shipMarker;
public float markerBuffer = 0.5f;//distance between current map point and ship marker
public Line travelPath;
public float unitsToSpaceMiles = 45;//multiply by Unity units to get space miles
// Start is called before the first frame update
void Start()
{
GameManager gameManager = FindObjectOfType<GameManager>();
if (gameManager)
{
if (gameManager.finishedRoute)
{
currentMapPoint = MapPoint.FindByID(gameManager.finishedRoute.destinationID);
}
}
FindObjectOfType<RoutePath>().display(true);
}
// Update is called once per frame
void Update()
{
//Find map point to highlight
MapPoint mouseOverPoint = null;
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
foreach (MapPoint mp in FindObjectsOfType<MapPoint>())
{
if (mp.GetComponent<SpriteRenderer>().bounds.Contains(mousePos))
{
mouseOverPoint = mp;
break;
}
}
if (mouseOverPoint == null)
{
foreach (MapPoint mp in FindObjectsOfType<MapPoint>())
{
if (mp.GetComponent<Collider2D>().OverlapPoint(mousePos))
{
mouseOverPoint = mp;
break;
}
}
}
if (mouseOverPoint != highlightMapPoint)
{
highlightMapPoint?.highlight(false);
highlightMapPoint = mouseOverPoint;
highlightMapPoint?.highlight(true);
targetMapPoint?.highlight(true);
}
//Update ship marker
Vector2 targetPos = mousePos;
if (currentMapPoint == targetMapPoint || currentMapPoint == highlightMapPoint)
{
targetPos = (Vector2)currentMapPoint.transform.position + Vector2.up;
shipMarker.transform.up = Vector2.up;
shipMarker.transform.position = currentMapPoint.transform.position;
}
else
{
if (targetMapPoint)
{
targetPos = (Vector2)targetMapPoint.transform.position;
}
else if (highlightMapPoint)
{
targetPos = (Vector2)highlightMapPoint.transform.position;
}
Vector2 dir = (targetPos - (Vector2)currentMapPoint.transform.position).normalized;
shipMarker.transform.up = dir;
shipMarker.transform.position = (Vector2)currentMapPoint.transform.position + (dir * markerBuffer);
}
//Update target map point
if (Input.GetMouseButtonDown(0))
{
targetMapPoint?.highlight(false);
if (highlightMapPoint == targetMapPoint && targetMapPoint != null)
{
//Launch ship
List<GameObject> objectPrefabs = new List<GameObject>();
foreach (MapArea mp in FindObjectsOfType<MapArea>())
{
objectPrefabs.AddRange(mp.objectPrefabs);
}
Route route = new Route(
(targetMapPoint.transform.position - currentMapPoint.transform.position).magnitude * unitsToSpaceMiles,
currentMapPoint.id,
targetMapPoint.id,
objectPrefabs
); ;
FindObjectOfType<GameManager>().startRoute(route);
}
if (highlightMapPoint != currentMapPoint)
{
targetMapPoint = highlightMapPoint;
}
else
{
targetMapPoint = null;
}
if (targetMapPoint)
{
travelPath.gameObject.SetActive(true);
travelPath.setEndPoints(currentMapPoint, targetMapPoint);
}
else
{
travelPath.gameObject.SetActive(false);
}
}
}
}
| fd518f130489fe46f04f074c15df8157791210ff | [
"C#"
]
| 17 | C# | shieldgenerator7/AdaptivePrototype | 07cb2af8e7bc239e9633771b4370e784b5cc1567 | 3dd874bf950391671816389f33ba4e537e3e4b96 |
refs/heads/master | <repo_name>DerLampe/Hausaufgaben<file_sep>/Memory/src/Memory.java
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
/**
* Ein einfaches Memory-Spiel
* @author <NAME> 4633121 Gruppe 11b
* erstellt am 11.01.2017.
*/
final public class Memory extends JFrame {
//Variablen der Grafikkomponenten
private Container container;
private JPanel spielPanel = new JPanel();
private JPanel diversesPanel = new JPanel();
private BorderLayout masterLayout = new BorderLayout(50, 10);
private GridLayout spielLayout = new GridLayout(4, 5, 10, 10);
private GridLayout diversesLayout = new GridLayout(5, 1, 10, 30);
private JLabel lblBesteRunde, lblAnzahlVersuche, lblKommentar;
private Font font = new Font("Comic Sans MS", Font.BOLD, 14);
private JLabel lblA0, lblA1, lblA2, lblA3, lblA4;
private JLabel lblB0, lblB1, lblB2, lblB3, lblB4;
private JLabel lblC0, lblC1, lblC2, lblC3, lblC4;
private JLabel lblD0, lblD1, lblD2, lblD3, lblD4;
private final int cardWidth = 100;
private final int cardHeight = 100;
private Dimension d = new Dimension(cardWidth, cardHeight);
private Border cardBorder = BorderFactory.createLineBorder(Color.BLACK, 1);
private final Color schwarz = new Color(0, 0, 0);
private final Color weiss = new Color(255, 255, 255);
private final Color rot = new Color(255, 0, 0);
private final Color gelb = new Color(255, 255, 0);
private final Color gruen = new Color(0, 100, 0);
private final Color blau = new Color(0, 0, 255);
private final Color grau = new Color(56, 56, 56);
private final Color magenta = new Color(255, 0, 255);
private final Color braun = new Color(85, 42, 19);
private final Color orange = new Color(255, 125, 0);
//Variablen der Spiellogik
private int zugNr = 0;
private int ersteKarte;
private int zweiteKarte;
private int anzahlVersuche = 0;
private int korrektAufgedeckt = 0;
private int besteRunde = Integer.MAX_VALUE;
private Color[] farben = {schwarz, schwarz, weiss, weiss, rot, rot, gelb, gelb, gruen, gruen, blau, blau, grau,
grau, magenta, magenta, braun, braun, orange, orange};
/**
* Erstellt den Frame fuer das Spiel
* @param name Name des Spielers, welcher in der Titelleiste verwendet wird
*/
private Memory(String name) {
setTitle("Memory - Spiel von " + name);
setLocation(500, 300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
container = getContentPane();
container.setLayout(masterLayout);
container.add(spielPanel, BorderLayout.CENTER);
container.add(diversesPanel, BorderLayout.EAST);
spielPanel.setLayout(spielLayout);
spielPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
lblA0 = new JLabel();
lblA0.setBackground(Color.LIGHT_GRAY);
lblA0.setOpaque(true);
lblA0.setPreferredSize(d);
lblA0.setBorder(cardBorder);
lblA0.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(0);
}
});
spielPanel.add(lblA0);
lblA1 = new JLabel();
lblA1.setBackground(Color.LIGHT_GRAY);
lblA1.setOpaque(true);
lblA1.setPreferredSize(d);
lblA1.setBorder(cardBorder);
lblA1.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(1);
}
});
spielPanel.add(lblA1);
lblA2 = new JLabel();
lblA2.setBackground(Color.LIGHT_GRAY);
lblA2.setOpaque(true);
lblA2.setPreferredSize(d);
lblA2.setBorder(cardBorder);
lblA2.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(2);
}
});
spielPanel.add(lblA2);
lblA3 = new JLabel();
lblA3.setBackground(Color.LIGHT_GRAY);
lblA3.setOpaque(true);
lblA3.setPreferredSize(d);
lblA3.setBorder(cardBorder);
lblA3.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(3);
}
});
spielPanel.add(lblA3);
lblA4 = new JLabel();
lblA4.setBackground(Color.LIGHT_GRAY);
lblA4.setOpaque(true);
lblA4.setPreferredSize(d);
lblA4.setBorder(cardBorder);
lblA4.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(4);
}
});
spielPanel.add(lblA4);
lblB0 = new JLabel();
lblB0.setBackground(Color.LIGHT_GRAY);
lblB0.setOpaque(true);
lblB0.setPreferredSize(d);
lblB0.setBorder(cardBorder);
lblB0.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(5);
}
});
spielPanel.add(lblB0);
lblB1 = new JLabel();
lblB1.setBackground(Color.LIGHT_GRAY);
lblB1.setOpaque(true);
lblB1.setPreferredSize(d);
lblB1.setBorder(cardBorder);
lblB1.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(6);
}
});
spielPanel.add(lblB1);
lblB2 = new JLabel();
lblB2.setBackground(Color.LIGHT_GRAY);
lblB2.setOpaque(true);
lblB2.setPreferredSize(d);
lblB2.setBorder(cardBorder);
lblB2.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(7);
}
});
spielPanel.add(lblB2);
lblB3 = new JLabel();
lblB3.setBackground(Color.LIGHT_GRAY);
lblB3.setOpaque(true);
lblB3.setPreferredSize(d);
lblB3.setBorder(cardBorder);
lblB3.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(8);
}
});
spielPanel.add(lblB3);
lblB4 = new JLabel();
lblB4.setBackground(Color.LIGHT_GRAY);
lblB4.setOpaque(true);
lblB4.setPreferredSize(d);
lblB4.setBorder(cardBorder);
lblB4.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(9);
}
});
spielPanel.add(lblB4);
lblC0 = new JLabel();
lblC0.setBackground(Color.LIGHT_GRAY);
lblC0.setOpaque(true);
lblC0.setPreferredSize(d);
lblC0.setBorder(cardBorder);
lblC0.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(10);
}
});
spielPanel.add(lblC0);
lblC1 = new JLabel();
lblC1.setBackground(Color.LIGHT_GRAY);
lblC1.setOpaque(true);
lblC1.setPreferredSize(d);
lblC1.setBorder(cardBorder);
lblC1.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(11);
}
});
spielPanel.add(lblC1);
lblC2 = new JLabel();
lblC2.setBackground(Color.LIGHT_GRAY);
lblC2.setOpaque(true);
lblC2.setPreferredSize(d);
lblC2.setBorder(cardBorder);
lblC2.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(12);
}
});
spielPanel.add(lblC2);
lblC3 = new JLabel();
lblC3.setBackground(Color.LIGHT_GRAY);
lblC3.setOpaque(true);
lblC3.setPreferredSize(d);
lblC3.setBorder(cardBorder);
lblC3.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(13);
}
});
spielPanel.add(lblC3);
lblC4 = new JLabel();
lblC4.setBackground(Color.LIGHT_GRAY);
lblC4.setOpaque(true);
lblC4.setPreferredSize(d);
lblC4.setBorder(cardBorder);
lblC4.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(14);
}
});
spielPanel.add(lblC4);
lblD0 = new JLabel();
lblD0.setBackground(Color.LIGHT_GRAY);
lblD0.setOpaque(true);
lblD0.setPreferredSize(d);
lblD0.setBorder(cardBorder);
lblD0.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(15);
}
});
spielPanel.add(lblD0);
lblD1 = new JLabel();
lblD1.setBackground(Color.LIGHT_GRAY);
lblD1.setOpaque(true);
lblD1.setPreferredSize(d);
lblD1.setBorder(cardBorder);
lblD1.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(16);
}
});
spielPanel.add(lblD1);
lblD2 = new JLabel();
lblD2.setBackground(Color.LIGHT_GRAY);
lblD2.setOpaque(true);
lblD2.setPreferredSize(d);
lblD2.setBorder(cardBorder);
lblD2.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(17);
}
});
spielPanel.add(lblD2);
lblD3 = new JLabel();
lblD3.setBackground(Color.LIGHT_GRAY);
lblD3.setOpaque(true);
lblD3.setPreferredSize(d);
lblD3.setBorder(cardBorder);
lblD3.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(18);
}
});
spielPanel.add(lblD3);
lblD4 = new JLabel();
lblD4.setBackground(Color.LIGHT_GRAY);
lblD4.setOpaque(true);
lblD4.setPreferredSize(d);
lblD4.setBorder(cardBorder);
lblD4.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
spielzug(19);
}
});
spielPanel.add(lblD4);
diversesPanel.setLayout(diversesLayout);
diversesPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
lblKommentar = new JLabel("<NAME>!");
lblKommentar.setFont(font);
diversesPanel.add(lblKommentar);
lblAnzahlVersuche = new JLabel("Anzahl Versuche: 0");
lblAnzahlVersuche.setFont(font);
diversesPanel.add(lblAnzahlVersuche);
lblBesteRunde = new JLabel("Beste Runde: ");
lblBesteRunde.setFont(font);
diversesPanel.add(lblBesteRunde);
JButton btnReset = new JButton("Neustart");
btnReset.setPreferredSize(new Dimension(100, 20));
btnReset.setFont(font);
btnReset.addActionListener(e -> neustart());
diversesPanel.add(btnReset);
JButton btnEnde = new JButton("Beenden");
btnEnde.setPreferredSize(new Dimension(100, 20));
btnEnde.setFont(font);
btnEnde.addActionListener(e -> System.exit(0));
diversesPanel.add(btnEnde);
pack();
}
/**
* Deckt die angeklickte Karte auf und vergleicht, ob die Bilder gleich sind
* @param button "Koordinaten" der angeklickten Schaltflaeche
*/
private void spielzug(int button) {
zugNr++;
switch (zugNr) {
case 1:
karteUmdrehen(ersteKarte);
karteUmdrehen(zweiteKarte);
ersteKarte = button;
karteAufdecken(button);
break;
case 2:
anzahlVersuche++;
zweiteKarte = button;
karteAufdecken(button);
if ((ersteKarte != zweiteKarte) && (farben[ersteKarte] == farben[zweiteKarte])) {
lblKommentar.setText("Richtig!");
korrektAufgedeckt++;
karteEntfernen(ersteKarte);
karteEntfernen(zweiteKarte);
} else {
lblKommentar.setText("Leider falsch");
}
lblAnzahlVersuche.setText("Anzahl Versuche: " + anzahlVersuche);
if (korrektAufgedeckt == 10) {
rekordFestlegen(anzahlVersuche);
JOptionPane.showMessageDialog(null, "Du hast Gewonnen!");
}
zugNr = 0;
break;
}
}
/**
* Deckt eine Karte auf indem das entsprechende Label mit der zugehoerigen Farbe gefaerbt wird
* @param label Label welches gefaerbt werden soll
*/
private void karteAufdecken(int label) {
switch (label) {
case 0:
lblA0.setBackground(farben[label]);
break;
case 1:
lblA1.setBackground(farben[label]);
break;
case 2:
lblA2.setBackground(farben[label]);
break;
case 3:
lblA3.setBackground(farben[label]);
break;
case 4:
lblA4.setBackground(farben[label]);
break;
case 5:
lblB0.setBackground(farben[label]);
break;
case 6:
lblB1.setBackground(farben[label]);
break;
case 7:
lblB2.setBackground(farben[label]);
break;
case 8:
lblB3.setBackground(farben[label]);
break;
case 9:
lblB4.setBackground(farben[label]);
break;
case 10:
lblC0.setBackground(farben[label]);
break;
case 11:
lblC1.setBackground(farben[label]);
break;
case 12:
lblC2.setBackground(farben[label]);
break;
case 13:
lblC3.setBackground(farben[label]);
break;
case 14:
lblC4.setBackground(farben[label]);
break;
case 15:
lblD0.setBackground(farben[label]);
break;
case 16:
lblD1.setBackground(farben[label]);
break;
case 17:
lblD2.setBackground(farben[label]);
break;
case 18:
lblD3.setBackground(farben[label]);
break;
case 19:
lblD4.setBackground(farben[label]);
break;
}
}
/**
* Dreht eine Karte wieder auf ihre Rueckseite indem das Label grau gefärbt wird
* @param label Label welches gefaerbt werden soll
*/
private void karteUmdrehen(int label) {
switch (label) {
case 0:
lblA0.setBackground(Color.LIGHT_GRAY);
break;
case 1:
lblA1.setBackground(Color.LIGHT_GRAY);
break;
case 2:
lblA2.setBackground(Color.LIGHT_GRAY);
break;
case 3:
lblA3.setBackground(Color.LIGHT_GRAY);
break;
case 4:
lblA4.setBackground(Color.LIGHT_GRAY);
break;
case 5:
lblB0.setBackground(Color.LIGHT_GRAY);
break;
case 6:
lblB1.setBackground(Color.LIGHT_GRAY);
break;
case 7:
lblB2.setBackground(Color.LIGHT_GRAY);
break;
case 8:
lblB3.setBackground(Color.LIGHT_GRAY);
break;
case 9:
lblB4.setBackground(Color.LIGHT_GRAY);
break;
case 10:
lblC0.setBackground(Color.LIGHT_GRAY);
break;
case 11:
lblC1.setBackground(Color.LIGHT_GRAY);
break;
case 12:
lblC2.setBackground(Color.LIGHT_GRAY);
break;
case 13:
lblC3.setBackground(Color.LIGHT_GRAY);
break;
case 14:
lblC4.setBackground(Color.LIGHT_GRAY);
break;
case 15:
lblD0.setBackground(Color.LIGHT_GRAY);
break;
case 16:
lblD1.setBackground(Color.LIGHT_GRAY);
break;
case 17:
lblD2.setBackground(Color.LIGHT_GRAY);
break;
case 18:
lblD3.setBackground(Color.LIGHT_GRAY);
break;
case 19:
lblD4.setBackground(Color.LIGHT_GRAY);
break;
}
}
/**
* Entfernt Karte vom Spielfeld, sodass sie nicht mehr angeklickt werden kann
* @param label Karte welche entfernt werden soll
*/
private void karteEntfernen(int label) {
switch (label) {
case 0:
lblA0.setVisible(false);
break;
case 1:
lblA1.setVisible(false);
break;
case 2:
lblA2.setVisible(false);
break;
case 3:
lblA3.setVisible(false);
break;
case 4:
lblA4.setVisible(false);
break;
case 5:
lblB0.setVisible(false);
break;
case 6:
lblB1.setVisible(false);
break;
case 7:
lblB2.setVisible(false);
break;
case 8:
lblB3.setVisible(false);
break;
case 9:
lblB4.setVisible(false);
break;
case 10:
lblC0.setVisible(false);
break;
case 11:
lblC1.setVisible(false);
break;
case 12:
lblC2.setVisible(false);
break;
case 13:
lblC3.setVisible(false);
break;
case 14:
lblC4.setVisible(false);
break;
case 15:
lblD0.setVisible(false);
break;
case 16:
lblD1.setVisible(false);
break;
case 17:
lblD2.setVisible(false);
break;
case 18:
lblD3.setVisible(false);
break;
case 19:
lblD4.setVisible(false);
break;
}
}
/**
* prueft ob ein neuer Rekord aufgestellt wurde und passt die Anzeige entsprechend an
* @param versuche Anzahl benoetigter Versuche der abgeschlossenen Runde
*/
private void rekordFestlegen(int versuche) {
if (versuche < besteRunde) {
lblBesteRunde.setText("Beste Runde: " + versuche);
}
}
/**
* "Legt" die Karte wieder auf das Spielfeld
* @param label Karte welche wieder auf das Spielfeld gelegt werden soll
*/
private void karteSichtbarMachen(int label) {
switch (label) {
case 0:
lblA0.setVisible(true);
break;
case 1:
lblA1.setVisible(true);
break;
case 2:
lblA2.setVisible(true);
break;
case 3:
lblA3.setVisible(true);
break;
case 4:
lblA4.setVisible(true);
break;
case 5:
lblB0.setVisible(true);
break;
case 6:
lblB1.setVisible(true);
break;
case 7:
lblB2.setVisible(true);
break;
case 8:
lblB3.setVisible(true);
break;
case 9:
lblB4.setVisible(true);
break;
case 10:
lblC0.setVisible(true);
break;
case 11:
lblC1.setVisible(true);
break;
case 12:
lblC2.setVisible(true);
break;
case 13:
lblC3.setVisible(true);
break;
case 14:
lblC4.setVisible(true);
break;
case 15:
lblD0.setVisible(true);
break;
case 16:
lblD1.setVisible(true);
break;
case 17:
lblD2.setVisible(true);
break;
case 18:
lblD3.setVisible(true);
break;
case 19:
lblD4.setVisible(true);
break;
}
}
/**
* Initialisiert ein neuen Spiel. Die Karten werden neu gemischt und wieder verdeckt.
*/
private void neustart() {
zugNr = 0;
anzahlVersuche = 0;
lblAnzahlVersuche.setText("Anzahl Versuche: " + anzahlVersuche);
korrektAufgedeckt = 0;
for (int i = 0; i <= 19; i++) {
karteUmdrehen(i);
karteSichtbarMachen(i);
}
farbenMischen(farben);
}
/**
* Mischt die Farben im Array, sodass die Karten bei Rundenanfang zufaellig verteilt werden
* @param array Array vom Typ Color[] welches gemischt werden soll
*/
private void farbenMischen(Color[] array) {
int index;
Color temp;
Random rand = new Random();
for (int i = array.length - 1; i > 0; i--) {
index = rand.nextInt(i + 1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
public static void main(String[] args) {
Memory memory = new Memory(JOptionPane.showInputDialog("Bitte gebe deinen Namen ein"));
memory.farbenMischen(memory.farben);
memory.setVisible(true);
}
}
<file_sep>/Blatt12/src/Graph.java
import java.util.List;
/**
* @author <NAME> 4633121 Gruppe 11b
* erstellt am 30.12.2016.
*/
public class Graph {
private final List<Vertex> vertices;
private final List<Edge> edges;
/**
* Konstruktor, zur Erstellung eines Graph-Objektes
* @param vertices Liste der Ecken
* @param edges Liste der Kanten
*/
public Graph(List<Vertex> vertices, List<Edge> edges) {
this.vertices = vertices;
this.edges = edges;
}
public List<Vertex> getVertices() {
return vertices;
}
public List<Edge> getEdges() {
return edges;
}
}
<file_sep>/README.md
Hausaufgaben - Programmieren II
<file_sep>/Blatt10/src/DoubleLinkedListTest.java
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @author <NAME> 4633121 Gruppe 11b
* erstellt am 15.11.2016.
*/
public class DoubleLinkedListTest {
public static void main(String[] args) {
BufferedReader br;
DoubleLinkedList list = new DoubleLinkedList();
try {
br = Files.newBufferedReader(Paths.get("languages.csv"));
String line;
String[] data;
br.readLine();
while ((line = br.readLine()) != null) {
data = line.split(",");
list.insert(new Language(data[0], data[1], data[2], data[3], data[4], data[5]));
}
br.close();
} catch (IOException e) {
System.out.println("File not found");
e.printStackTrace();
return;
}
System.out.printf("%16s | %8s | %12s | %8s | %10s | %10s%n", "Name", "Appeared", "Distribution", "Dialects", "Nerdfactor", "HelloWorld");
System.out.println("-------------------------------------------------------------------------------");
System.out.println(list.toString());
}
}
<file_sep>/Blatt11/src/Language.java
/**
* @author <NAME> 4633121 Gruppe 11b
* erstellt am 29.11.2016.
*/
public class Language implements Comparable<Language> {
private String name;
private int appeared;
private int distribution;
private String dialects;
private int nerdFactor;
private int helloWorldLength;
/**
* Konstruktor fuer ein neues Language Objekt
*
* @param name Name der Sprache
* @param appeared Release der Sprache
* @param distribution Distributionen der Sprache
* @param dialects Dialekte der Sprache
* @param nerdFactor Nerdfaktor der Sprache
* @param helloWorldLength Laenge von HelloWorld
*/
public Language(String name, String appeared, String distribution, String dialects,
String nerdFactor, String helloWorldLength) {
this.name = name;
this.appeared = Integer.parseInt(appeared);
this.distribution = Integer.parseInt(distribution);
this.dialects = dialects;
this.nerdFactor = Integer.parseInt(nerdFactor);
this.helloWorldLength = Integer.parseInt(helloWorldLength);
}
public int getAppeared() {
return appeared;
}
public int getHelloWorldLength() {
return helloWorldLength;
}
@Override
public String toString() {
return String.format("%16s | %8d | %12d | %8s | %010d | %10s", name, appeared, distribution, dialects,
nerdFactor, helloWorldLength);
}
/**
* Compares this object with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.
* <p>
* <p>The implementor must ensure <tt>sgn(x.compareTo(y)) ==
* -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This
* implies that <tt>x.compareTo(y)</tt> must throw an exception iff
* <tt>y.compareTo(x)</tt> throws an exception.)
* <p>
* <p>The implementor must also ensure that the relation is transitive:
* <tt>(x.compareTo(y)>0 && y.compareTo(z)>0)</tt> implies
* <tt>x.compareTo(z)>0</tt>.
* <p>
* <p>Finally, the implementor must ensure that <tt>x.compareTo(y)==0</tt>
* implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for
* all <tt>z</tt>.
* <p>
* <p>It is strongly recommended, but <i>not</i> strictly required that
* <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>. Generally speaking, any
* class that implements the <tt>Comparable</tt> interface and violates
* this condition should clearly indicate this fact. The recommended
* language is "Note: this class has a natural ordering that is
* inconsistent with equals."
* <p>
* <p>In the foregoing description, the notation
* <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
* <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
* <tt>0</tt>, or <tt>1</tt> according to whether the value of
* <i>expression</i> is negative, zero or positive.
*
* @param o the object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
* @throws NullPointerException if the specified object is null
* @throws ClassCastException if the specified object's type prevents it
* from being compared to this object.
*/
@Override
public int compareTo(Language o) {
return Integer.compare(appeared, o.appeared);
}
}
<file_sep>/Blatt10/src/Language.java
/**
* @author <NAME> 4633121 Gruppe 11b
* erstellt am 15.11.2016.
*/
public class Language {
private String name;
private int appeared;
private int distribution;
private String dialects;
private int nerdFactor;
private int helloWorldLength;
/**
* Konstruktor fuer ein neues Language Objekt
*
* @param name Name der Sprache
* @param appeared Release der Sprache
* @param distribution Distributionen der Sprache
* @param dialects Dialekte der Sprache
* @param nerdFactor Nerdfaktor der Sprache
* @param helloWorldLength Laenge von HelloWorld
*/
public Language(String name, String appeared, String distribution, String dialects,
String nerdFactor, String helloWorldLength) {
this.name = name;
this.appeared = Integer.parseInt(appeared);
this.distribution = Integer.parseInt(distribution);
this.dialects = dialects;
this.nerdFactor = Integer.parseInt(nerdFactor);
this.helloWorldLength = Integer.parseInt(helloWorldLength);
}
public int getAppeared() {
return appeared;
}
@Override
public String toString() {
return String.format("%16s | %8d | %12d | %8s | %010d | %10s", name, appeared, distribution, dialects,
nerdFactor, helloWorldLength);
}
}
<file_sep>/Blatt12/src/Vertex.java
/**
* @author <NAME> 4633121 Gruppe 11b
* erstellt am 30.12.2016.
*/
public class Vertex {
final private String name;
/**
* Konstrukur, zur Erstellung eines Vertex-Objektes
* @param name Name der Ecke
*/
public Vertex(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
| 03c7d2585c581665ebd372f04ec7292f54553c19 | [
"Markdown",
"Java"
]
| 7 | Java | DerLampe/Hausaufgaben | c52974ee95454fae46f7b1bab4b6b231c7f51ea3 | 3656b1dc31e4b13effeda4ca5b08b05fe5b05b63 |
refs/heads/master | <repo_name>OlegYakovlev1/Reminder<file_sep>/app/src/main/java/com/example/android/reminder/Constants.java
package com.example.android.reminder;
public class Constants {
public static final int TAB_NOTIFICATION = 0;
public static final int TAB_2 = 1;
public static final int TAB_3 = 2;
}
<file_sep>/app/src/main/java/com/example/android/reminder/fragments/AddNotificationFragment.java
package com.example.android.reminder.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import com.example.android.reminder.R;
import com.example.android.reminder.beans.Notification;
import com.example.android.reminder.db.DatabaseHelper;
public class AddNotificationFragment extends DialogFragment {
EditText editTextTitle;
EditText editTextDescription;
EditText editTextDate;
private OnDBChangedListener mCallback;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_add_notification, null);
editTextTitle = (EditText) view.findViewById(R.id.editTxtAddTitle);
editTextDescription = (EditText) view.findViewById(R.id.editTxtAddDesc);
editTextDate = (EditText) view.findViewById(R.id.editTxtAddDate);
builder.setView(view)
.setTitle(R.string.add_notification_title)
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
addNewNotification();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
editTextDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDatePickerDialog();
}
});
return builder.create();
}
public void showDatePickerDialog() {
DialogFragment datePickerFragment = new DatePickerFragment(){
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
editTextDate.setText(year + "-" + monthOfYear + "-" + dayOfMonth);
}
};
datePickerFragment.show(getFragmentManager(), "datePicker");
}
public void addNewNotification(){
try {
DatabaseHelper db = new DatabaseHelper(getActivity());
db.addNotification(new Notification(editTextTitle.getText().toString(),
editTextDescription.getText().toString(),
editTextDate.getText().toString()));
db.close();
}catch (Exception e){
Toast toast = Toast.makeText(getActivity(),"Error:"+ e.toString(),Toast.LENGTH_SHORT);
toast.show();
}
}
public interface OnDBChangedListener {
public void onDBNotificationChanged();
}
@Override
public void onDismiss(DialogInterface dialog) {
Log.v("TEST","onDismiss");
mCallback.onDBNotificationChanged();
super.onDismiss(dialog);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnDBChangedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnDBChangedListener");
}
}
}
<file_sep>/README.md
# Reminder
Reminder. Test android project
<file_sep>/app/src/main/java/com/example/android/reminder/services/NotificationService.java
package com.example.android.reminder.services;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import java.util.Calendar;
public class NotificationService extends Service{
public static final int INTERVAL = 1000*60; // 1 min
private int firstRun;
private int requestCode = 1234;
private AlarmManager alarmManager;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
firstRun = (60 - Calendar.getInstance().get(Calendar.SECOND))*1000;
startService();
}
private void startService(){
Intent intent = new Intent(this, RepeatingAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + firstRun,
INTERVAL,
pendingIntent);
Log.v("Test", "Calendar: "+Calendar.getInstance().get(Calendar.SECOND) + "First run: "+firstRun + " system clock: "+SystemClock.elapsedRealtime());
Toast.makeText(this, "Service Started.", Toast.LENGTH_LONG).show();
Log.v("Test", "AlarmManger started at " + new java.sql.Timestamp(System.currentTimeMillis()).toString());
}
@Override
public void onDestroy() {
if (alarmManager != null) {
Intent intent = new Intent(this, RepeatingAlarmService.class);
alarmManager.cancel(PendingIntent.getBroadcast(this, requestCode, intent, 0));
}
Toast.makeText(this, "Service Stopped!", Toast.LENGTH_LONG).show();
Log.v("Test", "Service onDestroy(). Stop AlarmManager at " + new java.sql.Timestamp(System.currentTimeMillis()).toString());
super.onDestroy();
}
}
| b964562123e92ad260fbede2a6b5cefbe4bdc907 | [
"Markdown",
"Java"
]
| 4 | Java | OlegYakovlev1/Reminder | d6e25fd54b2c953232c898f8fcb906d674009a66 | 3300f5bff85bab3997a553263115f4365d570d4e |
refs/heads/master | <repo_name>ShaunSEMO/settlement<file_sep>/storage/framework/views/b8a4cb25590cceac9ad103c1beb1403dc90dd7b8.php
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="<?php echo e(asset('/asset/css/main.css')); ?>">
<title>Settlement</title>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<a class="navbar-brand" href="#">
<img src="<?php echo e(asset('/asset/img/bootstrap-solid.svg')); ?>" width="30" height="30" class="d-inline-block align-top" alt="" loading="lazy"> Bootstrap
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
</div>
</nav>
<div class="formWrapper">
<form>
<div class="upSpace"></div>
<div class="form-group">
<label for="exampleFormControlInput1">Email address</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="<EMAIL>">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Example select</label>
<select class="form-control" id="exampleFormControlSelect1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlSelect2">Example multiple select</label>
<select multiple class="form-control" id="exampleFormControlSelect2">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Example textarea</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
</form>
<div class="map-div">
<div class="map">
<button id="find-me">Get Coordinates</button><br />
<p id="status"></p>
<a id="map-link" target="_blank"></a>
<br>
<div id="map"></div>
</div>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email address</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="<EMAIL>">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Example select</label>
<select class="form-control" id="exampleFormControlSelect1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<!-- <div class="container" style="padding: 100px;"> -->
<!-- </div> -->
</div>
<!-- Optional JavaScript -->
<script>
function geoFindMe() {
const status = document.querySelector('#status');
const mapLink = document.querySelector('#map-link');
mapLink.href = '';
mapLink.textContent = '';
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
status.textContent = '';
mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
}
function error() {
status.textContent = 'Unable to retrieve your location';
}
if (!navigator.geolocation) {
status.textContent = 'Geolocation is not supported by your browser';
} else {
status.textContent = 'Locating…';
navigator.geolocation.getCurrentPosition(success, error);
}
}
document.querySelector('#find-me').addEventListener('click', geoFindMe);
</script>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><?php /**PATH /home/tshego/Work/websites/settlement/resources/views/site/index.blade.php ENDPATH**/ ?> | e8af85908b1a9c12b54e00f234506996bcae2210 | [
"PHP"
]
| 1 | PHP | ShaunSEMO/settlement | 712138070e48b89c656271630e552b16b798b02f | 4e64602a3f9a86722e3ac5d23e16b17f377615e0 |
refs/heads/master | <repo_name>vip30/nest-middlewares<file_sep>/packages/helmet/referrer-policy.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import * as helmet from 'helmet';
@Injectable()
export class HelmetReferrerPolicyMiddleware implements NestMiddleware {
public static configure(opts: helmet.IHelmetReferrerPolicyConfiguration) {
this.options = opts;
}
private static options: helmet.IHelmetReferrerPolicyConfiguration;
public use(req: any, res: any, next: any) {
if (HelmetReferrerPolicyMiddleware.options) {
helmet.referrerPolicy(HelmetReferrerPolicyMiddleware.options)(req, res, next);
} else {
helmet.referrerPolicy()(req, res, next);
}
}
}
| cf20f168922c7776ff9c1146d45c27b7111b3b3b | [
"TypeScript"
]
| 1 | TypeScript | vip30/nest-middlewares | 3cddaf1585a2a645b345da1c393ed4e9c2e9acee | 666da918c51bb89a7ee7ed8c501ecd71e048a98e |
refs/heads/main | <repo_name>Bartl00/ABBNTest<file_sep>/bartlett.py
#This program greets the world and asks the user
#how they are doing.
print("Hello world")
userFeeling = input("Are doing well? Y/N: ")
if userFeeling == "Y":
print("I am glad that you are doing well.")
elif userFeeling == "N":
print("That is too bad. I hope things get better for you soon!")
else:
while userFeeling != "Y" or userFeeling != "N":
userFeeling = input("I am not sure how you feel. Are you doing well? Y/N ")
if userFeeling == "Y":
print("I am glad that you are doing well.")
break
elif userFeeling == "N":
print("That is too bad. I hope things get better for you soon!")
break
<file_sep>/README.md
# ABBNTest
This is a collaboration assignment
| b598370a549c929eed7bc2a7e55f7944bf36d874 | [
"Markdown",
"Python"
]
| 2 | Python | Bartl00/ABBNTest | f78f241763a8a0fe838110173670ee05d652d65b | c6c9d03e3d9659024c759fddd478206cf10cbd19 |
refs/heads/master | <file_sep># game loop
@turn = 1
@previous_move = ""
loop do
action_count = gets.to_i # the number of spells and recipes in play
actions = {}
action_count.times do
# action_id: the unique ID of this spell or recipe
# action_type: in the first league: BREW; later: CAST, OPPONENT_CAST, LEARN, BREW
# delta0: tier-0 ingredient change
# delta1: tier-1 ingredient change
# delta2: tier-2 ingredient change
# delta3: tier-3 ingredient change
# price: the price in rupees if this is a potion
# tome_index: in the first two leagues: always 0; later: the index in the tome if this is a tome spell, equal to the read-ahead tax; For brews, this is the value of the current urgency bonus
# tax_count: in the first two leagues: always 0; later: the amount of taxed tier-0 ingredients you gain from learning this spell; For brews, this is how many times you can still gain an urgency bonus
# castable: in the first league: always 0; later: 1 if this is a castable player spell
# repeatable: for the first two leagues: always 0; later: 1 if this is a repeatable player spell
action_id, action_type, delta0, delta1, delta2, delta3, price, tome_index, tax_count, castable, repeatable = gets.split(" ")
action_id = action_id.to_i
actions[action_id.to_i] =
if action_type == "LEARN"
# [type, (1..4)inv, 5=tome_index, 6=tax_bonus]
[action_type, delta0.to_i, delta1.to_i, delta2.to_i, delta3.to_i, tome_index.to_i, tax_count.to_i]
elsif action_type == "CAST"
# [type, (1..4)inv, 5=castable, 6=repeatable]
[action_type, delta0.to_i, delta1.to_i, delta2.to_i, delta3.to_i, castable.to_i == 1, repeatable.to_i == 1]
else # as in BREW and OPP_CAST
{
type: action_type,
delta0: delta0.to_i,
delta1: delta1.to_i,
delta2: delta2.to_i,
delta3: delta3.to_i,
price: price.to_i,
tome_index: tome_index.to_i,
tax_count: tax_count.to_i,
castable: castable.to_i == 1,
repeatable: repeatable.to_i == 1
}
end
end
inv0, inv1, inv2, inv3, score = gets.split(" ").map(&:to_i)
me = [
inv0, inv1, inv2, inv3, #[0..3]
score, # 4
@turn, # 5
@previous_move # 6
]
inv0, inv1, inv2, inv3, score = gets.split(" ").map(&:to_i)
opp = [
inv0, inv1, inv2, inv3,
score
]
turn = GameTurn.new(
actions: actions,
me: me,
opp: opp
)
# in the first league: BREW <id> | WAIT; later: BREW <id> | CAST <id> [<times>] | LEARN <id> | REST | WAIT
# puts(@previous_move = turn.move)
puts(@previous_move = turn.move_v2)
@turn += 1
end
<file_sep># frozen_string_literal: true
require "codinbot/version"
require "game_simulator"
require "game_header"
require "game_turn"
module Codinbot
class Error < StandardError; end
end
<file_sep># Condinbot
Not a gem! A sandbox where to develop bots for codingame in TDD manner, in separate, testable files.
## Use
1. Place files in `lib/`, and require them in `lib/codinbot.rb` like you normally would.
2. Write specs in `spec/`
3. Configure `build_order.txt` contents.
3. When you're ready to sync to codingame, run `$ ruby codingame_concatenator.rb`
## License
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
<file_sep>RSpec.describe Codinbot do
it "has a version number" do
expect(Codinbot::VERSION).not_to be nil
end
it "does something useful" do
end
describe "Array#add(other)" do
subject(:add) { array.add(other) }
context "when adding positive values" do
let(:array) { [1,2,3,4] }
let(:other) { [2,1,3,1] }
it "returns simple sums of inventory positions" do
is_expected.to eq([3, 3, 6, 5])
end
end
context "when adding negative values" do
let(:array) { [2,4,6,8] }
let(:other) { [-1,-2,-3,-4] }
it "returns an array of values subtracted" do
is_expected.to eq([1,2,3,4])
end
end
end
end
<file_sep># frozen_string_literal: true
# rspec spec/game_turn_spec.rb
RSpec.describe GameTurn do
let(:instance) { described_class.new(**options) }
let(:options) { {actions: actions, me: me, opp: opp} }
let(:actions) { {} }
let(:me) { [] }
let(:opp) { [] }
# v1
describe "#move" do
subject(:move) { instance.move }
context "when initialized with reference state 1" do
let(:actions) do
{
44 => {type: "BREW", delta0: 0, delta1:-2, delta2:0, delta3:0, :price=>8},
42 => {type: "BREW", delta0: -1, delta1:-1, delta2:0, delta3:0, :price=>6},
61 => {type: "BREW", delta0: 0, delta1:0, delta2:0, delta3:-2, :price=>16},
50 => {type: "BREW", delta0: -1, delta1:0, delta2:0, delta3:-1, :price=>10},
54 => {type: "BREW", delta0: 0, delta1:-1, delta2:0, delta3:-1, :price=>12}
}
end
context "when I have enough ingredients for the most lucrative potion" do
let(:me) { [2, 2, 3, 3] }
it "moves to brew the best potion" do
is_expected.to include("BREW 61")
end
end
context "when I dont have enough resources for the most lucrative potion, but do for the second" do
let(:me) { [2, 2, 3, 1] }
it "moves to brew the second best" do
is_expected.to include("BREW 54")
end
end
end
context "when there's spells to learn, but they're all degenerators" do
let(:me) { [3, 2, 0, 0, 3] }
let(:actions) do
{
11 => ["LEARN", 2, 2, -1, 0, 0, 0],
10 => ["LEARN", 4, -1, 0, 0, 1, 0],
44 => {type: "BREW", delta0: 0, delta1:-2, delta2:0, delta3:0, :price=>8},
}
end
before { allow(instance).to receive(:simplest_potion_id).and_return(44) }
it "skips learning, opting to get to brewing instead" do
is_expected.to include("BREW 44")
end
end
context "when there's pure giver spell to learn and it's early in the game" do
let(:me) { [3, 2, 0, 0, 3] }
let(:actions) do
{
11 => ["LEARN", 0, -2, 2, 0, 0, 0],
10 => ["LEARN", 2, 1, 0, 0, 1, 0]
}
end
it "returns the move to learn the pure giver spell" do
is_expected.to include("LEARN 10")
end
end
context "when there's a regular transmuter to learn and it's early in the game" do
let(:me) { [3, 2, 0, 0, 3] }
let(:actions) do
{
11 => ["LEARN", 0, -2, 2, 0, 0, 0],
10 => ["LEARN", 3, -2, 0, 0, 1, 0]
}
end
it "returns the move to learn the first spell" do
is_expected.to include("LEARN 11")
end
end
context "when there's a simple potion and we should work towards it" do
let(:actions) do
{
76 => {type:"BREW", delta0: -1, delta1:-1, delta2:-3, delta3:-1, :price=>18, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
70 => {type:"BREW", delta0: -1, delta1:-1, delta2:0, delta3:-1, :price=>15, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
1 => ["CAST", 2, 0, 0, 0, true, false],
2 => ["CAST", -1, 1, 0, 0, true, false],
3 => ["CAST", 0, -1, 1, 0, true, false],
4 => ["CAST", 0, 0, -1, 1, true, false]
}
end
let(:me) { [3, 0, 0, 0, 51] }
it "returns the move to transmute to green" do
is_expected.to include("CAST 2")
end
end
context "when I've just made a green one and should just rest to get another" do
let(:me) { [2, 1, 1, 1, 51] }
let(:actions) do
{
53 => {type:"BREW", delta0: 0, delta1:0, delta2:-4, delta3:0, :price=>15, :tome_index=>3, :tax_count=>3, :castable=>false, :repeatable=>false},
58 => {type:"BREW", delta0: 0, delta1:-3, delta2:0, delta3:-2, :price=>15, :tome_index=>1, :tax_count=>3, :castable=>false, :repeatable=>false},
70 => {type:"BREW", delta0: -2, delta1:-2, delta2:0, delta3:-2, :price=>15, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
67 => {type:"BREW", delta0: 0, delta1:-2, delta2:-1, delta3:-1, :price=>12, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
77 => {type:"BREW", delta0: -1, delta1:-1, delta2:-1, delta3:-3, :price=>20, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, false, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false]
}
end
it "returns a move to just rest to make another green" do
is_expected.to include("REST")
end
end
context "when we've a bunch of spells" do
let(:me) { [6, 2, 1, 0, 51] } # total of 9
let(:actions) do
{
79 => ["CAST", 4, 1, -1, 0, -1, true, false],
2 => ["CAST", -1, 1, 0, 0, -1, true, false],
3 => ["CAST", 0, 2, -1, 0, -1, true, false],
44 => {type:"BREW", delta0: 0, delta1:-5, delta2:0, delta3:0, :price=>15, :tome_index=>-1, :tax_count=>0, :castable=>false, :repeatable=>false},
}
end
before do
allow(instance).to receive(:simplest_potion_id).and_return(44)
end
it "returns a move that casts a valid spell (as opposed to one that overfills inventory)" do
is_expected.to include("CAST 2")
end
end
end
describe "#move_v2" do
subject(:move) { instance.move_v2 }
before(:all) do
TestProf::StackProf.run
end
context "when the situation is such that the leftmost potion is easy to make" do
let(:actions) do
{
60 => {:type=>"BREW", :delta0=>0, :delta1=>0, :delta2=>-5, :delta3=>0, :price=>18, :tome_index=>3, :tax_count=>4, :castable=>false, :repeatable=>false},
68 => {:type=>"BREW", :delta0=>-1, :delta1=>0, :delta2=>-2, :delta3=>-1, :price=>13, :tome_index=>1, :tax_count=>4, :castable=>false, :repeatable=>false},
48 => {:type=>"BREW", :delta0=>0, :delta1=>-2, :delta2=>-2, :delta3=>0, :price=>10, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
56 => {:type=>"BREW", :delta0=>0, :delta1=>-2, :delta2=>-3, :delta3=>0, :price=>13, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
51 => {:type=>"BREW", :delta0=>-2, :delta1=>0, :delta2=>-3, :delta3=>0, :price=>11, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
# [type, (1..4)inv, 5=tome_index, 6=tax_bonus]
36 => ["LEARN", 0, -3, 3, 0, 0, 0],
31 => ["LEARN", 0, 3, 2, -2, 1, 0],
34 => ["LEARN", -2, 0, -1, 2, 2, 0],
16 => ["LEARN", 1, 0, 1, 0, 3, 0],
1 => ["LEARN", 3, -1, 0, 0, 4, 0],
22 => ["LEARN", 0, 2, -2, 1, 5, 0],
# [type, (1..4)inv, 5=castable, 6=repeatable]
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false]
}
end
let(:me) { [3, 0, 0, 0, 0, 1, ""] }
it "returns the first step towards easy brewin of leftmost potion" do
is_expected.to start_with("LEARN 16")
end
end
context "when going for that leftmost potion, but an excellent (+4) giver spell is in the 6th position" do
let(:actions) do
{
0 => {:type=>"BREW", :delta0=>-1, :delta1=>-1, :delta2=>-3, :delta3=>-1, :price=>21, :tome_index=>3, :tax_count=>4, :castable=>false, :repeatable=>false},
1 => ["LEARN", 3, -1, 0, 0, 0, 1],
18 => ["LEARN", -1, -1, 0, 1, 1, 0],
9 => ["LEARN", 2, -3, 2, 0, 2, 0],
24 => ["LEARN", 0, 3, 0, -1, 3, 0],
23 => ["LEARN", 1, -3, 1, 1, 4, 0],
15 => ["LEARN", 0, 2, 0, 0, 5, 0], # our baby
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
87 => ["CAST", 0, 0, 0, 1, true, false],
90 => {:type=>"OPPONENT_CAST", :delta0=>0, :delta1=>2, :delta2=>-1, :delta3=>0, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>true},
}
end
let(:me) { [2, 0, 0, 1, 0, 5, "REST let's brew 52 via [REST, CAST 87, CAST 78]"] }
let(:opp) { [2, 1, 0, 0, 0, 5, "REST"] }
it "tentatively accumulates aquas to be in a position to learn later" do
is_expected.to start_with("CAST 78") # eq("LEARN 15")
end
end
context "when rushing [0, 0, 0, 1] is the best move" do
let(:actions) do
{
6 => ["LEARN", 2, 1, -2, 1, 0, 0],
36 => ["LEARN", 0, -3, 3, 0, 1, 0],
35 => ["LEARN", 0, 0, -3, 3, 2, 0],
19 => ["LEARN", 0, 2, -1, 0, 3, 0],
14 => ["LEARN", 0, 0, 0, 1, 4, 0], # our baby
1 => ["LEARN", 3, -1, 0, 0, 5, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
85 => {:type=>"OPPONENT_CAST", :delta0=>0, :delta1=>0, :delta2=>-1, :delta3=>1, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
}
end
let(:me) { [3, 0, 0, 0, 0, 1, ""] }
it "returns the first step in the road to snagging spell 14" do
is_expected.to start_with("CAST 78") # followed by rest and another "CAST 78"
end
end
context "when first spells have a lot of tax on them and opponent is not on the offensive (worth below 5)" do
let(:actions) do
{
76 => {:type=>"BREW", :delta0=>-1, :delta1=>-1, :delta2=>-3, :delta3=>-1, :price=>21, :tome_index=>3, :tax_count=>4, :castable=>false, :repeatable=>false},
50 => {:type=>"BREW", :delta0=>-2, :delta1=>0, :delta2=>0, :delta3=>-2, :price=>11, :tome_index=>1, :tax_count=>4, :castable=>false, :repeatable=>false},
62 => {:type=>"BREW", :delta0=>0, :delta1=>-2, :delta2=>0, :delta3=>-3, :price=>16, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
56 => {:type=>"BREW", :delta0=>0, :delta1=>-2, :delta2=>-3, :delta3=>0, :price=>13, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
43 => {:type=>"BREW", :delta0=>-3, :delta1=>-2, :delta2=>0, :delta3=>0, :price=>7, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
39 => ["LEARN", 0, 0, -2, 2, 0, 4],
8 => ["LEARN", 3, -2, 1, 0, 1, 4],
28 => ["LEARN", 4, 1, -1, 0, 2, 0],
10 => ["LEARN", 2, 2, 0, -1, 3, 0],
11 => ["LEARN", -4, 0, 2, 0, 4, 0],
19 => ["LEARN", 0, 2, -1, 0, 5, 0],
82 => ["CAST", 2, 0, 0, 0, true, false],
83 => ["CAST", -1, 1, 0, 0, true, false],
84 => ["CAST", 0, -1, 1, 0, true, false],
85 => ["CAST", 0, 0, -1, 1, true, false],
89 => ["CAST", 0, -3, 0, 2, true, true],
91 => ["CAST", 0, 2, 0, 0, true, false],
93 => ["CAST", 0, -2, 2, 0, true, true],
95 => ["CAST", 1, 1, 0, 0, true, false],
94 => {:type=>"OPPONENT_CAST", :delta0=>1, :delta1=>1, :delta2=>0, :delta3=>0, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
}
end
let(:me) { [3, 0, 1, 0, 0, 8, "LEARN 2"] }
let(:opp) { [0, 0, 0, 0, 0, 8, "LEARN 2"] } # yup, we both learned spell 2
it "prefers learning" do
is_expected.to start_with("LEARN 39")
end
end
context "when it's a real situation where learning a strategic degenerator is the way to go" do
let(:actions) do
{
57 => {:type=>"BREW", :delta0=>0, :delta1=>0, :delta2=>-2, :delta3=>-2, :price=>17, :tome_index=>3, :tax_count=>4, :castable=>false, :repeatable=>false},
50 => {:type=>"BREW", :delta0=>-2, :delta1=>0, :delta2=>0, :delta3=>-2, :price=>11, :tome_index=>1, :tax_count=>4, :castable=>false, :repeatable=>false},
44 => {:type=>"BREW", :delta0=>0, :delta1=>-4, :delta2=>0, :delta3=>0, :price=>8, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
77 => {:type=>"BREW", :delta0=>-1, :delta1=>-1, :delta2=>-1, :delta3=>-3, :price=>20, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
66 => {:type=>"BREW", :delta0=>-2, :delta1=>-1, :delta2=>0, :delta3=>-1, :price=>9, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
1 => ["LEARN", 3, -1, 0, 0, 0, 2],
35 => ["LEARN", 0, 0, -3, 3, 1, 2],
31 => ["LEARN", 0, 3, 2, -2, 2, 2], # ultimate goal
5 => ["LEARN", 2, 3, -2, 0, 3, 0],
30 => ["LEARN", -4, 0, 1, 1, 4, 0],
17 => ["LEARN", -2, 0, 1, 0, 5, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
86 => ["CAST", 0, 0, 0, 1, true, false],
87 => {:type=>"OPPONENT_CAST", :delta0=>0, :delta1=>0, :delta2=>0, :delta3=>1, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
}
end
let(:me) { [0, 0, 0, 0, 0, 2, "LEARN 14"] }
it "returns a move to learn the first spell, which will give tax rebate and allow learning the very situationally awesome 31" do
is_expected.to start_with("LEARN 1")
end
end
context "when it's a no-brainer transmuter learning time" do
let(:actions) do
{
56 => {:type=>"BREW", :delta0=>0, :delta1=>-2, :delta2=>-3, :delta3=>0, :price=>16, :tome_index=>3, :tax_count=>4, :castable=>false, :repeatable=>false},
51 => {:type=>"BREW", :delta0=>-2, :delta1=>0, :delta2=>-3, :delta3=>0, :price=>12, :tome_index=>1, :tax_count=>4, :castable=>false, :repeatable=>false},
77 => {:type=>"BREW", :delta0=>-1, :delta1=>-1, :delta2=>-1, :delta3=>-3, :price=>20, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
71 => {:type=>"BREW", :delta0=>-2, :delta1=>0, :delta2=>-2, :delta3=>-2, :price=>17, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
60 => {:type=>"BREW", :delta0=>0, :delta1=>0, :delta2=>-5, :delta3=>0, :price=>15, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
20 => ["LEARN", 2, -2, 0, 1, 0, 0], # This is it right here, we have green givers, and this is green taker
34 => ["LEARN", -2, 0, -1, 2, 1, 0],
33 => ["LEARN", -5, 0, 3, 0, 2, 0],
29 => ["LEARN", -5, 0, 0, 2, 3, 0],
21 => ["LEARN", -3, 1, 1, 0, 4, 0],
9 => ["LEARN", 2, -3, 2, 0, 5, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
86 => ["CAST", 0, 2, 0, 0, false, false], # pure green giver
88 => ["CAST", 1, 1, 0, 0, true, false], # 1, 1 pure giver
90 => {:type=>"OPPONENT_CAST", :delta0=>0, :delta1=>0, :delta2=>-2, :delta3=>2, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>true},
}
end
let(:me) { [2, 2, 0, 0, 0, 4, "CAST 86"] }
# suffers the problem of becoming too eager on learning transmuters.
# Need to check existing transmuter count not to create a bottleneck
xit "returns the move to learn a transmuter from green, will definitely come in handly" do
is_expected.to start_with("LEARN 20")
end
end
context "when a real good spell is available, a real example" do
let(:actions) do
{
57 => {:type=>"BREW", :delta0=>0, :delta1=>0, :delta2=>-2, :delta3=>-2, :price=>17, :tome_index=>3, :tax_count=>4, :castable=>false, :repeatable=>false},
64 => {:type=>"BREW", :delta0=>0, :delta1=>0, :delta2=>-2, :delta3=>-3, :price=>19, :tome_index=>1, :tax_count=>4, :castable=>false, :repeatable=>false},
49 => {:type=>"BREW", :delta0=>0, :delta1=>-5, :delta2=>0, :delta3=>0, :price=>10, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
73 => {:type=>"BREW", :delta0=>-1, :delta1=>-1, :delta2=>-1, :delta3=>-1, :price=>12, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
59 => {:type=>"BREW", :delta0=>-2, :delta1=>0, :delta2=>0, :delta3=>-3, :price=>14, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
33 => ["LEARN", -5, 0, 3, 0, 0, 0], # the very rare net +4 spell
0 => ["LEARN", -3, 0, 0, 1, 1, 0],
38 => ["LEARN", -2, 2, 0, 0, 2, 0],
25 => ["LEARN", 0, -3, 0, 2, 3, 0],
27 => ["LEARN", 1, 2, -1, 0, 4, 0],
35 => ["LEARN", 0, 0, -3, 3, 5, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
85 => {:type=>"OPPONENT_CAST", :delta0=>0, :delta1=>0, :delta2=>-1, :delta3=>1, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
}
end
let(:me) { [3, 0, 0, 0, 0, 1, ""] }
let(:opp) { [3, 0, 0, 0, 0, 1, ""] }
it "goes for learning the transmuter with huge net advantage" do
is_expected.to start_with("LEARN 33")
end
end
context "when I already have all the ingredients for a good potion" do
let(:actions) do
{
76 => {:type=>"BREW", :delta0=>-1, :delta1=>-1, :delta2=>-3, :delta3=>-1, :price=>19, :tome_index=>1, :tax_count=>3, :castable=>false, :repeatable=>false},
# this is the one we can brew
58 => {:type=>"BREW", :delta0=>0, :delta1=>-3, :delta2=>0, :delta3=>-2, :price=>14, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
72 => {:type=>"BREW", :delta0=>0, :delta1=>-2, :delta2=>-2, :delta3=>-2, :price=>19, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
56 => {:type=>"BREW", :delta0=>0, :delta1=>-2, :delta2=>-3, :delta3=>0, :price=>13, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
46 => {:type=>"BREW", :delta0=>-2, :delta1=>-3, :delta2=>0, :delta3=>0, :price=>8, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
6 => ["LEARN", 2, 1, -2, 1, 0, 0],
26 => ["LEARN", 1, 1, 1, -1, 1, 0],
20 => ["LEARN", 2, -2, 0, 1, 2, 0],
21 => ["LEARN", -3, 1, 1, 0, 3, 0],
25 => ["LEARN", 0, -3, 0, 2, 4, 0],
1 => ["LEARN", 3, -1, 0, 0, 5, 0],
82 => ["CAST", 2, 0, 0, 0, true, false],
83 => ["CAST", -1, 1, 0, 0, false, false],
84 => ["CAST", 0, -1, 1, 0, true, false],
85 => ["CAST", 0, 0, -1, 1, true, false],
81 => {:type=>"OPPONENT_CAST", :delta0=>0, :delta1=>0, :delta2=>-1, :delta3=>1, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
}
end
let(:me) { [1, 3, 0, 2, 56, 67, "CAST 83 let's brew 46 via [CAST 83, CAST 82]"] }
it "returns a move to brew it, not got for the cheapest potion" do
is_expected.to start_with("BREW 58")
end
end
context "when it's a real situation that times out" do
let(:actions) do
{
77 => {:type=>"BREW", :delta0=>-1, :delta1=>-1, :delta2=>-1, :delta3=>-3, :price=>21, :tome_index=>1, :tax_count=>4, :castable=>false, :repeatable=>false},
74 => {:type=>"BREW", :delta0=>-3, :delta1=>-1, :delta2=>-1, :delta3=>-1, :price=>14, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
68 => {:type=>"BREW", :delta0=>-1, :delta1=>0, :delta2=>-2, :delta3=>-1, :price=>12, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
76 => {:type=>"BREW", :delta0=>-1, :delta1=>-1, :delta2=>-3, :delta3=>-1, :price=>18, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
65 => {:type=>"BREW", :delta0=>0, :delta1=>0, :delta2=>0, :delta3=>-5, :price=>20, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
20 => ["LEARN", 2, -2, 0, 1, 0, 0],
34 => ["LEARN", -2, 0, -1, 2, 1, 0],
33 => ["LEARN", -5, 0, 3, 0, 2, 0],
26 => ["LEARN", 1, 1, 1, -1, 3, 0],
7 => ["LEARN", 3, 0, 1, -1, 4, 0],
37 => ["LEARN", -3, 3, 0, 0, 5, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
87 => ["CAST", 0, 0, 0, 1, false, false],
92 => ["CAST", 0, 2, 0, 0, false, false],
95 => ["CAST", 0, 3, 0, -1, false, true],
97 => ["CAST", 1, -3, 1, 1, false, true],
98 => ["CAST", -5, 0, 0, 2, true, true],
99 => {:type=>"OPPONENT_CAST", :delta0=>-5, :delta1=>0, :delta2=>0, :delta3=>2, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>false, :repeatable=>true},
}
end
let(:me) { [0, 0, 0, 0, 44, 23, "BREW 75"] }
let(:opp) { [0, 0, 0, 0, 44, 23, "BREW 75"] }
it "runs in under 50ms" do
runtime = Benchmark.realtime do
is_expected.to match(%r'\A((REST)|(CAST 78))')
end * 1000
expect(runtime).to be < 50 # as below 50ms
# "let's brew 74 via [REST, CAST 87, CAST 95, CAST 78, CAST 97, CAST 92]"
# or [REST, CAST 87, CAST 78, CAST 95, CAST 97, CAST 92]"
end
end
end
describe "array vs hash dup" do
before(:all) do
TestProf::StackProf.run
end
it "compares time it takes to dup array vs a hash 40k times" do
hash = {type:"MEHH", delta0: 4, delta1:1, delta2:-1, delta3:0, price: 0, :tt=>-1, :tx=>-1, :cc=>true, :repeatable=>false}
array = ["CAST", 4, 1, -1, 0, 0, -1, -1, true, false]
array_time = Benchmark.realtime do
40_000.times do
array.dup
end
end
puts("Array time: #{ array_time }")
hash_time = Benchmark.realtime do
40_000.times do
hash.dup
end
end
puts("Hash time: #{ hash_time }")
expect(1).to eq(1)
end
end
#== Privates ==
describe "#cost_in_moves(potion)" do
subject(:cost_in_moves) { instance.send(:cost_in_moves, potion) }
context "when potion requires one of each resource" do
let(:potion) { {delta0: -1, delta1:-1, delta2:-1, delta3:-1, price: 9} }
it { is_expected.to eq(16) }
end
context "when potion requires two green and three orange" do
let(:potion) { {delta0: 0, delta1:-2, delta2:-3, delta3:0} }
it { is_expected.to eq(21) }
end
end
describe "#next_step_towards(target_inventory)" do
subject(:next_step_towards) do
instance.send(:next_step_towards, target_inventory)
end
let(:actions) do
{
1 => ["CAST", 2, 0, 0, 0, true, false],
2 => ["CAST", -1, 1, 0, 0, true, false],
3 => ["CAST", 0, -1, 1, 0, true, false],
4 => ["CAST", 0, 0, -1, 1, true, false]
}
end
let(:me) { [] }
context "when lacking a yellow" do
let(:target_inventory) { [0, 0, 0, 1] }
context "when spell is available and orange is available" do
let(:me) { [0, 0, 1, 0] }
it "returns the move to cast orange->yellow spell" do
is_expected.to include("CAST 4")
end
end
context "when I know several spells to transmute to yellow" do
let(:actions) do
s = super()
s[4][5] = false
s[5] = ["CAST", 0, -1, 0, 1, true, false]
s
end
let(:me) { [0, 1, 0, 0] }
it "returns the move to cast the available spell" do
is_expected.to include("CAST 5")
end
end
context "when yellow can not be created due to orange missing but orange can be created" do
let(:me) { [0, 1, 0, 0] }
let(:actions) { super().tap{ |a| a[4][5] = false } }
it "returns the move to cast green->orange spell" do
is_expected.to include("CAST 3")
end
end
context "when yellow can not be created due to orange missing and green missing, but green can be made" do
let(:me) { [1, 0, 0, 0] }
it "returns the move to cast blue->green spell" do
is_expected.to include("CAST 2")
end
end
context "when yellow can not be created due to everything missing" do
let(:me) { [0, 0, 0, 0] }
it "returns the move to cast blue++" do
is_expected.to include("CAST 1")
end
end
context "when nothing can be cast" do
let(:actions) { super().tap{ |s| s[1][5] = false } }
let(:me) { [0, 0, 0, 0] }
it "returns the move to REST" do
is_expected.to include("REST")
end
end
end
end
describe "#i_can_cast?(spell)" do
subject(:i_can_cast?) { instance.send(:i_can_cast?, spell) }
let(:spell) { ["CAST", -1, 1, 0, 0, true] }
context "when the spell would overfill inventory" do
let(:spell) { ["CAST", 1, 0, 0, 0, true] }
let(:me) { [4, 3, 2, 1] }
it { is_expected.to be(false) }
end
context "when the spell transmutes and would overfill inventory" do
let(:spell) { ["CAST", 2, 2, -1, 0, true] }
let(:me) { [1, 1, 1, 5] }
it { is_expected.to be(false) }
end
context "when the spell requires no ingredients" do
let(:spell) { ["CAST", 2, 0, 0, 0, true] }
let(:me) { [0, 0, 0, 0] }
it { is_expected.to be(true) }
end
context "when I have ingredients to cast" do
let(:me) { [1, 0, 0, 0] }
it { is_expected.to be(true) }
end
context "when I have complex ingredients to cast" do
let(:spell) { ["CAST", -1, -2, -3, 4, true, true] }
let(:me) { [2, 3, 4, 1] }
it { is_expected.to be(true) }
end
context "when I don't have ingredients to cast" do
let(:me) { [0, 1, 1, 1] }
it { is_expected.to be(false) }
end
end
describe "#inventory_delta(now, target)" do
subject(:inventory_delta) { instance.send(:inventory_delta, now, target) }
let(:now) { [0, 0, 0, 0] }
context "when im missing everything" do
let(:target) { [1, 1, 1, 1] }
it "returns the missing counts" do
is_expected.to eq([1, 1, 1, 1])
end
end
context "when I have everything" do
let(:now) { [1, 1, 1, 1] }
let(:target) { [1, 1, 1, 1] }
it "returns the missing counts, which are none" do
is_expected.to eq([0, 0, 0, 0])
end
end
context "when I have something, but missing others" do
let(:now) { [1, 0, 3, 1] }
let(:target) { [1, 1, 2, 2] }
it "returns the missing counts" do
is_expected.to eq([0, 1, 0, 1])
end
end
end
describe "#degeneration_spell?(spell)" do
subject(:degeneration_spell?) { instance.send(:degeneration_spell?, spell) }
context "when the spell is a definite degenerator" do
let(:spell) { {delta0: 3, delta1:-1, delta2:0, delta3:0, :castable=>true} }
it { is_expected.to be(true) }
end
context "when the spell is a definite transmuter" do
let(:spell) { {delta0: 0, delta1:-2, delta2:2, delta3:0, :castable=>true} }
it { is_expected.to be(false) }
end
context "when the spell is a mixture of degen and transmute" do
let(:spell) { {delta0: 2, delta1:-2, delta2:1, delta3:0, :castable=>true} }
it { is_expected.to be(false) }
end
context "when the spell is a complex transmuter" do
let(:spell) { {delta0: -1, delta1:-2, delta2:-3, delta3:4, :castable=>true} }
it { is_expected.to be(false) }
end
end
describe "#pure_giver_spell?(spell)" do
subject(:pure_giver_spell?) { instance.send(:pure_giver_spell?, spell) }
context "when the spell is indeed a pure giver" do
let(:spell) { {delta0: 2, delta1:1, delta2:0, delta3:0, :castable=>true} }
it { is_expected.to be(true) }
end
context "when the spell requires even one ingredient, even if transmuting up" do
let(:spell) { {delta0: -1, delta1:2, delta2:2, delta3:2, :castable=>true} }
it { is_expected.to be(false) }
end
end
end
<file_sep>source "https://rubygems.org"
# Specify your gem's dependencies in codinbot.gemspec
gemspec
gem "rake", "~> 12.0"
gem "rspec", "~> 3.8"
gem "stackprof", ">= 0.2.9", require: false
gem "test-prof", require: false
<file_sep>require "set"
require "benchmark"
STDOUT.sync = true # DO NOT REMOVE
INVENTORY_SIZE = 10
def debug(message, prefix: "=> ")
STDERR.puts("#{ prefix }#{ message }")
end
# takes in a spell or a potion and returns inventory-compatible array
def deltas(action)
if action.is_a?(Hash)
[action[:delta0], action[:delta1], action[:delta2], action[:delta3]]
else
action[1..4]
end
end
# @return [String]
def action_type(action)
if action.is_a?(Hash)
action[:type]
else
action[0]
end
end
class Array
# monkeypatches Array to allow adding inventories
def add(other)
mem = []
size.times do |i|
mem[i] = self[i] + other[i]
end
mem
end
end
<file_sep>require "set"
require "benchmark"
STDOUT.sync = true # DO NOT REMOVE
INVENTORY_SIZE = 10
def debug(message, prefix: "=> ")
STDERR.puts("#{ prefix }#{ message }")
end
# takes in a spell or a potion and returns inventory-compatible array
def deltas(action)
if action.is_a?(Hash)
[action[:delta0], action[:delta1], action[:delta2], action[:delta3]]
else
action[1..4]
end
end
# @return [String]
def action_type(action)
if action.is_a?(Hash)
action[:type]
else
action[0]
end
end
class Array
# monkeypatches Array to allow adding inventories
def add(other)
mem = []
size.times do |i|
mem[i] = self[i] + other[i]
end
mem
end
end
class GameSimulator
# This class provides methods to advance game state into the future to a certain degree
# opponent moves can naturally not be simulated, and impossible to know what new spells
# and potions will appear later.
class ::SimulatorError < RuntimeError; end
# 78, 82 are default 1st spell ids, the [2, 0, 0, 0] spells
PURE_GIVER_IDS = [78, 82, 2, 3, 4, 12, 13, 14, 15, 16].to_set.freeze
GOOD_SPELL_IDS = [18, 17, 38, 39, 40, 30, 34].to_set.freeze
TACTICAL_DEGENERATORS = [31, 32, 41, 7, 5, 19, 26, 27].to_set.freeze
INSTALEARN_NET_FOUR_SPELLS = [12, 13, 14, 15, 16, 33].to_set.freeze
LEARNABLE_SPELLS = {
# id => [deltas, can be multicast, hard_skip, value_per_turn]
2 => [1, 1, 0, 0, false, false, 3], # pure giver
3 => [0, 0, 1, 0, false, false, 3], # pure giver
4 => [3, 0, 0, 0, false, false, 3], # pure giver
12 => [2, 1, 0, 0, false, false, 4], # pure giver
13 => [4, 0, 0, 0, false, false, 4], # pure giver
14 => [0, 0, 0, 1, false, false, 4], # pure giver
15 => [0, 2, 0, 0, false, false, 4], # pure giver
16 => [1, 0, 1, 0, false, false, 4], # pure giver
# excellent transmuters
18 => [-1, -1, 0, 1, true, false, 1], # IMBA, huge multicast potential, special in that it takes two givers
17 => [-2, 0, 1, 0, true, false, 1], # GREAT!, better version of 11
38 => [-2, 2, 0, 0, true, false, 2], # OK
39 => [0, 0, -2, 2, true, false, 2], # OK
40 => [0, -2, 2, 0, true, false, 2], # OK
30 => [-4, 0, 1, 1, true, false, 3], # OK
34 => [-2, 0, -1, 2, true, false, 3], # OK, takes two givers
33 => [-5, 0, 3, 0, true, false, 4], # OK, one of the rare spells with net+ of 4
# Tactical degens, ony from orange and yello for now
31 => [0, 3, 2, -2, true, false, 4], # degen. excellent if you have [0, 0, 0, 1]
32 => [1, 1, 3, -2, true, false, 4], # degen
41 => [0, 0, 2, -1, true, false, 2], # degen, good chance to multicast
7 => [3, 0, 1, -1, true, false, 2], # degen
26 => [1, 1, 1, -1, true, false, 2], # degen, excellent multicast
5 => [2, 3, -2, 0, true, false, 2], # degen
19 => [0, 2, -1, 0, true, false, 1], # degen
27 => [1, 2, -1, 0, true, false, 2], # degen, good multicast
0 => [-3, 0, 0, 1, true, false, 1], # so-so-to-OK
21 => [-3, 1, 1, 0, true, false, 2], # so-so, lossy
37 => [-3, 3, 0, 0, true, false, 3], # so-so-to-OK
6 => [2, 1, -2, 1, true, false, 2], # so-so, lossy
10 => [2, 2, 0, -1, true, false, 2], # degen
24 => [0, 3, 0, -1, true, false, 2], # degen
22 => [0, 2, -2, 1, true, false, 2], # so-so, twist
28 => [4, 1, -1, 0, true, false, 3], # degen, low chance to multicast :(
35 => [0, 0, -3, 3, true, false, 3], # so-so, situational, when are you gonna have 3 oranges?
8 => [3, -2, 1, 0, true, false, 2], # so-so, lossy
9 => [2, -3, 2, 0, true, false, 2], # so-so, lossy
20 => [2, -2, 0, 1, true, false, 2], # so-so, lossy
23 => [1, -3, 1, 1, true, false, 2], # so-so, twist
25 => [0, -3, 0, 2, true, false, 2], # so-so
36 => [0, -3, 3, 0, true, false, 3], # so-so
11 => [-4, 0, 2, 0, true, false, 2], # so-so, bad version of 17
29 => [-5, 0, 0, 2, true, false, 3], # mehh, situational
1 => [3, -1, 0, 0, true, true, 1], # degen, extremely situational
}.freeze
LEARNED_SPELL_DATA = {
2 => ["CAST", 1, 1, 0, 0, true, false],
3 => ["CAST", 0, 0, 1, 0, true, false],
4 => ["CAST", 3, 0, 0, 0, true, false],
12 => ["CAST", 2, 1, 0, 0, true, false],
13 => ["CAST", 4, 0, 0, 0, true, false],
14 => ["CAST", 0, 0, 0, 1, true, false],
15 => ["CAST", 0, 2, 0, 0, true, false],
16 => ["CAST", 1, 0, 1, 0, true, false],
18 => ["CAST", -1, -1, 0, 1, true, true],
17 => ["CAST", -2, 0, 1, 0, true, true],
38 => ["CAST", -2, 2, 0, 0, true, true],
39 => ["CAST", 0, 0, -2, 2, true, true],
40 => ["CAST", 0, -2, 2, 0, true, true],
30 => ["CAST", -4, 0, 1, 1, true, true],
34 => ["CAST", -2, 0, -1, 2, true, true],
0 => ["CAST", -3, 0, 0, 1, true, true],
1 => ["CAST", 3, -1, 0, 0, true, true],
5 => ["CAST", 2, 3, -2, 0, true, true],
6 => ["CAST", 2, 1, -2, 1, true, true],
7 => ["CAST", 3, 0, 1, -1, true, true],
8 => ["CAST", 3, -2, 1, 0, true, true],
9 => ["CAST", 2, -3, 2, 0, true, true],
10 => ["CAST", 2, 2, 0, -1, true, true],
11 => ["CAST", -4, 0, 2, 0, true, true],
19 => ["CAST", 0, 2, -1, 0, true, true],
20 => ["CAST", 2, -2, 0, 1, true, true],
21 => ["CAST", -3, 1, 1, 0, true, true],
22 => ["CAST", 0, 2, -2, 1, true, true],
23 => ["CAST", 1, -3, 1, 1, true, true],
24 => ["CAST", 1, 3, 0, -1, true, true],
25 => ["CAST", 1, -3, 0, 2, true, true],
26 => ["CAST", 1, 1, 1, -1, true, true],
27 => ["CAST", 1, 2, -1, 0, true, true],
28 => ["CAST", 4, 1, -1, 0, true, true],
31 => ["CAST", 0, 3, 2, -2, true, true],
32 => ["CAST", 1, 1, 3, -2, true, true],
35 => ["CAST", 0, 0, -3, 3, true, true],
36 => ["CAST", 0, -3, 3, 0, true, true],
37 => ["CAST", -3, 3, 0, 0, true, true],
33 => ["CAST", -5, 0, 3, 0, true, true],
29 => ["CAST", -5, 0, 0, 2, true, true],
41 => ["CAST", 0, 0, 2, -1, true, true]
}.freeze
POTIONS = {
42 => [[2, 2, 0, 0], 6],
43 => [[3, 2, 0, 0], 7],
44 => [[0, 4, 0, 0], 8],
45 => [[2, 0, 2, 0], 8],
46 => [[2, 3, 0, 0], 8],
47 => [[3, 0, 2, 0], 9],
48 => [[0, 2, 2, 0], 10],
49 => [[0, 5, 0, 0], 10],
50 => [[2, 0, 0, 2], 10],
51 => [[2, 0, 3, 0], 11],
52 => [[3, 0, 0, 2], 11],
53 => [[0, 0, 4, 0], 12],
54 => [[0, 2, 0, 2], 12],
55 => [[0, 3, 2, 0], 12],
56 => [[0, 2, 3, 0], 13],
57 => [[0, 0, 2, 2], 14],
58 => [[0, 3, 0, 2], 14],
59 => [[2, 0, 0, 3], 14],
60 => [[0, 0, 5, 0], 15],
61 => [[0, 0, 0, 4], 16],
62 => [[0, 2, 0, 3], 16],
63 => [[0, 0, 3, 2], 17],
64 => [[0, 0, 2, 3], 18],
65 => [[0, 0, 0, 5], 20],
66 => [[2, 1, 0, 1], 9],
67 => [[0, 2, 1, 1], 12],
68 => [[1, 0, 2, 1], 12],
69 => [[2, 2, 2, 0], 13],
70 => [[2, 2, 0, 2], 15],
71 => [[2, 0, 2, 2], 17],
72 => [[0, 2, 2, 2], 19],
73 => [[1, 1, 1, 1], 12],
74 => [[3, 1, 1, 1], 14],
75 => [[1, 3, 1, 1], 16],
76 => [[1, 1, 3, 1], 18],
77 => [[1, 1, 1, 3], 20]
}.freeze
SPELL_TYPES = ["CAST", "OPPONENT_CAST"].freeze
def self.the_instance
@the_instance ||= new
end
def initialize; end
# Returns the init parameters for the GameTurn that would follow after a certain move
# Caches the outcomes, since same state and same move will always result in the same outcome
#
# @position [Hash] #
# @return [Hash]
# @return [String] # err message if there's err
def result(position:, move:)
portions = move.split(" ")
verb = portions.first #=> "LEARN", "REST", "CAST"
case verb
when "REST"
if position.dig(:me, 6).to_s.start_with?("REST")
return "do not rest twice in a row!"
end
p = dup_of(position)
p[:actions].transform_values! do |v|
if action_type(v) == "CAST"
v[5] = true
v
else
v
end
end
p[:me][5] += 1
p[:me][6] = move
p
when "LEARN"
id = portions[1].to_i
learned_spell = position[:actions][id]
learn_index = learned_spell[5]
if learn_index > position[:me][0]
return "insufficient aqua for learning tax!"
end
# needed to know what will be the added spell's id
max_cast_id =
position[:actions].max_by do |id, action|
if SPELL_TYPES.include?(action_type(action))
id
else
-1
end
end.first
# 1. learning
# removes learned spell from list
# adds a spell with correct id to own spells
p = dup_of(position)
p[:actions].reject!{ |k, v| k == id }
p[:actions].transform_values! do |v|
if action_type(v) == "LEARN"
if v[5] > learn_index
v[5] -= 1
end
if v[5] < learn_index
v[6] += 1
end
v
else
v
end
end
p[:actions][max_cast_id.next] = LEARNED_SPELL_DATA[id]
p[:me][5] += 1
p[:me][6] = move
p[:me][0] -= learn_index
p[:me][0] += learned_spell[6] if learned_spell[6].positive?
p
when "CAST"
id = portions[1].to_i
cast_spell = position[:actions][id]
return "spell exhausted!" unless cast_spell[5]
cast_times =
if portions.size > 2
portions[2].to_i
else
1
end
if cast_times > 1 && !cast_spell[6]
return "spell can't multicast!"
end
operation =
if cast_times == 1
deltas(cast_spell)
else
deltas(cast_spell).map{ |v| v * cast_times}
end
casting_check = can_cast?(operation: operation, from: position[:me][0..3])
if !casting_check[:can]
if casting_check[:detail] == :insufficient_ingredients
return "insufficient ingredients for casting!" if cast_times == 1
return "insufficient ingredients for multicasting!"
else
return "casting overfills inventory!"
end
end
p = dup_of(position)
cast_times.times do
p[:me][0..3] = p[:me][0..3].add(deltas(cast_spell))
end
p[:actions][id][5] = false
# 2. casting
# changes my inv accordingly
# changes spell castability accordingly
p[:me][5] += 1
p[:me][6] = move
p
else
{error: "verb '#{ verb }' not supported"}
end
end
def dup_of(position)
# 2.22s
dupped_actions = position[:actions].dup
dupped_actions.transform_values!(&:dup)
{
actions: dupped_actions,
me: position[:me].dup
}
# # 2.38s
# {
# # actions: position[:actions].map{ |k, v| [k, v.dup]}.to_h,
# # actions: position[:actions].each_with_object({}){ |(k, v), mem| mem[k] = v.dup },
# me: position[:me].dup
# }
end
MY_MOVES = ["CAST", "LEARN"].to_set.freeze
DISTANCE_CUTOFF_DELTA = 6
MAXIMUM_DEPTH = 6
# This is the brute-forcing component.
# Uses heuristics to try most promising paths first
# @target [Array] # target inventory to solve for
# @start [Hash] # the starting position, actions and me expected
#
# @return [Array<String>]
def moves_towards(target:, start:, path: [], max_depth: MAXIMUM_DEPTH, depth: 0)
prime_candidate = nil
moves_to_return = nil
initial_distance_from_target = distance_from_target(
target: target, inv: start[:me][0..3]
)
return [] if initial_distance_from_target[:distance].zero?
# debug("Initial distance is #{ initial_distance_from_target }")
# This cleans position passed on in hopes of saving on dup time, works well
start[:actions] = start[:actions].select do |_k, v|
MY_MOVES.include?(action_type(v))
end.to_h
max_allowed_learning_moves = max_depth / 2 # in case of odd max debt, learn less
positions = {path => start}
ms_spent = 0.0
(1..max_depth).to_a.each do |generation|
break if moves_to_return
if ms_spent > 45
debug("Quick-returning #{ prime_candidate[0] } due to imminent timeout!")
return prime_candidate[0]
end
past_halfway = generation >= (max_depth / 2).next
generation_runtime = Benchmark.realtime do
debug("Starting move and outcome crunch for generation #{ generation }") if past_halfway
# debug("There are #{ positions.keys.size } positions to check moves for")
final_iteration = generation == max_depth
penultimate_iteration = generation == max_depth - 1
data = []
ms_spent_in_this_gen = ms_spent
positions.each_pair do |path, position|
position_processing_time = Benchmark.realtime do
already_studied_max_times =
past_halfway &&
path.count { |v| v.start_with?("LEARN") } >= max_allowed_learning_moves
# HH This prevents resting after just learning a spell
just_learned = position[:me][6].to_s.start_with?("LEARN")
moves = moves_from(
position: position,
skip_resting: final_iteration || just_learned,
skip_learning: final_iteration || already_studied_max_times
)
# debug("There are #{ moves.size } moves that can be made after #{ path }")
#=> ["REST", "CAST 79"]
moves.each do |move|
# 2. loop over OK moves, get results
outcome =
begin
result(position: positions[path], move: move)
rescue => e
raise("Path #{ path << move } leads to err: '#{ e.message }' in #{ e.backtrace.first }")
end
# outcome was an expected invalid move, skipping the outcome
next if outcome.is_a?(String)
# 3. evaluate the outcome
distance_from_target = distance_from_target(
target: target, inv: outcome[:me][0..3]
)
data << [
[*path, move],
{
outcome: outcome,
distance_from_target: distance_from_target
}
]
end
end * 1000
ms_spent_in_this_gen += position_processing_time
if ms_spent_in_this_gen > 45
debug("Doing an emergency break out of position processing due to time running out!")
break
end
end
# debug("There turned out to be #{ moves_to_try.size } moves to check") if past_halfway
data.sort_by! do |(_move, path), specifics|
[
specifics[:distance_from_target][:distance],
-specifics[:distance_from_target][:bonus]
]
end
#=> [[move, data], ["CATS 78", {outcome: {actions: {...}}}]]
prime_candidate = data.first
prime_specifics = prime_candidate[1]
# check best move, if with it we're there, done!
return_prime_candidate =
if prime_specifics[:distance_from_target][:distance] == 0
:target_reached
elsif final_iteration
:max_depth_reached
else
false
end
if return_prime_candidate
debug("Returning prime candidate because #{ return_prime_candidate }")
moves_to_return = prime_candidate[0]
else
# no move got us there, lets go deeper.
# here's we can inject heuristics of which results to keep and drop for next gen
# 1. drop outcomes that are too far behind the best variant. Since some spells give 4 in one move,
# probably safe to use 8+
# 1. dropping hopeless variations
lowest_distance = prime_specifics[:distance_from_target][:distance]
no_longer_tolerable_distance =
# the further in we are, the less forgiving of bad variations we are
if penultimate_iteration
lowest_distance + DISTANCE_CUTOFF_DELTA - 1
else
lowest_distance + DISTANCE_CUTOFF_DELTA
end
cutoff_index = nil
data.each.with_index do |(new_path, specifics), i|
if specifics[:distance_from_target][:distance] < no_longer_tolerable_distance
next
end
# detects no progress towards target past the halfway mark, pure idling here.
if past_halfway
if specifics[:distance_from_target][:distance] <= initial_distance_from_target[:distance]
if specifics[:distance_from_target][:bonus] <= initial_distance_from_target[:bonus]
cutoff_index = i
break
end
end
end
cutoff_index = i
break
end
if cutoff_index
# debug("Cutoff at index #{ cutoff_index } from #{ data.size }")
debug("Cutoff at index #{ cutoff_index } from OMITTED")
data = data[0..(cutoff_index-1)]
else
debug(
"Nothing to cut off, "\
"closest variant has #{ prime_specifics[:distance_from_target] }, "\
"and furthest has #{ data.last[1][:distance_from_target] }"
) if past_halfway
end
positions = {}
data.each do |variation_path, specifics|
positions[variation_path] = specifics[:outcome]
end
end
end * 1000
ms_spent += generation_runtime
debug("Gen #{ generation } ran for #{ generation_runtime.round(1) }ms, totalling #{ ms_spent.round(1) }ms") if past_halfway
end
moves_to_return
end
# This is the evaluator method.
# every ingredient that is missing from target is taken to be a distance of [1,2,3,4] respectively
# ingredients that are more do not reduce distance, but are counted as a bonus
#
# @return [Hash]
def distance_from_target(target:, inv:)
@distance_cache ||= {}
key = [target, inv]
if @distance_cache.key?(key)
@distance_cache[key]
else
sum = target.add(inv.map{|v| -v})
distance = sum.map.with_index{ |v, i| next unless v.positive?; v*i.next }.compact.sum
bonus = sum.map.with_index{ |v, i| next unless v.negative?; -v*i.next }.compact.sum
@distance_cache[key] = {distance: distance, bonus: bonus}
end
# sum = target.add(inv.map{|v| -v})
# distance = sum.map.with_index{ |v, i| next unless v.positive?; v*i.next }.compact.sum
# bonus = sum.map.with_index{ |v, i| next unless v.negative?; -v*i.next }.compact.sum
# {distance: distance, bonus: bonus}
end
# returns a net gain of 0 if can't afford learning tax anyway
def net_aqua_gains_from_learning(aquas_on_hand:, tomes:)
tomes.map do |id, tome|
gain =
if aquas_on_hand >= tome[5]
tome[6] - tome[5]
else
0
end
[id, gain]
end
end
# Does not care about legality much, since simulator will check when deciding outcome.
# @return [Array<String>]
def moves_from(position:, skip_resting: false, skip_learning: false)
moves = []
all_spells_rested = true
givers_i_know = nil
spells =
position[:actions].select do |id, action|
action_type(action) == "CAST"
end
tomes =
position[:actions].select do |id, action|
action_type(action) == "LEARN"
end
aquas_on_hand = position[:me][0]
# can also give 0 and 1 aqua, beware
best_aqua_giver_from_learning = net_aqua_gains_from_learning(
aquas_on_hand: aquas_on_hand, tomes: tomes
).max_by{ |_id, gain| gain }
position[:actions].each do |id, action|
type = action_type(action)
if type == "LEARN" && !skip_learning
try_learning =
if PURE_GIVER_IDS.include?(id)
true
elsif spells.size >= 8
false
# elsif # TODO, consider not learning [-5] spells if an advanced aqua giver is not known
else
givers_needed = action[1..4].map{ |v| v.negative? } #=> [false, false, true, false]
givers_i_know ||= spells.select do |id, action|
!action[1..4].find{ |v| v.negative? }
end.each_with_object([false, false, false, false]) do |(id, giver), mem|
mem[0] ||= giver[1].positive?
mem[1] ||= giver[2].positive?
mem[2] ||= giver[3].positive?
mem[3] ||= giver[4].positive?
end
even_one_required_but_no_giver =
givers_needed.find.with_index do |req, i|
req && !givers_i_know[i]
end
!even_one_required_but_no_giver
end
moves << "LEARN #{ id }" if try_learning
elsif type == "CAST"
unless action[5] # oops, exhausted
all_spells_rested = false
next
end
times = possible_cast_times(spell: action, inv: position[:me][0..3])
next if times == 0
# givers can ever only be cast once
if times == 1
only_gives_aquas =
action[1].positive? && action[2].zero? && action[3].zero? && action[4].zero?
# preferring to get aquas by learning
if only_gives_aquas && best_aqua_giver_from_learning && best_aqua_giver_from_learning[1] >= action[1]
moves << "LEARN #{ best_aqua_giver_from_learning[0] }"
next
end
end
times.times do |i|
moves <<
if i == 0
"CAST #{ id }"
else
"CAST #{ id } #{ i.next }"
end
end
end
end
if skip_resting || position[:me][6].to_s.start_with?("REST") || all_spells_rested
else
moves << "REST"
end
moves.uniq
end
# Returns ways can this spell can be cast in. 0, 1 or n(multicast) variants possible.
# @return [Integer] # number of times the spell can be cast from this inventory
def possible_cast_times(spell:, inv:)
# @cast_time_cache ||= {}
# key = [spell, inv]
# if @cast_time_cache.key?(key)
# @cast_time_cache[key]
# else
# return @cast_time_cache[key] = 0 unless spell[5]
# deltas = deltas(spell)
# can_cast_once = can_cast?(operation: deltas, from: inv)
# return @cast_time_cache[key] = 0 unless can_cast_once[:can]
# # here we know that can be cast at least once
# return @cast_time_cache[key] = 1 unless spell[6]
# # here we know the spell can be repeated
# (2..5).to_a.each do |i|
# next if can_cast?(operation: deltas.map{ |v| v * i}, from: inv)[:can]
# return @cast_time_cache[key] = i-1
# end
# return @cast_time_cache[key] = 5
# end
return 0 unless spell[5]
deltas = deltas(spell)
can_cast_once = can_cast?(operation: deltas, from: inv)
return 0 unless can_cast_once[:can]
# here we know that can be cast at least once
return 1 unless spell[6]
# here we know the spell can be repeated
(2..5).to_a.each do |i|
next if can_cast?(operation: deltas.map { |v| v * i }, from: inv)[:can]
return i-1
end
5
end
NO_INGREDIENTS = {can: false, detail: :insufficient_ingredients}.freeze
INVENTORY_OVERFLOW = {can: false, detail: :overflow}.freeze
CANN = {can: true}.freeze
# Takes into account the two constraints
# - ingredients must suffice
# - inventory of 10 may not be exceeded
#
# @operation [Array] # deltas
# @return [Hash] {can: true/false, detail: :insufficient_ingredients/:overflow}
def can_cast?(operation:, from:)
# @cast_cache ||= {}
# key = [operation, from]
# if @cast_cache.key?(key)
# @cast_cache[key]
# else
# result = from.add(operation)
# return @cast_cache[key] = {can: false, detail: :insufficient_ingredients} if result.find{ |v| v.negative? }
# return @cast_cache[key] = {can: false, detail: :overflow} if result.sum > INVENTORY_SIZE
# @cast_cache[key] = {can: true}
# end
result = from.add(operation)
return NO_INGREDIENTS if result.find{ |v| v.negative? }
return INVENTORY_OVERFLOW if result.sum > INVENTORY_SIZE
CANN
end
end
class GameTurn
# Given wood 2 spells, ingredient relative costs
COSTS = {
delta0: 1,
delta1: 3,
delta2: 5,
delta3: 7
}.freeze
attr_reader :actions, :me, :opp
def initialize(actions:, me:, opp:)
actions.each do |k, v|
debug("#{ k } => #{ v },", prefix: "")
end
@actions = actions
@me = me
@opp = opp
debug("me: #{ me }")
# debug("opp: #{ opp }")
end
# V1, a bunch of else-ifs
# The only public API, returns the preferable move string
def move
brewable_potion = potions.find { |id, potion| i_can_brew?(potion) }
unless brewable_potion.nil?
return "BREW #{ brewable_potion[0] } Brewin' #{ brewable_potion[0] }"
end
# nothing brewable, let's learn some spells!
if spell_to_learn_id
return "LEARN #{ spell_to_learn_id } Studyin'"
end
# nothing brewable, let's spell towards the simplest potion
if simplest_potion_id
target_inventory = deltas(potions[simplest_potion_id]).map(&:abs)
return next_step_towards(target_inventory)
end
# "WAIT"
raise("Dunno what to do!")
end
# V2, uses perspective cruncher
# Cruncher has the brute-forcing component that is reliable and deterministic.
# And the goal component, which I am not sure about at this point.
# Goal could be:
# 1. Always leftmost potion, snag dat bonus
# 2. Always the priciest potion
# 3. always the quickest to make (but this depends on spells, dont it?)
# 4. cost/benefit idea, but also depends on spell availability.
# 5. can theoretically use perspective cruncher to evaluate cost to make any resource
# 6. possibly less random, would be to use a graph structure to determine how many resources I
# can (or could) make in some most efficient setup
#
# For now going for 1. always leftmost potion!
def move_v2
move = nil
# realtime
elapsed = Benchmark.realtime do
brewable_potion = potions.find { |_id, potion| i_can_brew?(potion) }
if brewable_potion
return "BREW #{ brewable_potion[0] } Brewin' #{ brewable_potion[0] }"
end
if me[5] < 10 # before 10th turn
closest_pure_giver_spell =
tomes.find do |id, _tome|
GameSimulator::PURE_GIVER_IDS.include?(id)
end
#=> [id, tome]
# never learn pure givers in 6th tome spot, too expensive
if closest_pure_giver_spell && closest_pure_giver_spell[1][5] < 5
tax_for_giver = [closest_pure_giver_spell[1][5], 0].max
the_moves = GameSimulator.the_instance.moves_towards(
start: position, target: [tax_for_giver, 0, 0, 0]
)
move =
if the_moves == []
# oh, already there, let's learn
"LEARN #{ closest_pure_giver_spell[0] }"
else
"#{ the_moves.first } let's try learning #{ closest_pure_giver_spell[0] } via [#{ the_moves.join(", ") }]"
end
return move
end
end
if me[5] < 4 # before 4th turn
closest_very_good_spell =
tomes.find do |id, _tome|
GameSimulator::INSTALEARN_NET_FOUR_SPELLS.include?(id)
end
if closest_very_good_spell && closest_very_good_spell[1][5] <= me[0]
return "LEARN #{ closest_very_good_spell[0] } this one's a keeper!"
end
end
# if me[5] <= 4 # up to move 4, simply learning spells that give 2 or more net aqua
if me[5] <= 4 || gross_value(opp) < 5 # if opp is focused on learning also and has low value
lucrative_to_learn = GameSimulator.the_instance.
net_aqua_gains_from_learning(aquas_on_hand: me[0], tomes: tomes).
max_by{ |_id, gain| gain }
if lucrative_to_learn && lucrative_to_learn[1] >= 2
return "LEARN #{ lucrative_to_learn[0] } good Aqua gain from learning"
end
end
# casting [2,0,0,0] in the first few rounds if no learning has come up (yet)
if me[5] <= 4 || gross_value(opp) < 5 # if opp is focused on learning also and has low value
best_aqua_giver = my_spells.select do |id, spell|
# pure aqua giver
spell[1].positive? && spell[2].zero? && spell[3].zero? && spell[4].zero? &&
# can be cast
spell[5]
end.max_by{|_id, spell| spell[1] }
if best_aqua_giver
return "CAST #{ best_aqua_giver[0] } stockpiling Aquas early in the game"
end
end
# if me[5] < 4 # before 4th turn, hardcoded learning
# # identify 3rd spell as very good, by starting with Yello, down to Aqua, checking if I have giver
# # determine that [2, 0, 0, 0] is the state to learn it
# # run bruteforcer for that, make sure it returns learning
# closest_tactical_transmuter =
# tomes.find do |id, tome|
# next unless GameSimulator::TACTICAL_DEGENERATORS.include?(id)
# _i_have_a_givers_for_what_this_spell_takes =
# if tome[3].negative?
# givers_i_know[2]
# elsif tome[4].negative?
# givers_i_know[3]
# end
# end
# if closest_tactical_transmuter
# tax_for_transmuter = [closest_tactical_transmuter[1][5], 0].max
# the_moves = GameSimulator.the_instance.moves_towards(
# start: position, target: [tax_for_transmuter, 0, 0, 0]
# )
# move =
# if the_moves == []
# # oh, already there, let's learn
# "LEARN #{ closest_tactical_transmuter[0] }"
# else
# "#{ the_moves.first } let's try learning #{ closest_tactical_transmuter[0] } via [#{ the_moves.join(", ") }]"
# end
# return move
# end
# end
# if me[5] < 4 && givers_i_know[1] # i know green givers
# # identify tactical advantage in learning a green transmuter
# closest_green_user =
# tomes.find do |id, tome|
# next if id == 1 # LEARN 1 is very bad
# tome[2].negative? && tome[5] <= me[0]
# end
# if closest_green_user
# return "LEARN #{ closest_green_user[0] } learning useful transmuter that uses green"
# end
# # if I have green givers and the spell takes greens (an is not LEARN 1)
# end
leftmost_potion_with_bonus =
potions.find { |id, potion| potion[:tome_index] == 3 }
#[id, potion]
potion_to_work_towards =
if leftmost_potion_with_bonus
leftmost_potion_with_bonus
else
# [simplest_potion_id, potions[simplest_potion_id]]
most_lucrative_potion
end
the_moves = GameSimulator.the_instance.moves_towards(
start: position, target: deltas(potion_to_work_towards[1]).map(&:-@)
)
move =
if the_moves == []
# oh, already there, let's brew
"BREW #{ potion_to_work_towards[0] }"
else
"#{ the_moves.first } let's brew #{ potion_to_work_towards[0] } via [#{ the_moves.join(", ") }]"
end
end
debug("finding move_v2 '#{ move }' took #{ (elapsed * 1000.0).round }ms")
move
end
private
def position
@position ||= {
actions: actions,
me: me
}
end
# Just potion actions (have price), sorted descending by price
#
# @return [Hash]
def potions
@potions ||= actions.to_a.
select{ |id, action| action_type(action) == "BREW" }.
sort_by{ |id, action| -action[:price] }.
to_h
end
def my_spells
@my_spells ||= actions.to_a.
select{ |id, action| action_type(action) == "CAST" }.
to_h
end
# @return [bool, bool, bool, bool]
def givers_i_know
givers_i_know ||= my_spells.select do |id, action|
!action[1..4].find{ |v| v.negative? }
end.each_with_object([false, false, false, false]) do |(id, giver), mem|
mem[0] ||= giver[1].positive?
mem[1] ||= giver[2].positive?
mem[2] ||= giver[3].positive?
mem[3] ||= giver[4].positive?
end
end
def tomes
@tomes ||= actions.to_a.
select{ |id, action| action_type(action) == "LEARN" }.
to_h
end
def opp_spells
end
# @player [Array] :me or :opp array
# @return [Integer] 1 for any aqua 2 for green etc + worth from potions
def gross_value(player)
player[0] + player[1]*2 + player[2]*3 + player[3]*4 + player[4]
end
# @potion [Hash] # {:delta0=>0, delta1:-2, delta2:0, delta3:0}
# @return [Integer] # the relative cost to make a potion from empty inv
def cost_in_moves(potion)
costs = potion.slice(*COSTS.keys).map{ |k, v| v * COSTS[k] }
# minusing since potion deltas are negative
-costs.sum
end
# @return [Integer], the id of simplest potion in the market
def simplest_potion_id
return @simplest_potion_id if defined?(@simplest_potion_id)
@simplest_potion_id = potions.
map{ |id, potion| [id, cost_in_moves(potion)] }.
sort_by{|id, cost| cost }.
first[0]
end
def most_lucrative_potion
return @most_lucrative_potion if defined?(@most_lucrative_potion)
@most_lucrative_potion = potions.max_by{ |_id, potion| potion[:price] }
end
# For now assuming that all 'degeneration' spells are bad, and skipping them
#
# @return [Integer, nil]
def spell_to_learn_id
return @spell_to_learn_id if defined?(@spell_to_learn_id)
return @spell_to_learn_id = nil if me[4] > 15
# first pass, looking over up to fourth slot for pure giver spells
spell_to_learn =
tomes.find do |id, spell|
spell[5] == 0 && pure_giver_spell?(spell)
end
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 1 && pure_giver_spell?(spell) && me[0..3][0] >= 1
end
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 2 && pure_giver_spell?(spell) && me[0..3][0] >= 2
end
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 3 && pure_giver_spell?(spell) && me[0..3][0] >= 3
end
# first candidate is free
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 0 && !degeneration_spell?(spell)
end
# but subsequent need to consider tax
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 1 && !degeneration_spell?(spell) && me[0..3][0] >= 1
end
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 2 && !degeneration_spell?(spell) && me[0..3][0] >= 2
end
return @spell_to_learn_id = nil if spell_to_learn.nil?
@spell_to_learn_id = spell_to_learn[0]
end
# A spell is a degenerator if it's highest consumed ingredient tier is higher than produced tier
def degeneration_spell?(spell)
(deltas(spell) - [0]).last.negative?
end
def pure_giver_spell?(spell)
deltas(spell).find(&:negative?).nil?
end
# Killer method, considers inventory now, target, spells available.
# Assumes brewing is not possible, and assumes there's a clear unchanging
# hirearchy of ingredients (3>2>1>0)
#
# @target_inventory [Array] # [1, 2, 3, 4]
# @return [String]
def next_step_towards(target_inventory)
whats_missing = inventory_delta(me[0..3], target_inventory)
if whats_missing[3] > 0
spells_for_getting_yellow =
my_spells.select{ |id, spell| spell[4].positive? && spell[5] }
castable_spell =
spells_for_getting_yellow.find do |id, spell|
i_can_cast?(spell)
end
return "CAST #{ castable_spell[0] } Yello for #{ target_inventory }" if castable_spell
end
if whats_missing[2] > 0 || (whats_missing[3] > 0 && me[0..3][2] == 0)
spells_for_getting_orange =
my_spells.select{ |id, spell| spell[3].positive? && spell[5] }
castable_spell =
spells_for_getting_orange.find do |id, spell|
i_can_cast?(spell)
end
return "CAST #{ castable_spell[0] } Oranges for #{ target_inventory }" if castable_spell
end
if whats_missing[1] > 0 || ((whats_missing[2] > 0 || whats_missing[3] > 0) && me[0..3][1] == 0)
spells_for_getting_green =
begin
my_spells.select{ |id, spell| spell[2].positive? && spell[5] }
rescue => e
debug my_spells
end
castable_spell =
spells_for_getting_green.find do |id, spell|
i_can_cast?(spell)
end
return "CAST #{ castable_spell[0] } Goo for #{ target_inventory }" if castable_spell
end
if (whats_missing[0] > 0 || (whats_missing[1] > 0 || whats_missing[2] > 0 || whats_missing[3] > 0) && me[0..3][0] == 0)
spells_for_getting_blue =
begin
my_spells.select{ |id, spell| spell[1].positive? && spell[5] }
rescue => e
debug my_spells
end
castable_spell =
spells_for_getting_blue.find do |id, spell|
i_can_cast?(spell)
end
return "CAST #{ castable_spell[0] } Aqua for #{ target_inventory }" if castable_spell
end
"REST I'm beat while working towards #{ target_inventory }"
end
# @spell [Hash] # {:delta0=>0, delta1:-1, delta2:0, delta3:1, :castable=>true}
# @return [Boolean]
def i_can_cast?(spell)
return false unless spell[5]
GameSimulator.the_instance.can_cast?(
operation: deltas(spell), from: me[0..3]
)[:can]
end
# Returns positions and counts that are missing
def inventory_delta(now, target)
(0..3).map do |i|
have = now[i]
need = target[i]
if have >= need
0
else
need - have
end
end
end
# @potion [Hash] # {:delta0=>0, delta1:-2, delta2:0, delta3:0}
# @return [Boolean]
def i_can_brew?(potion)
deltas = deltas(potion)
problems =
(0..3).to_a.map do |i|
next if (me[0..3][i] + deltas[i]) >= 0
i
end
can = problems.compact.none?
# debug("I can brew #{ potion }: #{ can }")
can
end
end
# game loop
@turn = 1
@previous_move = ""
loop do
action_count = gets.to_i # the number of spells and recipes in play
actions = {}
action_count.times do
# action_id: the unique ID of this spell or recipe
# action_type: in the first league: BREW; later: CAST, OPPONENT_CAST, LEARN, BREW
# delta0: tier-0 ingredient change
# delta1: tier-1 ingredient change
# delta2: tier-2 ingredient change
# delta3: tier-3 ingredient change
# price: the price in rupees if this is a potion
# tome_index: in the first two leagues: always 0; later: the index in the tome if this is a tome spell, equal to the read-ahead tax; For brews, this is the value of the current urgency bonus
# tax_count: in the first two leagues: always 0; later: the amount of taxed tier-0 ingredients you gain from learning this spell; For brews, this is how many times you can still gain an urgency bonus
# castable: in the first league: always 0; later: 1 if this is a castable player spell
# repeatable: for the first two leagues: always 0; later: 1 if this is a repeatable player spell
action_id, action_type, delta0, delta1, delta2, delta3, price, tome_index, tax_count, castable, repeatable = gets.split(" ")
action_id = action_id.to_i
actions[action_id.to_i] =
if action_type == "LEARN"
# [type, (1..4)inv, 5=tome_index, 6=tax_bonus]
[action_type, delta0.to_i, delta1.to_i, delta2.to_i, delta3.to_i, tome_index.to_i, tax_count.to_i]
elsif action_type == "CAST"
# [type, (1..4)inv, 5=castable, 6=repeatable]
[action_type, delta0.to_i, delta1.to_i, delta2.to_i, delta3.to_i, castable.to_i == 1, repeatable.to_i == 1]
else # as in BREW and OPP_CAST
{
type: action_type,
delta0: delta0.to_i,
delta1: delta1.to_i,
delta2: delta2.to_i,
delta3: delta3.to_i,
price: price.to_i,
tome_index: tome_index.to_i,
tax_count: tax_count.to_i,
castable: castable.to_i == 1,
repeatable: repeatable.to_i == 1
}
end
end
inv0, inv1, inv2, inv3, score = gets.split(" ").map(&:to_i)
me = [
inv0, inv1, inv2, inv3, #[0..3]
score, # 4
@turn, # 5
@previous_move # 6
]
inv0, inv1, inv2, inv3, score = gets.split(" ").map(&:to_i)
opp = [
inv0, inv1, inv2, inv3,
score
]
turn = GameTurn.new(
actions: actions,
me: me,
opp: opp
)
# in the first league: BREW <id> | WAIT; later: BREW <id> | CAST <id> [<times>] | LEARN <id> | REST | WAIT
# puts(@previous_move = turn.move)
puts(@previous_move = turn.move_v2)
@turn += 1
end
<file_sep>class GameSimulator
# This class provides methods to advance game state into the future to a certain degree
# opponent moves can naturally not be simulated, and impossible to know what new spells
# and potions will appear later.
class ::SimulatorError < RuntimeError; end
# 78, 82 are default 1st spell ids, the [2, 0, 0, 0] spells
PURE_GIVER_IDS = [78, 82, 2, 3, 4, 12, 13, 14, 15, 16].to_set.freeze
GOOD_SPELL_IDS = [18, 17, 38, 39, 40, 30, 34].to_set.freeze
TACTICAL_DEGENERATORS = [31, 32, 41, 7, 5, 19, 26, 27].to_set.freeze
INSTALEARN_NET_FOUR_SPELLS = [12, 13, 14, 15, 16, 33].to_set.freeze
LEARNABLE_SPELLS = {
# id => [deltas, can be multicast, hard_skip, value_per_turn]
2 => [1, 1, 0, 0, false, false, 3], # pure giver
3 => [0, 0, 1, 0, false, false, 3], # pure giver
4 => [3, 0, 0, 0, false, false, 3], # pure giver
12 => [2, 1, 0, 0, false, false, 4], # pure giver
13 => [4, 0, 0, 0, false, false, 4], # pure giver
14 => [0, 0, 0, 1, false, false, 4], # pure giver
15 => [0, 2, 0, 0, false, false, 4], # pure giver
16 => [1, 0, 1, 0, false, false, 4], # pure giver
# excellent transmuters
18 => [-1, -1, 0, 1, true, false, 1], # IMBA, huge multicast potential, special in that it takes two givers
17 => [-2, 0, 1, 0, true, false, 1], # GREAT!, better version of 11
38 => [-2, 2, 0, 0, true, false, 2], # OK
39 => [0, 0, -2, 2, true, false, 2], # OK
40 => [0, -2, 2, 0, true, false, 2], # OK
30 => [-4, 0, 1, 1, true, false, 3], # OK
34 => [-2, 0, -1, 2, true, false, 3], # OK, takes two givers
33 => [-5, 0, 3, 0, true, false, 4], # OK, one of the rare spells with net+ of 4
# Tactical degens, ony from orange and yello for now
31 => [0, 3, 2, -2, true, false, 4], # degen. excellent if you have [0, 0, 0, 1]
32 => [1, 1, 3, -2, true, false, 4], # degen
41 => [0, 0, 2, -1, true, false, 2], # degen, good chance to multicast
7 => [3, 0, 1, -1, true, false, 2], # degen
26 => [1, 1, 1, -1, true, false, 2], # degen, excellent multicast
5 => [2, 3, -2, 0, true, false, 2], # degen
19 => [0, 2, -1, 0, true, false, 1], # degen
27 => [1, 2, -1, 0, true, false, 2], # degen, good multicast
0 => [-3, 0, 0, 1, true, false, 1], # so-so-to-OK
21 => [-3, 1, 1, 0, true, false, 2], # so-so, lossy
37 => [-3, 3, 0, 0, true, false, 3], # so-so-to-OK
6 => [2, 1, -2, 1, true, false, 2], # so-so, lossy
10 => [2, 2, 0, -1, true, false, 2], # degen
24 => [0, 3, 0, -1, true, false, 2], # degen
22 => [0, 2, -2, 1, true, false, 2], # so-so, twist
28 => [4, 1, -1, 0, true, false, 3], # degen, low chance to multicast :(
35 => [0, 0, -3, 3, true, false, 3], # so-so, situational, when are you gonna have 3 oranges?
8 => [3, -2, 1, 0, true, false, 2], # so-so, lossy
9 => [2, -3, 2, 0, true, false, 2], # so-so, lossy
20 => [2, -2, 0, 1, true, false, 2], # so-so, lossy
23 => [1, -3, 1, 1, true, false, 2], # so-so, twist
25 => [0, -3, 0, 2, true, false, 2], # so-so
36 => [0, -3, 3, 0, true, false, 3], # so-so
11 => [-4, 0, 2, 0, true, false, 2], # so-so, bad version of 17
29 => [-5, 0, 0, 2, true, false, 3], # mehh, situational
1 => [3, -1, 0, 0, true, true, 1], # degen, extremely situational
}.freeze
LEARNED_SPELL_DATA = {
2 => ["CAST", 1, 1, 0, 0, true, false],
3 => ["CAST", 0, 0, 1, 0, true, false],
4 => ["CAST", 3, 0, 0, 0, true, false],
12 => ["CAST", 2, 1, 0, 0, true, false],
13 => ["CAST", 4, 0, 0, 0, true, false],
14 => ["CAST", 0, 0, 0, 1, true, false],
15 => ["CAST", 0, 2, 0, 0, true, false],
16 => ["CAST", 1, 0, 1, 0, true, false],
18 => ["CAST", -1, -1, 0, 1, true, true],
17 => ["CAST", -2, 0, 1, 0, true, true],
38 => ["CAST", -2, 2, 0, 0, true, true],
39 => ["CAST", 0, 0, -2, 2, true, true],
40 => ["CAST", 0, -2, 2, 0, true, true],
30 => ["CAST", -4, 0, 1, 1, true, true],
34 => ["CAST", -2, 0, -1, 2, true, true],
0 => ["CAST", -3, 0, 0, 1, true, true],
1 => ["CAST", 3, -1, 0, 0, true, true],
5 => ["CAST", 2, 3, -2, 0, true, true],
6 => ["CAST", 2, 1, -2, 1, true, true],
7 => ["CAST", 3, 0, 1, -1, true, true],
8 => ["CAST", 3, -2, 1, 0, true, true],
9 => ["CAST", 2, -3, 2, 0, true, true],
10 => ["CAST", 2, 2, 0, -1, true, true],
11 => ["CAST", -4, 0, 2, 0, true, true],
19 => ["CAST", 0, 2, -1, 0, true, true],
20 => ["CAST", 2, -2, 0, 1, true, true],
21 => ["CAST", -3, 1, 1, 0, true, true],
22 => ["CAST", 0, 2, -2, 1, true, true],
23 => ["CAST", 1, -3, 1, 1, true, true],
24 => ["CAST", 1, 3, 0, -1, true, true],
25 => ["CAST", 1, -3, 0, 2, true, true],
26 => ["CAST", 1, 1, 1, -1, true, true],
27 => ["CAST", 1, 2, -1, 0, true, true],
28 => ["CAST", 4, 1, -1, 0, true, true],
31 => ["CAST", 0, 3, 2, -2, true, true],
32 => ["CAST", 1, 1, 3, -2, true, true],
35 => ["CAST", 0, 0, -3, 3, true, true],
36 => ["CAST", 0, -3, 3, 0, true, true],
37 => ["CAST", -3, 3, 0, 0, true, true],
33 => ["CAST", -5, 0, 3, 0, true, true],
29 => ["CAST", -5, 0, 0, 2, true, true],
41 => ["CAST", 0, 0, 2, -1, true, true]
}.freeze
POTIONS = {
42 => [[2, 2, 0, 0], 6],
43 => [[3, 2, 0, 0], 7],
44 => [[0, 4, 0, 0], 8],
45 => [[2, 0, 2, 0], 8],
46 => [[2, 3, 0, 0], 8],
47 => [[3, 0, 2, 0], 9],
48 => [[0, 2, 2, 0], 10],
49 => [[0, 5, 0, 0], 10],
50 => [[2, 0, 0, 2], 10],
51 => [[2, 0, 3, 0], 11],
52 => [[3, 0, 0, 2], 11],
53 => [[0, 0, 4, 0], 12],
54 => [[0, 2, 0, 2], 12],
55 => [[0, 3, 2, 0], 12],
56 => [[0, 2, 3, 0], 13],
57 => [[0, 0, 2, 2], 14],
58 => [[0, 3, 0, 2], 14],
59 => [[2, 0, 0, 3], 14],
60 => [[0, 0, 5, 0], 15],
61 => [[0, 0, 0, 4], 16],
62 => [[0, 2, 0, 3], 16],
63 => [[0, 0, 3, 2], 17],
64 => [[0, 0, 2, 3], 18],
65 => [[0, 0, 0, 5], 20],
66 => [[2, 1, 0, 1], 9],
67 => [[0, 2, 1, 1], 12],
68 => [[1, 0, 2, 1], 12],
69 => [[2, 2, 2, 0], 13],
70 => [[2, 2, 0, 2], 15],
71 => [[2, 0, 2, 2], 17],
72 => [[0, 2, 2, 2], 19],
73 => [[1, 1, 1, 1], 12],
74 => [[3, 1, 1, 1], 14],
75 => [[1, 3, 1, 1], 16],
76 => [[1, 1, 3, 1], 18],
77 => [[1, 1, 1, 3], 20]
}.freeze
SPELL_TYPES = ["CAST", "OPPONENT_CAST"].freeze
def self.the_instance
@the_instance ||= new
end
def initialize; end
# Returns the init parameters for the GameTurn that would follow after a certain move
# Caches the outcomes, since same state and same move will always result in the same outcome
#
# @position [Hash] #
# @return [Hash]
# @return [String] # err message if there's err
def result(position:, move:)
portions = move.split(" ")
verb = portions.first #=> "LEARN", "REST", "CAST"
case verb
when "REST"
if position.dig(:me, 6).to_s.start_with?("REST")
return "do not rest twice in a row!"
end
p = dup_of(position)
p[:actions].transform_values! do |v|
if action_type(v) == "CAST"
v[5] = true
v
else
v
end
end
p[:me][5] += 1
p[:me][6] = move
p
when "LEARN"
id = portions[1].to_i
learned_spell = position[:actions][id]
learn_index = learned_spell[5]
if learn_index > position[:me][0]
return "insufficient aqua for learning tax!"
end
# needed to know what will be the added spell's id
max_cast_id =
position[:actions].max_by do |id, action|
if SPELL_TYPES.include?(action_type(action))
id
else
-1
end
end.first
# 1. learning
# removes learned spell from list
# adds a spell with correct id to own spells
p = dup_of(position)
p[:actions].reject!{ |k, v| k == id }
p[:actions].transform_values! do |v|
if action_type(v) == "LEARN"
if v[5] > learn_index
v[5] -= 1
end
if v[5] < learn_index
v[6] += 1
end
v
else
v
end
end
p[:actions][max_cast_id.next] = LEARNED_SPELL_DATA[id]
p[:me][5] += 1
p[:me][6] = move
p[:me][0] -= learn_index
p[:me][0] += learned_spell[6] if learned_spell[6].positive?
p
when "CAST"
id = portions[1].to_i
cast_spell = position[:actions][id]
return "spell exhausted!" unless cast_spell[5]
cast_times =
if portions.size > 2
portions[2].to_i
else
1
end
if cast_times > 1 && !cast_spell[6]
return "spell can't multicast!"
end
operation =
if cast_times == 1
deltas(cast_spell)
else
deltas(cast_spell).map{ |v| v * cast_times}
end
casting_check = can_cast?(operation: operation, from: position[:me][0..3])
if !casting_check[:can]
if casting_check[:detail] == :insufficient_ingredients
return "insufficient ingredients for casting!" if cast_times == 1
return "insufficient ingredients for multicasting!"
else
return "casting overfills inventory!"
end
end
p = dup_of(position)
cast_times.times do
p[:me][0..3] = p[:me][0..3].add(deltas(cast_spell))
end
p[:actions][id][5] = false
# 2. casting
# changes my inv accordingly
# changes spell castability accordingly
p[:me][5] += 1
p[:me][6] = move
p
else
{error: "verb '#{ verb }' not supported"}
end
end
def dup_of(position)
# 2.22s
dupped_actions = position[:actions].dup
dupped_actions.transform_values!(&:dup)
{
actions: dupped_actions,
me: position[:me].dup
}
# # 2.38s
# {
# # actions: position[:actions].map{ |k, v| [k, v.dup]}.to_h,
# # actions: position[:actions].each_with_object({}){ |(k, v), mem| mem[k] = v.dup },
# me: position[:me].dup
# }
end
MY_MOVES = ["CAST", "LEARN"].to_set.freeze
DISTANCE_CUTOFF_DELTA = 6
MAXIMUM_DEPTH = 6
# This is the brute-forcing component.
# Uses heuristics to try most promising paths first
# @target [Array] # target inventory to solve for
# @start [Hash] # the starting position, actions and me expected
#
# @return [Array<String>]
def moves_towards(target:, start:, path: [], max_depth: MAXIMUM_DEPTH, depth: 0)
prime_candidate = nil
moves_to_return = nil
initial_distance_from_target = distance_from_target(
target: target, inv: start[:me][0..3]
)
return [] if initial_distance_from_target[:distance].zero?
# debug("Initial distance is #{ initial_distance_from_target }")
# This cleans position passed on in hopes of saving on dup time, works well
start[:actions] = start[:actions].select do |_k, v|
MY_MOVES.include?(action_type(v))
end.to_h
max_allowed_learning_moves = max_depth / 2 # in case of odd max debt, learn less
positions = {path => start}
ms_spent = 0.0
(1..max_depth).to_a.each do |generation|
break if moves_to_return
if ms_spent > 44
debug("Quick-returning #{ prime_candidate[0] } due to imminent timeout!")
return prime_candidate[0]
end
past_halfway = generation >= (max_depth / 2).next
generation_runtime = Benchmark.realtime do
debug("Starting move and outcome crunch for generation #{ generation }") if past_halfway
# debug("There are #{ positions.keys.size } positions to check moves for")
final_iteration = generation == max_depth
penultimate_iteration = generation == max_depth - 1
data = []
ms_spent_in_this_gen = ms_spent
positions.each_pair do |path, position|
position_processing_time = Benchmark.realtime do
already_studied_max_times =
past_halfway &&
path.count { |v| v.start_with?("LEARN") } >= max_allowed_learning_moves
# HH This prevents resting after just learning a spell
just_learned = position[:me][6].to_s.start_with?("LEARN")
moves = moves_from(
position: position,
skip_resting: final_iteration || just_learned,
skip_learning: final_iteration || already_studied_max_times
)
# debug("There are #{ moves.size } moves that can be made after #{ path }")
#=> ["REST", "CAST 79"]
moves.each do |move|
# 2. loop over OK moves, get results
outcome =
begin
result(position: positions[path], move: move)
rescue => e
raise("Path #{ path << move } leads to err: '#{ e.message }' in #{ e.backtrace.first }")
end
# outcome was an expected invalid move, skipping the outcome
next if outcome.is_a?(String)
# 3. evaluate the outcome
distance_from_target = distance_from_target(
target: target, inv: outcome[:me][0..3]
)
data << [
[*path, move],
{
outcome: outcome,
distance_from_target: distance_from_target
}
]
end
end * 1000
ms_spent_in_this_gen += position_processing_time
if ms_spent_in_this_gen > 44
debug("Doing an emergency break out of position processing due to time running out!")
break
end
end
# debug("There turned out to be #{ moves_to_try.size } moves to check") if past_halfway
data.sort_by! do |(_move, path), specifics|
[
specifics[:distance_from_target][:distance],
-specifics[:distance_from_target][:bonus]
]
end
#=> [[move, data], ["CATS 78", {outcome: {actions: {...}}}]]
prime_candidate = data.first
prime_specifics = prime_candidate[1]
# check best move, if with it we're there, done!
return_prime_candidate =
if prime_specifics[:distance_from_target][:distance] == 0
:target_reached
elsif final_iteration
:max_depth_reached
else
false
end
if return_prime_candidate
debug("Returning prime candidate because #{ return_prime_candidate }")
moves_to_return = prime_candidate[0]
else
# no move got us there, lets go deeper.
# here's we can inject heuristics of which results to keep and drop for next gen
# 1. drop outcomes that are too far behind the best variant. Since some spells give 4 in one move,
# probably safe to use 8+
# 1. dropping hopeless variations
lowest_distance = prime_specifics[:distance_from_target][:distance]
no_longer_tolerable_distance =
# the further in we are, the less forgiving of bad variations we are
if penultimate_iteration
lowest_distance + DISTANCE_CUTOFF_DELTA - 1
else
lowest_distance + DISTANCE_CUTOFF_DELTA
end
cutoff_index = nil
data.each.with_index do |(new_path, specifics), i|
if specifics[:distance_from_target][:distance] < no_longer_tolerable_distance
next
end
# detects no progress towards target past the halfway mark, pure idling here.
if past_halfway
if specifics[:distance_from_target][:distance] <= initial_distance_from_target[:distance]
if specifics[:distance_from_target][:bonus] <= initial_distance_from_target[:bonus]
cutoff_index = i
break
end
end
end
cutoff_index = i
break
end
if cutoff_index
# debug("Cutoff at index #{ cutoff_index } from #{ data.size }")
debug("Cutoff at index #{ cutoff_index } from OMITTED")
data = data[0..(cutoff_index-1)]
else
debug(
"Nothing to cut off, "\
"closest variant has #{ prime_specifics[:distance_from_target] }, "\
"and furthest has #{ data.last[1][:distance_from_target] }"
) if past_halfway
end
positions = {}
data.each do |variation_path, specifics|
positions[variation_path] = specifics[:outcome]
end
end
end * 1000
ms_spent += generation_runtime
debug("Gen #{ generation } ran for #{ generation_runtime.round(1) }ms, totalling #{ ms_spent.round(1) }ms") if past_halfway
end
moves_to_return
end
# This is the evaluator method.
# every ingredient that is missing from target is taken to be a distance of [1,2,3,4] respectively
# ingredients that are more do not reduce distance, but are counted as a bonus
#
# @return [Hash]
def distance_from_target(target:, inv:)
@distance_cache ||= {}
key = [target, inv]
if @distance_cache.key?(key)
@distance_cache[key]
else
sum = target.add(inv.map{|v| -v})
distance = sum.map.with_index{ |v, i| next unless v.positive?; v*i.next }.compact.sum
bonus = sum.map.with_index{ |v, i| next unless v.negative?; -v*i.next }.compact.sum
@distance_cache[key] = {distance: distance, bonus: bonus}
end
# sum = target.add(inv.map{|v| -v})
# distance = sum.map.with_index{ |v, i| next unless v.positive?; v*i.next }.compact.sum
# bonus = sum.map.with_index{ |v, i| next unless v.negative?; -v*i.next }.compact.sum
# {distance: distance, bonus: bonus}
end
# returns a net gain of 0 if can't afford learning tax anyway
def net_aqua_gains_from_learning(aquas_on_hand:, tomes:)
tomes.map do |id, tome|
gain =
if aquas_on_hand >= tome[5]
tome[6] - tome[5]
else
0
end
[id, gain]
end
end
# Does not care about legality much, since simulator will check when deciding outcome.
# @return [Array<String>]
def moves_from(position:, skip_resting: false, skip_learning: false)
moves = []
all_spells_rested = true
givers_i_know = nil
spells =
position[:actions].select do |id, action|
action_type(action) == "CAST"
end
tomes =
position[:actions].select do |id, action|
action_type(action) == "LEARN"
end
aquas_on_hand = position[:me][0]
# can also give 0 and 1 aqua, beware
best_aqua_giver_from_learning = net_aqua_gains_from_learning(
aquas_on_hand: aquas_on_hand, tomes: tomes
).max_by{ |_id, gain| gain }
position[:actions].each do |id, action|
type = action_type(action)
if type == "LEARN" && !skip_learning
try_learning =
if PURE_GIVER_IDS.include?(id)
true
elsif spells.size >= 8
false
# elsif # TODO, consider not learning [-5] spells if an advanced aqua giver is not known
else
givers_needed = action[1..4].map{ |v| v.negative? } #=> [false, false, true, false]
givers_i_know ||= spells.select do |id, action|
!action[1..4].find{ |v| v.negative? }
end.each_with_object([false, false, false, false]) do |(id, giver), mem|
mem[0] ||= giver[1].positive?
mem[1] ||= giver[2].positive?
mem[2] ||= giver[3].positive?
mem[3] ||= giver[4].positive?
end
even_one_required_but_no_giver =
givers_needed.find.with_index do |req, i|
req && !givers_i_know[i]
end
!even_one_required_but_no_giver
end
moves << "LEARN #{ id }" if try_learning
elsif type == "CAST"
unless action[5] # oops, exhausted
all_spells_rested = false
next
end
times = possible_cast_times(spell: action, inv: position[:me][0..3])
next if times == 0
# givers can ever only be cast once
if times == 1
only_gives_aquas =
action[1].positive? && action[2].zero? && action[3].zero? && action[4].zero?
# preferring to get aquas by learning
if only_gives_aquas && best_aqua_giver_from_learning && best_aqua_giver_from_learning[1] >= action[1]
moves << "LEARN #{ best_aqua_giver_from_learning[0] }"
next
end
end
times.times do |i|
moves <<
if i == 0
"CAST #{ id }"
else
"CAST #{ id } #{ i.next }"
end
end
end
end
if skip_resting || position[:me][6].to_s.start_with?("REST") || all_spells_rested
else
moves << "REST"
end
moves.uniq
end
# Returns ways can this spell can be cast in. 0, 1 or n(multicast) variants possible.
# @return [Integer] # number of times the spell can be cast from this inventory
def possible_cast_times(spell:, inv:)
# @cast_time_cache ||= {}
# key = [spell, inv]
# if @cast_time_cache.key?(key)
# @cast_time_cache[key]
# else
# return @cast_time_cache[key] = 0 unless spell[5]
# deltas = deltas(spell)
# can_cast_once = can_cast?(operation: deltas, from: inv)
# return @cast_time_cache[key] = 0 unless can_cast_once[:can]
# # here we know that can be cast at least once
# return @cast_time_cache[key] = 1 unless spell[6]
# # here we know the spell can be repeated
# (2..5).to_a.each do |i|
# next if can_cast?(operation: deltas.map{ |v| v * i}, from: inv)[:can]
# return @cast_time_cache[key] = i-1
# end
# return @cast_time_cache[key] = 5
# end
return 0 unless spell[5]
deltas = deltas(spell)
can_cast_once = can_cast?(operation: deltas, from: inv)
return 0 unless can_cast_once[:can]
# here we know that can be cast at least once
return 1 unless spell[6]
# here we know the spell can be repeated
(2..5).to_a.each do |i|
next if can_cast?(operation: deltas.map { |v| v * i }, from: inv)[:can]
return i-1
end
5
end
NO_INGREDIENTS = {can: false, detail: :insufficient_ingredients}.freeze
INVENTORY_OVERFLOW = {can: false, detail: :overflow}.freeze
CANN = {can: true}.freeze
# Takes into account the two constraints
# - ingredients must suffice
# - inventory of 10 may not be exceeded
#
# @operation [Array] # deltas
# @return [Hash] {can: true/false, detail: :insufficient_ingredients/:overflow}
def can_cast?(operation:, from:)
# @cast_cache ||= {}
# key = [operation, from]
# if @cast_cache.key?(key)
# @cast_cache[key]
# else
# result = from.add(operation)
# return @cast_cache[key] = {can: false, detail: :insufficient_ingredients} if result.find{ |v| v.negative? }
# return @cast_cache[key] = {can: false, detail: :overflow} if result.sum > INVENTORY_SIZE
# @cast_cache[key] = {can: true}
# end
result = from.add(operation)
return NO_INGREDIENTS if result.find{ |v| v.negative? }
return INVENTORY_OVERFLOW if result.sum > INVENTORY_SIZE
CANN
end
end
<file_sep># frozen_string_literal: true
# rspec spec/game_simulator_spec.rb
RSpec.describe GameSimulator do
let(:instance) { described_class.new }
describe "#result(start:, move:)" do
subject(:result) { instance.result(position: position, move: move) }
context "when simply learning the 1st spell on the 1st move" do
let(:move) { "LEARN 8" }
let(:position) do
{
actions: {
8 => ["LEARN", 3, -2, 1, 0, 0, 0],
24 => ["LEARN", 0, 3, 0, -1, 1, 0],
0 => ["LEARN", -3, 0, 0, 1, 2, 0],
18 => ["LEARN", -1, -1, 0, 1, 3, 0],
21 => ["LEARN", -3, 1, 1, 0, 4, 0],
4 => ["LEARN", 3, 0, 0, 0, 5, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
82 => {type:"OPPONENT_CAST", delta0: 2, delta1:0, delta2:0, delta3:0, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
83 => {type:"OPPONENT_CAST", delta0: -1, delta1:1, delta2:0, delta3:0, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
84 => {type:"OPPONENT_CAST", delta0: 0, delta1:-1, delta2:1, delta3:0, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [3, 0, 0, 0, 0, 1, ""]
}
end
let(:outcome) do
{
actions: {
24 => ["LEARN", 0, 3, 0, -1, 0, 0],
0 => ["LEARN", -3, 0, 0, 1, 1, 0],
18 => ["LEARN", -1, -1, 0, 1, 2, 0],
21 => ["LEARN", -3, 1, 1, 0, 3, 0],
4 => ["LEARN", 3, 0, 0, 0, 4, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
82 => {type:"OPPONENT_CAST", delta0: 2, delta1:0, delta2:0, delta3:0, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
83 => {type:"OPPONENT_CAST", delta0: -1, delta1:1, delta2:0, delta3:0, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
84 => {type:"OPPONENT_CAST", delta0: 0, delta1:-1, delta2:1, delta3:0, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
86 => described_class::LEARNED_SPELL_DATA[8]
},
me: [3, 0, 0, 0, 0, 2, move]
}
end
it "returns the next game state, with spell removed from tome and added to memory" do
is_expected.to eq(outcome)
end
end
context "when learning a spell that I have to pay tax for" do
let(:move) { "LEARN 0" }
let(:position) do
{
actions: {
24 => ["LEARN", 0, 3, 0, -1, 0, 0],
0 => ["LEARN", -3, 0, 0, 1, 1, 0],
18 => ["LEARN", -1, -1, 0, 1, 2, 0],
21 => ["LEARN", -3, 1, 1, 0, 3, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
86 => ["CAST", 3, -2, 1, 0, true, true],
87 => {type:"OPPONENT_CAST", delta0: 3, delta1:-2, delta2:1, delta3:0, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>true},
},
me: [2, 0, 0, 0, 0, 2, ""]
}
end
let(:outcome) do
{
actions: {
24 => ["LEARN", 0, 3, 0, -1, 0, 1],
18 => ["LEARN", -1, -1, 0, 1, 1, 0],
21 => ["LEARN", -3, 1, 1, 0, 2, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
86 => ["CAST", 3, -2, 1, 0, true, true],
87 => {type:"OPPONENT_CAST", delta0: 3, delta1:-2, delta2:1, delta3:0, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>true},
88 => described_class::LEARNED_SPELL_DATA[0]
},
me: [1, 0, 0, 0, 0, 3, move]
}
end
it "returns a state where I have the spell and paid tax (gone from my inv, and put on next spell, and further spells shifted down" do
is_expected.to eq(outcome)
end
end
context "when learning a first spell that has tax aquas on it" do
let(:move) { "LEARN 24" }
let(:position) do
{
actions: {
24 => ["LEARN", 0, 3, 0, -1, 0, 1],
0 => ["LEARN", -3, 0, 0, 1, 1, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
87 => {type:"OPPONENT_CAST", delta0: 3, delta1:-2, delta2:1, delta3:0, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>true},
},
me: [2, 0, 0, 0, 0, 2, ""]
}
end
let(:outcome) do
{
actions: {
0 => ["LEARN", -3, 0, 0, 1, 0, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
87 => {type:"OPPONENT_CAST", delta0: 3, delta1:-2, delta2:1, delta3:0, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>true},
88 => described_class::LEARNED_SPELL_DATA[24]
},
me: [3, 0, 0, 0, 0, 3, move]
}
end
it "returns the next game state, with spell removed from tome and added to memory, and aqua added to my inv" do
is_expected.to eq(outcome)
end
end
context "when resting" do
let(:move) { "REST" }
let(:position) do
{
actions: {
24 => ["LEARN", 0, 3, 0, -1, 0, 0],
78 => ["CAST", 3, 0, 0, 0, false, false],
79 => ["CAST", -2, 2, 0, 0, false, true],
},
me: [2, 0, 0, 0, 0, 2, ""]
}
end
it "returns a state where I have unchanged resources, and all spells refreshed" do
is_expected.to eq(
actions: {
24 => ["LEARN", 0, 3, 0, -1, 0, 0],
78 => ["CAST", 3, 0, 0, 0, true, false],
79 => ["CAST", -2, 2, 0, 0, true, true],
},
me: [2, 0, 0, 0, 0, 3, "REST"]
)
end
end
context "when casting a pure giver spell" do
let(:move) { "CAST 78" }
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [0, 1, 0, 0, 0, 5, ""]
}
end
it "returns a state where I have more resources and spell is exhausted" do
is_expected.to eq(
actions: {
78 => ["CAST", 2, 0, 0, 0, false, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [2, 1, 0, 0, 0, 6, move],
)
end
end
context "when casting a vanilla transmute spell" do
let(:move) { "CAST 79" }
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [1, 0, 0, 0, 0, 4, ""]
}
end
it "returns a state where I have transmuted resources and spell is exhausted" do
is_expected.to eq(
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, false, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [0, 1, 0, 0, 0, 5, move]
)
end
end
context "when casting a degen transmute spell" do
let(:move) { "CAST 10" }
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
10 => ["CAST", 2, 2, 0, -1, true, true],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [1, 2, 3, 1, 0, 4, ""]
}
end
it "returns a state where I have transmuted resources and spell is exhausted" do
is_expected.to eq(
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
10 => ["CAST", 2, 2, 0, -1, false, true],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [3, 4, 3, 0, 0, 5, move]
)
end
end
context "when casting a multicast transmute spell" do
let(:move) { "CAST 10 2" }
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
10 => ["CAST", 2, 2, 0, -1, true, true],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [1, 0, 1, 2, 0, 4, ""]
}
end
it "returns a state where I have transmuted resources (x2!) and spell is exhausted" do
is_expected.to eq(
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
10 => ["CAST", 2, 2, 0, -1, false, true],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [5, 4, 1, 0, 0, 5, move]
)
end
end
context "when making an invalid move (two rests in a row)" do
let(:move) { "REST" }
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
10 => ["CAST", 2, 2, 0, -1, true, true],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [1, 0, 1, 2, 0, 4, "REST mehh"]
}
end
it "returns an error string" do
is_expected.to match(%r'do not rest twice in a row!')
end
end
context "when making an invalid move (learning a spell I can not pay tax for)" do
let(:move) { "LEARN 4" }
let(:position) do
{
actions: {
8 => ["LEARN", 3, -2, 1, 0, 0, 0],
24 => ["LEARN", 0, 3, 0, -1, 1, 0],
0 => ["LEARN", -3, 0, 0, 1, 2, 0],
18 => ["LEARN", -1, -1, 0, 1, 3, 0],
21 => ["LEARN", -3, 1, 1, 0, 4, 0],
4 => ["LEARN", 3, 0, 0, 0, 5, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [4, 0, 0, 0, 0, 1, ""]
}
end
it "returns an error string" do
is_expected.to match(%r'insufficient aqua for learning tax!')
end
end
context "when making an invalid move (casting an exhausted spell)" do
let(:move) { "CAST 79" }
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, false, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [3, 3, 2, 2, 0, 4, ""]
}
end
it "returns an error string" do
is_expected. to match(%r'spell exhausted!')
end
end
context "when making an invalid move (casting spell that I lack ingredients for)" do
let(:move) { "CAST 79" }
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [0, 0, 0, 0, 0, 4, ""]
}
end
it "returns an error string" do
is_expected. to match(%r'insufficient ingredients for casting!')
end
end
context "when making an invalid move (multicasting spell that I lack ingredients for)" do
let(:move) { "CAST 86 2" }
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
86 => ["CAST", -2, 2, 0, 0, true, true],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [3, 0, 0, 0, 0, 4, ""]
}
end
it "returns an error string" do
is_expected.to match(%r'insufficient ingredients for multicasting!')
end
end
context "when making an invalid move (casting a spell that overfills inventory)" do
let(:move) { "CAST 86" }
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
86 => ["CAST", 2, 2, 0, -1, true, true],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [4, 3, 1, 1, 0, 4, ""]
}
end
it "returns an error string" do
is_expected.to match(%r'casting overfills inventory!')
end
end
context "when making an invalid move (multicasting a spell that does not support it)" do
let(:move) { "CAST 79 2" }
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [1, 1, 1, 1, 0, 4, ""]
}
end
it "returns an error string" do
is_expected.to match(%r"spell can't multicast!")
end
end
end
describe "#moves_towards(target:, start:)" do
subject(:moves_towards) { instance.moves_towards(**options) }
let(:options) { {target: target, start: start, depth: 0} }
context "when we're already at the target, and should seek to brew or something" do
let(:target) { [2, 1, 0, 0] }
let(:start) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [3, 1, 0, 0, 0, 1, ""]
}
end
it { is_expected.to eq([]) }
end
context "when position is very simple, just make Aquas one time" do
let(:target) { [2, 0, 0, 0] }
let(:start) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [0, 0, 0, 0, 0, 1, ""]
}
end
it do
is_expected.to eq(["CAST 78"])
end
end
context "when position has two competing Aqua producing spells" do
let(:target) { [2, 0, 0, 0] }
let(:start) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
86 => ["CAST", 3, 0, 0, 0, true, false],
},
me: [0, 0, 0, 0, 0, 1, ""],
}
end
it "returns the move that reaches target and produces most bonus" do
is_expected.to eq(["CAST 86"])
end
end
context "when position is very simple, just make Aquas and rest several times" do
let(:target) { [6, 0, 0, 0] }
let(:start) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false}
},
me: [0, 0, 0, 0, 0, 1, ""]
}
end
it do
is_expected.to eq(["CAST 78", "REST", "CAST 78", "REST", "CAST 78"])
end
end
context "when position is still simple, just use imba spell and rest combo" do
let(:target) { [0, 0, 0, 4] }
let(:start) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
86 => ["CAST", 0, 0, 0, 1, false, false],
},
me: [0, 0, 0, 1, 0, 3, "CAST 86"]
}
end
it do
is_expected.to eq(["REST", "CAST 86", "REST", "CAST 86", "REST", "CAST 86"])
end
end
context "when position is such that saving up and doing a multicast is the best move" do
let(:target) { [0, 0, 0, 4] }
let(:start) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
90 => ["CAST", -3, 0, 0, 1, true, true],
},
me: [2, 0, 0, 0, 0, 3, "REST"]
}
end
it "knows patience and saves Aquas to do a single powerful transmute" do
is_expected.to eq(["CAST 78", "REST", "CAST 78", "CAST 90 2", "REST", "CAST 78"])
end
end
context "when position is such that saving up for learning is the best move" do
let(:options) { super().merge(max_depth: 7) }
let(:target) { [0, 0, 0, 4] }
let(:start) do
{
actions: {
# 8 => ["LEARN", delta0: 3, delta1:-2, delta2:1, delta3:0, price: 0, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>true},
# 24 => ["LEARN", delta0: 0, delta1:3, delta2:0, delta3:-1, price: 0, :tome_index=>1, :tax_count=>0, :castable=>false, :repeatable=>true},
# 0 => ["LEARN", delta0: -3, delta1:0, delta2:0, delta3:1, price: 0, :tome_index=>2, :tax_count=>0, :castable=>false, :repeatable=>true},
# 18 => ["LEARN", delta0: -1, delta1:-1, delta2:0, delta3:1, price: 0, :tome_index=>3, :tax_count=>0, :castable=>false, :repeatable=>true},
# 21 => ["LEARN", delta0: -3, delta1:1, delta2:1, delta3:0, price: 0, :tome_index=>4, :tax_count=>0, :castable=>false, :repeatable=>true},
14 => ["LEARN", 0, 0, 0, 1, 5, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
# 85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
},
me: [2, 0, 0, 0, 0, 3, "REST"]
}
end
it "knows patience and saves Aquas to learn an imba spell" do
is_expected.to eq(["CAST 78", "REST", "CAST 78", "LEARN 14", "CAST 82", "REST", "CAST 82"])
end
end
context "when position is such that to get 2 more Aquas the best move is to learn the first spell" do
let(:target) { [2, 0, 0, 1] }
let(:start) do
{
actions: {
35 => ["LEARN", 0, 0, -3, 3, 0, 2], # yeah, baby, get aquas from tax
31 => ["LEARN", 0, 3, 2, -2, 1, 2],
5 => ["LEARN", 2, 3, -2, 0, 2, 0],
30 => ["LEARN", -4, 0, 1, 1, 3, 0],
17 => ["LEARN", -2, 0, 1, 0, 4, 0],
41 => ["LEARN", 0, 0, 2, -1, 5, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
86 => ["CAST", 0, 0, 0, 1, false, false],
88 => {:type=>"OPPONENT_CAST", :delta0=>3, :delta1=>-1, :delta2=>0, :delta3=>0, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>true},
},
me: [0, 0, 0, 1, 0, 3, "CAST 86"]
}
end
it "opts to get aquas from spell tax" do
is_expected.to eq(["LEARN 35"])
end
end
context "when position is such that learning an imba pure giver and a situational degenerator are the best moves" do
xit "prefers getting the imba spell first, then the degen, and knows to save up" do
expect(0).to eq(1)
end
end
context "when it's a tricky position where inventory space is limited and a suboptimal transmute needs to be done" do
# Here we probably want to go for BREW 51, since we have blues, and oranges are easy to make.
# But perhaps the pro move is to snag the 1st spell with 4 tax points and "LEARN 14"!
# 68 => {:type=>"BREW", :delta0=>-1, :delta1=>0, :delta2=>-2, :delta3=>-1, :price=>15, :tome_index=>3, :tax_count=>3, :castable=>false, :repeatable=>false},
# 48 => {:type=>"BREW", :delta0=>0, :delta1=>-2, :delta2=>-2, :delta3=>0, :price=>11, :tome_index=>1, :tax_count=>4, :castable=>false, :repeatable=>false},
# 56 => {:type=>"BREW", :delta0=>0, :delta1=>-2, :delta2=>-3, :delta3=>0, :price=>13, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
# 51 => {:type=>"BREW", :delta0=>-2, :delta1=>0, :delta2=>-3, :delta3=>0, :price=>11, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
# 72 => {:type=>"BREW", :delta0=>0, :delta1=>-2, :delta2=>-2, :delta3=>-2, :price=>19, :tome_index=>0, :tax_count=>0, :castable=>false, :repeatable=>false},
# 31 => {:type=>"LEARN", :delta0=>0, :delta1=>3, :delta2=>2, :delta3=>-2, :price=>0, :tome_index=>0, :tax_count=>4, :castable=>false, :repeatable=>true},
# 1 => {:type=>"LEARN", :delta0=>3, :delta1=>-1, :delta2=>0, :delta3=>0, :price=>0, :tome_index=>1, :tax_count=>1, :castable=>false, :repeatable=>true},
# 32 => {:type=>"LEARN", :delta0=>1, :delta1=>1, :delta2=>3, :delta3=>-2, :price=>0, :tome_index=>2, :tax_count=>0, :castable=>false, :repeatable=>true},
# 18 => {:type=>"LEARN", :delta0=>-1, :delta1=>-1, :delta2=>0, :delta3=>1, :price=>0, :tome_index=>3, :tax_count=>0, :castable=>false, :repeatable=>true},
# 4 => {:type=>"LEARN", :delta0=>3, :delta1=>0, :delta2=>0, :delta3=>0, :price=>0, :tome_index=>4, :tax_count=>0, :castable=>false, :repeatable=>false},
# 14 => {:type=>"LEARN", :delta0=>0, :delta1=>0, :delta2=>0, :delta3=>1, :price=>0, :tome_index=>5, :tax_count=>0, :castable=>false, :repeatable=>false},
# 90 => {:type=>"OPPONENT_CAST", :delta0=>0, :delta1=>2, :delta2=>-2, :delta3=>1, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>true},
# 82 => {:type=>"CAST", :delta0=>2, :delta1=>0, :delta2=>0, :delta3=>0, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
# 83 => {:type=>"CAST", :delta0=>-1, :delta1=>1, :delta2=>0, :delta3=>0, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
# 84 => {:type=>"CAST", :delta0=>0, :delta1=>-1, :delta2=>1, :delta3=>0, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
# 85 => {:type=>"CAST", :delta0=>0, :delta1=>0, :delta2=>-1, :delta3=>1, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
# 87 => {:type=>"CAST", :delta0=>1, :delta1=>0, :delta2=>1, :delta3=>0, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>false, :repeatable=>false},
# => me: [5, 0, 0, 0], 0}
# => meta: {:turn=>12, previous_move: "CAST 87"}
xit " " do
expect(0).to eq(1)
end
end
context "when position is such that learning a useless spell just for the tax bonus is the best move" do
# NB, tax gains will never overflow inventory, so factor that into allowing
xit " " do
expect(0).to eq(1)
end
end
context "when an expected error occurs when traversing" do
let(:target) { [0, 0, 0, 4] }
let(:start) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
90 => ["CAST", -3, 0, 0, 1, true, true],
},
me: [2, 0, 0, 0, 0, 3, "REST"]
}
end
before do
allow(instance).to receive(:result).and_call_original
allow(instance).to(
receive(:result).
with(position: anything, move: "CAST 90 2")
).and_return("Oops")
end
it "ignores the error, merely skips that move branch" do
is_expected.to include("CAST 79")
end
end
context "when an unexpected error occurs when traversing" do
let(:target) { [0, 0, 0, 4] }
let(:start) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
90 => ["CAST", -3, 0, 0, 1, true, true],
},
me: [2, 0, 0, 0, 0, 3, "REST"]
}
end
before do
allow(instance).to receive(:result).and_call_original
allow(instance).to(
receive(:result).
with(position: anything, move: "CAST 90 2")
).and_raise("whoa there")
end
it "raises a descriptive error" do
expect{ subject }.to raise_error(
RuntimeError,
%r'Path \["CAST 78", "REST", "CAST 78", "CAST 90 2"\] leads to err: \'whoa there\' in'
)
end
end
end
describe "#distance_from_target(target:, inv:)" do
subject(:distance_from_target) { instance.distance_from_target(**options) }
let(:options) { {target: target, inv: inv} }
context "when precisely at target" do
let(:target) { [1, 0, 0, 0] }
let(:inv) { target }
it { is_expected.to eq(distance: 0, bonus: 0) }
end
context "when slightly over target" do
let(:target) { [1, 0, 0, 0] }
let(:inv) { [2, 1, 0, 0] }
it { is_expected.to eq(distance: 0, bonus: 3) }
end
context "when under target" do
let(:target) { [1, 0, 1, 0] }
let(:inv) { [0, 1, 0, 0] }
it { is_expected.to eq(distance: 4, bonus: 2) }
end
end
describe "#moves_from(position:, skip_resting: false, skip_learning: false)" do
subject(:moves_from) { instance.moves_from(**options) }
let(:options) { {position: position} }
context "when all categories of actions are possible" do
# - learning
# - casting
# - multicasting
# - rest
let(:position) do
{
actions: {
24 => ["LEARN", 0, 3, 0, -1, 0, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
85 => {type:"OPPONENT_CAST", delta0: 0, delta1:0, delta2:-1, delta3:1, price: 0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
86 => ["CAST", 0, -2, 2, 0, true, true],
87 => ["CAST", 0, 2, -1, 0, false, true],
88 => ["CAST", 0, 0, 0, 1, false, false]
},
me: [0, 4, 0, 0, 0, 1, ""]
}
end
it "returns an array of moves to try" do
is_expected.to contain_exactly(
"REST", "LEARN 24", "CAST 78", "CAST 86", "CAST 86 2"
)
end
end
context "when just rested" do
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, false, false], # this is fake, never will a spell be exhausted after resting
},
me: [0, 4, 0, 0, 0, 1, "REST"]
}
end
it "does not include resting among moves to try" do
is_expected.to be_empty
end
end
context "when didn't just rest, but all spells are off cooldown" do
let(:position) do
{
actions: {
78 => ["CAST", 2, 0, 0, 0, true, false],
80 => ["CAST", -2, 2, 0, 0, true, true],
},
me: [2, 4, 0, 0, 0, 1, "LEARN 8"]
}
end
it "does not include resting among moves to try" do
is_expected.to contain_exactly("CAST 78", "CAST 80")
end
end
context "when there are learnable spells that take expensive, not easily made inputs" do
let(:position) do
{
actions: {
6 => ["LEARN", 2, 1, -2, 1, 0, 0],
36 => ["LEARN", 0, -3, 3, 0, 1, 0],
35 => ["LEARN", 0, 0, -3, 3, 2, 0],
19 => ["LEARN", 0, 2, -1, 0, 3, 0],
14 => ["LEARN", 0, 0, 0, 1, 4, 0],
1 => ["LEARN", 3, -1, 0, 0, 5, 0],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, false, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
85 => {:type=>"OPPONENT_CAST", :delta0=>0, :delta1=>0, :delta2=>-1, :delta3=>1, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>false},
},
me: [3, 1, 1, 0, 0, 1, ""]
}
end
it "returns an array of moves that excludes learning those spells" do
is_expected.to contain_exactly("CAST 78", "CAST 80", "CAST 81", "LEARN 14", "REST")
end
end
context "when there are learnable spells that take expensive, not easily made inputs, and I know giver spell" do
let(:position) do
{
actions: {
35 => ["LEARN", 0, 0, -3, 3, 0, 1],
19 => ["LEARN", 0, 2, -1, 0, 1, 1],
1 => ["LEARN", 3, -1, 0, 0, 2, 1],
18 => ["LEARN", -1, -1, 0, 1, 3, 0],
9 => ["LEARN", 2, -3, 2, 0, 4, 0],
24 => ["LEARN", 0, 3, 0, -1, 5, 0], # the degen we should consider
78 => ["CAST", 2, 0, 0, 0, false, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 0, -1, 1, 0, true, false],
81 => ["CAST", 0, 0, -1, 1, true, false],
87 => ["CAST", 0, 0, 0, 1, true, false],
88 => {:type=>"OPPONENT_CAST", :delta0=>0, :delta1=>-3, :delta2=>3, :delta3=>0, :price=>0, :tome_index=>-1, :tax_count=>-1, :castable=>true, :repeatable=>true},
},
me: [2, 0, 0, 0, 0, 3, "LEARN 14 let's brew 52 via [LEARN 14, CAST 82, REST, CAST 82, CAST 78]"]
}
end
it "returns an array of moves that includes learning those spells" do
is_expected.to contain_exactly(
"CAST 79", "CAST 87", "LEARN 24", "REST"
)
end
end
context "when position allows getting two Aquas from learning 1st spell" do
let(:position) do
{
actions: {
35 => ["LEARN", 0, 0, -3, 3, 0, 2],
31 => ["LEARN", 0, 2, 0, 0, 1, 2],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 1, 1, 0, 0, true, false],
},
me: [1, 0, 0, 1, 0, 3, "CAST 86 let's brew 57 via [CAST 86, REST, CAST 86, CAST 78, CAST 79, CAST 80]"]
}
end
it "returns a set of moves that have learning, and not casting [2,0,0,0]" do
is_expected.to contain_exactly("LEARN 35", "LEARN 31", "CAST 79", "CAST 80")
end
end
context "when position allows getting net two Aquas from learning 3rd spell, and I can pay tax" do
let(:options) { super().merge(skip_learning: true) }
let(:position) do
{
actions: {
35 => ["LEARN", 0, 0, -3, 3, 0, 1],
31 => ["LEARN", 0, 2, 0, 0, 1, 1],
32 => ["LEARN", 0, 2, 0, 0, 2, 4],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 1, 1, 0, 0, true, false],
81 => ["CAST", 3, 1, 0, 0, true, false],
},
me: [2, 0, 0, 1, 0, 3, "CAST 86 let's brew 57 via [CAST 86, REST, CAST 86, CAST 78, CAST 79, CAST 80]"]
}
end
it "returns a set of moves that have learning, and not casting [2,0,0,0]" do
is_expected.to contain_exactly("LEARN 32", "CAST 79", "CAST 80", "CAST 81")
end
end
context "when position allows getting net four Aquas from learning 2nd spell, and I can pay tax" do
let(:options) { super().merge(skip_learning: true) }
let(:position) do
{
actions: {
35 => ["LEARN", 0, 0, -3, 3, 0, 1],
31 => ["LEARN", 0, 2, 0, 0, 1, 5],
78 => ["CAST", 2, 0, 0, 0, true, false],
79 => ["CAST", -1, 1, 0, 0, true, false],
80 => ["CAST", 1, 1, 0, 0, true, false],
81 => ["CAST", 3, 0, 0, 0, true, false],
82 => ["CAST", 4, 0, 0, 0, true, false],
},
me: [2, 0, 0, 1, 0, 3, "CAST 86 let's brew 57 via [CAST 86, REST, CAST 86, CAST 78, CAST 79, CAST 80]"]
}
end
it "returns a set of moves that have learning, and not casting [2,0,0,0], nor [3,0,0,0], nor [4,0,0,0]" do
is_expected.to contain_exactly("LEARN 31", "CAST 79", "CAST 80")
end
end
end
describe "#possible_cast_times(spell:, inv:)" do
subject(:possible_cast_times) do
instance.possible_cast_times(spell: spell, inv: inv)
end
context "when spell is exhausted" do
let(:spell) { ["CAST", -1, 1, 0, 0, false, false] }
let(:inv) { [2,0,0,0] }
it { is_expected.to eq(0) }
end
context "when spell is castable, but lacking inv" do
let(:spell) { ["CAST", -1, 1, 0, 0, true, false] }
let(:inv) { [0,0,0,0] }
it { is_expected.to eq(0) }
end
context "when a non-repeatable spell can be cast once" do
let(:spell) { ["CAST", -1, 1, 0, 0, true, false] }
let(:inv) { [1,0,0,0] }
it { is_expected.to eq(1) }
end
context "when a repeatable spell can be cast once" do
let(:spell) { ["CAST", -2, 2, 0, 0, true, true] }
let(:inv) { [3,0,0,0] }
it { is_expected.to eq(1) }
end
context "when a repeatable spell can be cast twice" do
let(:spell) { ["CAST", -2, 2, 0, 0, true, true] }
let(:inv) { [5,0,0,0] }
it { is_expected.to eq(2) }
end
context "when a repeatable spell can be cast five times, the max" do
let(:spell) { ["CAST", -2, 2, 0, 0, true, true] }
let(:inv) { [10,0,0,0] }
it { is_expected.to eq(5) }
end
end
describe "#can_cast?(operation:, from:)" do
subject(:can_cast?) { instance.can_cast?(operation: operation, from: from) }
context "when ingredients suffice for casting" do
let(:operation) { [-2, 1, 1, 1] }
let(:from) { [3, 0, 1, 2] }
it "returns true, and memoizes" do
is_expected.to eq(can: true)
# # now setting the cache ivar by force to see it's preferred
# key = [operation, from]
# instance.instance_variable_set("@cast_cache", {key => false})
# expect(
# instance.can_cast?(operation: operation, from: from)
# ).to be(false)
# # forcing some random value
# key = [operation, from]
# instance.instance_variable_set("@cast_cache", {key => :mehh})
# expect(
# instance.can_cast?(operation: operation, from: from)
# ).to eq(:mehh)
# # and back to true
# key = [operation, from]
# instance.instance_variable_set("@cast_cache", {})
expect(
instance.can_cast?(operation: operation, from: from)
).to eq(can: true)
end
end
context "when ingredients suffice for casting, but overflow inventory" do
let(:operation) { [-2, 1, 1, 1] }
let(:from) { [2, 2, 4, 2] }
it "returns false, and memoizes" do
is_expected.to eq(can: false, detail: :overflow)
end
end
context "when ingredients not sufficient for casting" do
let(:operation) { [-2, 1, 1, 1] }
let(:from) { [1, 2, 4, 2] }
it "returns false, and memoizes" do
is_expected.to eq(can: false, detail: :insufficient_ingredients)
end
end
end
end
<file_sep># Bronze ideas
## Perspective!
Perspective hinges on ability to extrapolate with reasonable precision:
1) Moves to make to reach a series of inventory states (will need caching of progression to be performant)
2) What the expected value to end of game (
either 100th turn or brewing #{ 6 } potions
) is from current state
1) Compare
all potion make cost with current spells
VS
all potion make cost with learning each of 6 spells (plust tax gotten, minus tax paid)
Learn as spell if its summed shortening of each potion's brew time exceeds 5 (
makes up for the turn spent learning and them some
) && it gives the best boost
2) When to stop learning?
a) Stop learning and cash in after opponent has brewed #{ 3rd } (halfway) potion
OR
b) #{ 50th } move has been reached
OR
c) If learning new spells does not increase value gained in the remaining moves (
this can be time consuming to calculate. Have to compare expected value from spells now
to expected value if spending a turn learning a good-looking spell
)
<file_sep>class GameTurn
# Given wood 2 spells, ingredient relative costs
COSTS = {
delta0: 1,
delta1: 3,
delta2: 5,
delta3: 7
}.freeze
attr_reader :actions, :me, :opp
def initialize(actions:, me:, opp:)
actions.each do |k, v|
debug("#{ k } => #{ v },", prefix: "")
end
@actions = actions
@me = me
@opp = opp
debug("me: #{ me }")
# debug("opp: #{ opp }")
end
# V1, a bunch of else-ifs
# The only public API, returns the preferable move string
def move
brewable_potion = potions.find { |id, potion| i_can_brew?(potion) }
unless brewable_potion.nil?
return "BREW #{ brewable_potion[0] } Brewin' #{ brewable_potion[0] }"
end
# nothing brewable, let's learn some spells!
if spell_to_learn_id
return "LEARN #{ spell_to_learn_id } Studyin'"
end
# nothing brewable, let's spell towards the simplest potion
if simplest_potion_id
target_inventory = deltas(potions[simplest_potion_id]).map(&:abs)
return next_step_towards(target_inventory)
end
# "WAIT"
raise("Dunno what to do!")
end
# V2, uses perspective cruncher
# Cruncher has the brute-forcing component that is reliable and deterministic.
# And the goal component, which I am not sure about at this point.
# Goal could be:
# 1. Always leftmost potion, snag dat bonus
# 2. Always the priciest potion
# 3. always the quickest to make (but this depends on spells, dont it?)
# 4. cost/benefit idea, but also depends on spell availability.
# 5. can theoretically use perspective cruncher to evaluate cost to make any resource
# 6. possibly less random, would be to use a graph structure to determine how many resources I
# can (or could) make in some most efficient setup
#
# For now going for 1. always leftmost potion!
def move_v2
move = nil
# realtime
elapsed = Benchmark.realtime do
brewable_potion = potions.find { |_id, potion| i_can_brew?(potion) }
if brewable_potion
return "BREW #{ brewable_potion[0] } Brewin' #{ brewable_potion[0] }"
end
if me[5] < 10 # before 10th turn
closest_pure_giver_spell =
tomes.find do |id, _tome|
GameSimulator::PURE_GIVER_IDS.include?(id)
end
#=> [id, tome]
# never learn pure givers in 6th tome spot, too expensive
if closest_pure_giver_spell && closest_pure_giver_spell[1][5] < 5
tax_for_giver = [closest_pure_giver_spell[1][5], 0].max
the_moves = GameSimulator.the_instance.moves_towards(
start: position, target: [tax_for_giver, 0, 0, 0]
)
move =
if the_moves == []
# oh, already there, let's learn
"LEARN #{ closest_pure_giver_spell[0] }"
else
"#{ the_moves.first } let's try learning #{ closest_pure_giver_spell[0] } via [#{ the_moves.join(", ") }]"
end
return move
end
end
if me[5] < 4 # before 4th turn
closest_very_good_spell =
tomes.find do |id, _tome|
GameSimulator::INSTALEARN_NET_FOUR_SPELLS.include?(id)
end
if closest_very_good_spell && closest_very_good_spell[1][5] <= me[0]
return "LEARN #{ closest_very_good_spell[0] } this one's a keeper!"
end
end
# if me[5] <= 4 # up to move 4, simply learning spells that give 2 or more net aqua
if me[5] <= 4 || gross_value(opp) < 5 # if opp is focused on learning also and has low value
lucrative_to_learn = GameSimulator.the_instance.
net_aqua_gains_from_learning(aquas_on_hand: me[0], tomes: tomes).
max_by{ |_id, gain| gain }
if lucrative_to_learn && lucrative_to_learn[1] >= 2
return "LEARN #{ lucrative_to_learn[0] } good Aqua gain from learning"
end
end
# casting [2,0,0,0] in the first few rounds if no learning has come up (yet)
if me[5] <= 4 || gross_value(opp) < 5 # if opp is focused on learning also and has low value
best_aqua_giver = my_spells.select do |id, spell|
# pure aqua giver
spell[1].positive? && spell[2].zero? && spell[3].zero? && spell[4].zero? &&
# can be cast
spell[5]
end.max_by{|_id, spell| spell[1] }
if best_aqua_giver
return "CAST #{ best_aqua_giver[0] } stockpiling Aquas early in the game"
end
end
# if me[5] < 4 # before 4th turn, hardcoded learning
# # identify 3rd spell as very good, by starting with Yello, down to Aqua, checking if I have giver
# # determine that [2, 0, 0, 0] is the state to learn it
# # run bruteforcer for that, make sure it returns learning
# closest_tactical_transmuter =
# tomes.find do |id, tome|
# next unless GameSimulator::TACTICAL_DEGENERATORS.include?(id)
# _i_have_a_givers_for_what_this_spell_takes =
# if tome[3].negative?
# givers_i_know[2]
# elsif tome[4].negative?
# givers_i_know[3]
# end
# end
# if closest_tactical_transmuter
# tax_for_transmuter = [closest_tactical_transmuter[1][5], 0].max
# the_moves = GameSimulator.the_instance.moves_towards(
# start: position, target: [tax_for_transmuter, 0, 0, 0]
# )
# move =
# if the_moves == []
# # oh, already there, let's learn
# "LEARN #{ closest_tactical_transmuter[0] }"
# else
# "#{ the_moves.first } let's try learning #{ closest_tactical_transmuter[0] } via [#{ the_moves.join(", ") }]"
# end
# return move
# end
# end
# if me[5] < 4 && givers_i_know[1] # i know green givers
# # identify tactical advantage in learning a green transmuter
# closest_green_user =
# tomes.find do |id, tome|
# next if id == 1 # LEARN 1 is very bad
# tome[2].negative? && tome[5] <= me[0]
# end
# if closest_green_user
# return "LEARN #{ closest_green_user[0] } learning useful transmuter that uses green"
# end
# # if I have green givers and the spell takes greens (an is not LEARN 1)
# end
leftmost_potion_with_bonus =
potions.find { |id, potion| potion[:tome_index] == 3 }
#[id, potion]
potion_to_work_towards =
if leftmost_potion_with_bonus
leftmost_potion_with_bonus
else
# [simplest_potion_id, potions[simplest_potion_id]]
most_lucrative_potion
end
the_moves = GameSimulator.the_instance.moves_towards(
start: position, target: deltas(potion_to_work_towards[1]).map(&:-@)
)
move =
if the_moves == []
# oh, already there, let's brew
"BREW #{ potion_to_work_towards[0] }"
else
"#{ the_moves.first } let's brew #{ potion_to_work_towards[0] } via [#{ the_moves.join(", ") }]"
end
end
debug("finding move_v2 '#{ move }' took #{ (elapsed * 1000.0).round }ms")
move
end
private
def position
@position ||= {
actions: actions,
me: me
}
end
# Just potion actions (have price), sorted descending by price
#
# @return [Hash]
def potions
@potions ||= actions.to_a.
select{ |id, action| action_type(action) == "BREW" }.
sort_by{ |id, action| -action[:price] }.
to_h
end
def my_spells
@my_spells ||= actions.to_a.
select{ |id, action| action_type(action) == "CAST" }.
to_h
end
# @return [bool, bool, bool, bool]
def givers_i_know
givers_i_know ||= my_spells.select do |id, action|
!action[1..4].find{ |v| v.negative? }
end.each_with_object([false, false, false, false]) do |(id, giver), mem|
mem[0] ||= giver[1].positive?
mem[1] ||= giver[2].positive?
mem[2] ||= giver[3].positive?
mem[3] ||= giver[4].positive?
end
end
def tomes
@tomes ||= actions.to_a.
select{ |id, action| action_type(action) == "LEARN" }.
to_h
end
def opp_spells
end
# @player [Array] :me or :opp array
# @return [Integer] 1 for any aqua 2 for green etc + worth from potions
def gross_value(player)
player[0] + player[1]*2 + player[2]*3 + player[3]*4 + player[4]
end
# @potion [Hash] # {:delta0=>0, delta1:-2, delta2:0, delta3:0}
# @return [Integer] # the relative cost to make a potion from empty inv
def cost_in_moves(potion)
costs = potion.slice(*COSTS.keys).map{ |k, v| v * COSTS[k] }
# minusing since potion deltas are negative
-costs.sum
end
# @return [Integer], the id of simplest potion in the market
def simplest_potion_id
return @simplest_potion_id if defined?(@simplest_potion_id)
@simplest_potion_id = potions.
map{ |id, potion| [id, cost_in_moves(potion)] }.
sort_by{|id, cost| cost }.
first[0]
end
def most_lucrative_potion
return @most_lucrative_potion if defined?(@most_lucrative_potion)
@most_lucrative_potion = potions.max_by{ |_id, potion| potion[:price] }
end
# For now assuming that all 'degeneration' spells are bad, and skipping them
#
# @return [Integer, nil]
def spell_to_learn_id
return @spell_to_learn_id if defined?(@spell_to_learn_id)
return @spell_to_learn_id = nil if me[4] > 15
# first pass, looking over up to fourth slot for pure giver spells
spell_to_learn =
tomes.find do |id, spell|
spell[5] == 0 && pure_giver_spell?(spell)
end
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 1 && pure_giver_spell?(spell) && me[0..3][0] >= 1
end
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 2 && pure_giver_spell?(spell) && me[0..3][0] >= 2
end
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 3 && pure_giver_spell?(spell) && me[0..3][0] >= 3
end
# first candidate is free
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 0 && !degeneration_spell?(spell)
end
# but subsequent need to consider tax
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 1 && !degeneration_spell?(spell) && me[0..3][0] >= 1
end
spell_to_learn ||=
tomes.find do |id, spell|
spell[5] == 2 && !degeneration_spell?(spell) && me[0..3][0] >= 2
end
return @spell_to_learn_id = nil if spell_to_learn.nil?
@spell_to_learn_id = spell_to_learn[0]
end
# A spell is a degenerator if it's highest consumed ingredient tier is higher than produced tier
def degeneration_spell?(spell)
(deltas(spell) - [0]).last.negative?
end
def pure_giver_spell?(spell)
deltas(spell).find(&:negative?).nil?
end
# Killer method, considers inventory now, target, spells available.
# Assumes brewing is not possible, and assumes there's a clear unchanging
# hirearchy of ingredients (3>2>1>0)
#
# @target_inventory [Array] # [1, 2, 3, 4]
# @return [String]
def next_step_towards(target_inventory)
whats_missing = inventory_delta(me[0..3], target_inventory)
if whats_missing[3] > 0
spells_for_getting_yellow =
my_spells.select{ |id, spell| spell[4].positive? && spell[5] }
castable_spell =
spells_for_getting_yellow.find do |id, spell|
i_can_cast?(spell)
end
return "CAST #{ castable_spell[0] } Yello for #{ target_inventory }" if castable_spell
end
if whats_missing[2] > 0 || (whats_missing[3] > 0 && me[0..3][2] == 0)
spells_for_getting_orange =
my_spells.select{ |id, spell| spell[3].positive? && spell[5] }
castable_spell =
spells_for_getting_orange.find do |id, spell|
i_can_cast?(spell)
end
return "CAST #{ castable_spell[0] } Oranges for #{ target_inventory }" if castable_spell
end
if whats_missing[1] > 0 || ((whats_missing[2] > 0 || whats_missing[3] > 0) && me[0..3][1] == 0)
spells_for_getting_green =
begin
my_spells.select{ |id, spell| spell[2].positive? && spell[5] }
rescue => e
debug my_spells
end
castable_spell =
spells_for_getting_green.find do |id, spell|
i_can_cast?(spell)
end
return "CAST #{ castable_spell[0] } Goo for #{ target_inventory }" if castable_spell
end
if (whats_missing[0] > 0 || (whats_missing[1] > 0 || whats_missing[2] > 0 || whats_missing[3] > 0) && me[0..3][0] == 0)
spells_for_getting_blue =
begin
my_spells.select{ |id, spell| spell[1].positive? && spell[5] }
rescue => e
debug my_spells
end
castable_spell =
spells_for_getting_blue.find do |id, spell|
i_can_cast?(spell)
end
return "CAST #{ castable_spell[0] } Aqua for #{ target_inventory }" if castable_spell
end
"REST I'm beat while working towards #{ target_inventory }"
end
# @spell [Hash] # {:delta0=>0, delta1:-1, delta2:0, delta3:1, :castable=>true}
# @return [Boolean]
def i_can_cast?(spell)
return false unless spell[5]
GameSimulator.the_instance.can_cast?(
operation: deltas(spell), from: me[0..3]
)[:can]
end
# Returns positions and counts that are missing
def inventory_delta(now, target)
(0..3).map do |i|
have = now[i]
need = target[i]
if have >= need
0
else
need - have
end
end
end
# @potion [Hash] # {:delta0=>0, delta1:-2, delta2:0, delta3:0}
# @return [Boolean]
def i_can_brew?(potion)
deltas = deltas(potion)
problems =
(0..3).to_a.map do |i|
next if (me[0..3][i] + deltas[i]) >= 0
i
end
can = problems.compact.none?
# debug("I can brew #{ potion }: #{ can }")
can
end
end
| e0db4219c1a85544cdd8f143b8aadcb25c41536b | [
"Markdown",
"Ruby"
]
| 12 | Ruby | Epigene/codingame_fall_2020_challenge | ab095e74192ccbe3be6b83f07d841ebdae0c66b2 | 0448676fae6621977f9feb037e6c994795e8d0be |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lthdt.chuong3.donglenh;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Locale;
import lthdt.chuong3.coffeelogic.CoffeeShop;
import lthdt.chuong3.coffeelogic.Manager;
/**
*
* @author Administrator
*/
public class testCoffee {
private static long[] managers;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParseException {
// TODO code application logic here
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
CoffeeShop[] a = new CoffeeShop[]
{
new CoffeeShop("Kha Coffee", "2 Nguyen Hue"),
new CoffeeShop("White garden", "4 Nguyen Sinh Cung"),
new CoffeeShop("Hong Kong", "33 Nguyen Khuyen")
};
Manager[] managers = new Manager[]
{
new Manager(a, 1000, "<NAME>", 0, df.parse("12-12-2000")),
new Manager(new CoffeeShop[]
{
new CoffeeShop("Hoang Hac", "12 Nguyen Hue")
},
2000, "<NAME>", 1, df.parse("12-12-1999"))
};
System.out.println(Arrays.toString(managers));
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lthdt.donglenh.chuong1;
/**
*
* @author Administrator
*/
public class bai4 {
public static void main(String[] args){
Shape htron = new Circle(5,1,2);
// System.out.println("chu vi cua hinh tron la "+htron.calcPerimeter());
// System.out.println("dien tich cua hinh tron la "+htron.calcArea());
System.out.println(htron.toString());
Shape hcn = new Rectangle(3, 15, 8, 5);
// System.out.println("Chu vi hcn " + hcn.calcPerimeter());
// System.out.println("Dien tich hcn " + hcn.calcArea());
System.out.println(hcn);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package wekapro;
import weka.classifiers.trees.J48;
/**
*
* @author Administrator
*/
public class Wekapro {
/**
* @param args the command line arguments
* @throws java.lang.Exception
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
// myknowledgemodel model = new myknowledgemodel(
// "C:\\Program Files\\Weka-3-8-5\\data\\iris.arff");
// System.out.println(model);
// model.savedata("D:\\data\\iris.arff");
// model.saveData2CSV("D:\\data\\iris_CSV.csv");
MyAprioriModel model = new MyAprioriModel("C:\\Program Files\\Weka-3-8-5\\data\\weather.numeric.arff",
"-N 10 -T 0 -C 0.9 -D 0.05 -U 1.0 -M 0.1 -S -1.0 -c -1",
"-R 2-3");
model.mineAssociationaRules();
// MyFPGrowtModel model = new MyFPGrowtModel("C:\\Program Files\\Weka-3-8-5\\data\\weather.nominal.arff",
// "-P 2 -I -1 -N 10 -T 0 -C 0.7 -D 0.05 -U 1.0 -M 0.2",
// "-N -R first-last");
// model.mineAssociationRules();
System.out.println(model);
// }
// myknowledgemodel model = new myknowledgemodel( "C:\\Program Files\\Weka-3-8-5\\data\\iris.arff", null, null);
// model.trainset = model.divideTrainTestR(model.dataset, 70, false);
// model.testset = model.divideTrainTestR(model.dataset, 70, true);
// System.out.println(model);
// System.out.println(model.trainset.toSummaryString());
// System.out.println(model.testset.toSummaryString());
// MyDecisionTreeModel model = new MyDecisionTreeModel("C:\\Program Files\\Weka-3-8-5\\data\\iris.arff",
// "-C 0.25 -M 2", null);
// model.buildDecisionTree();
// model.evaluateDicisionTree();
// System.out.println(model);
// // model.saveModel("D:\\data\\model\\decitiontree.model", model.tree);
// model.tree = (J48)model.loadModel("D:\\data\\model\\decitiontree.model");
// model.predictClassLabel(model.testset);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lthdt.chuong3.donglenh;
import lthdt.chuong3.coffeelogic.Bill;
import lthdt.chuong3.coffeelogic.Product;
/**
*
* @author Administrator
*/
public class testBILL {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws CloneNotSupportedException {
Bill a = new Bill(12, new Product[]{
new Product("Shampo", 12),
new Product("Closeup", 21)});
System.out.println("a = " + a);
Bill temp = (Bill) a.clone();
temp.setBillID(15);
System.out.println("a = " + a);
System.out.println("temp = " + temp);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package wekapro;
import java.awt.PageAttributes;
import java.io.File;
import java.io.IOException;
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVSaver;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.NominalToBinary;
import weka.filters.unsupervised.attribute.NumericToNominal;
import weka.filters.unsupervised.attribute.Remove;
import weka.filters.unsupervised.instance.RemovePercentage;
import weka.filters.unsupervised.instance.Resample;
/**
*
* @author Administrator
*/
public class myknowledgemodel {
DataSource source;
Instances dataset;
String[] model_options;
String[] data_optioins;
Instances trainset;
Instances testset;
public myknowledgemodel(String filename, String m_otps, String d_otps) throws Exception {
this.source = new DataSource(filename);
this.dataset = source.getDataSet();
if(m_otps != null){
this.model_options = weka.core.Utils.splitOptions(m_otps);
}
if(d_otps != null) {
this.data_optioins = weka.core.Utils.splitOptions(d_otps);
}
}
myknowledgemodel(String cProgram_FilesWeka385datairisarff) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public Instances removeData(Instances originalData) throws Exception {
Remove remove = new Remove();
remove.setOptions(data_optioins);
remove.setInputFormat(originalData);
return Filter.useFilter(originalData, remove);
}
public Instances convertData(Instances originalData) throws Exception{
NumericToNominal n2n = new NumericToNominal();
n2n.setOptions(data_optioins);
n2n.setInputFormat(originalData);
return Filter.useFilter(originalData, n2n);
}
public Instances convert2Binary(Instances originalData) throws Exception {
NominalToBinary n2b = new NominalToBinary();
n2b.setOptions(data_optioins);
n2b.setBinaryAttributesNominal(true);
n2b.setInputFormat(originalData);
return Filter.useFilter(originalData, n2b);
}
public void savedata(String filename) throws IOException{
ArffSaver outdata = new ArffSaver();
outdata.setInstances(this.dataset);
outdata.setFile(new File(filename));
outdata.writeBatch();
System.out.println("Finished");
}
public void saveData2CSV(String filename) throws IOException{
CSVSaver outdata = new CSVSaver();
outdata.setInstances(this.dataset);
outdata.setFile(new File(filename));
outdata.writeBatch();
System.out.println("Converted");
}
public Instances dividetrainTest(Instances originalSet,
double percent, boolean isTest ) throws Exception {
RemovePercentage rp = new RemovePercentage();
rp.setPercentage(percent);
rp.setInvertSelection(isTest);
rp.setInputFormat(originalSet);
return Filter.useFilter(originalSet, rp);
}
public Instances divideTrainTestR(Instances originalSet,
double percent, boolean isTest) throws Exception {
Resample rs = new Resample();
rs.setNoReplacement(true);
rs.setSampleSizePercent(percent);
rs.setInvertSelection(isTest);
rs.setInputFormat(originalSet);
return Filter.useFilter(originalSet, rs);
}
public void saveModel(String filename, Object model) throws Exception{
weka.core.SerializationHelper.write(filename, model);
}
public Object loadModel(String filename) throws Exception{
return weka.core.SerializationHelper.read(filename);
}
@Override
public String toString() {
return dataset.toSummaryString(); //To change body of generated methods, choose Tools | Templates.
}
void savedata2CSV(String ddatairis_CSVcsv) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Instances dividetrainTestR(Instances dataset, int i, boolean b) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Instances dividetrainTesR(Instances dataset, int i, boolean b) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| 5c05ee06ac5bb2bda216ba713b72a52b8fc45cfb | [
"Java"
]
| 5 | Java | nhitrannn/KHAIPHADULIEU | b0793070550f0432413c0be93471b3d8e714f11b | 00b7fbb22c6df1e181704c8c17366de273f2e234 |
refs/heads/main | <repo_name>andreramosilva/udacity<file_sep>/projeto_modulo3/problem_6.py
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
min = float('inf')
max = float('inf')
for number in ints:
if number > max:
max = number
elif number < min:
min = number
print((min, max))
return (min, max)
## Example Test Case of Ten Integers
import random
test1 = [i for i in range(0, 10)] # a list containing 0 - 9
random.shuffle(test1)
print ("Pass" if ((0, 9) == get_min_max(test1)) else "Fail")
test2 = [i for i in range(-9, 10)] # a list containing 0 - 9
random.shuffle(test2)
print ("Pass" if ((-9, 9) == get_min_max(test2)) else "Fail")
test3 = [i for i in range(5, 7)] # a list containing 0 - 9
random.shuffle(test3)
print ("Pass" if ((5, 6) == get_min_max(test3)) else "Fail")
test4 = []
print ("Pass" if (tuple() == get_min_max(test4)) else "Fail")<file_sep>/projeto_modulo2/problem_2/problem_2.py
## Locally save and call this file ex.py ##
# Code to demonstrate the use of some of the OS modules in python
import os
# Let us print the files in the directory in which you are running this script
print (os.listdir("."))
# Let us check if this file is indeed a file!
print (os.path.isfile("./ex.py"))
# Does the file end with .py?
print ("./ex.py".endswith(".py"))
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
list_of_paths = []
if suffix == "*":
if not os.path.isdir(path):
list_of_paths.append(path)
return list_of_paths
else:
current_path = os.listdir(path)
for sub_path in current_path:
current_sub_path = os.path.join(path, sub_path)
list_of_paths.append(current_sub_path)
list_of_paths.append(find_files("*", current_sub_path))
return list_of_paths #print(list_of_paths)
else:
#list_of_paths = []
if not os.path.isdir(path):
if path.endswith(suffix):
list_of_paths.append(path)
return list_of_paths
else:
current_path = os.listdir(path)
for sub_path in current_path:
current_sub_path = os.path.join(path, sub_path)
if current_sub_path.endswith(suffix):
list_of_paths.append(current_sub_path)
list_of_paths.append(find_files(suffix, current_sub_path))
#print(list_of_paths)
return list_of_paths
## Test cases :
print(find_files( ".h", "."))
print(find_files( "", "."))
print(find_files(".c", "."))
<file_sep>/projeto_modulo2/problem_3/problem_3.py
import sys
#import models as md
LEFT_BIT = "0"
RIGHT_BIT = "1"
class MinHeap:
def __init__(self, capacity = 10):
self.array = [None] * capacity
self.size = 0
def insert(self, value):
if self.size == len(self.array):
new_array = [None] *(2*len(self.array))
for i, element in enumerate(self.array):
new_array[i] = element
self.array = new_array
index = self.size
self.array[index] = value
while (index > 0):
parent_index = (index - 1) // 2
if self.array[index] < self.array[parent_index]:
self.array[index],self.array[parent_index] = self.array[parent_index], self.array[index]
index = parent_index
else:
break
self.size += 1
def get_min(self):
return self.array[0]
def delete_min(self):
if self.size == 0:
return
self.size -= 1
self.array[0] = self.array[self.size]
self.array[self.size] = None
self._min_heapify(0)
def pop_min(self):
min_el = self.get_min()
self.delete_min()
return min_el
def _min_heapify(self, index):
left = (2 * index) + 1
right = (2 * index) + 2
smallest = index
if left < self.size and self.array[left] < self.array[smallest]:
smallest = left
if right < self.size and self.array[right] < self.array[smallest]:
smallest = right
if smallest != index:
self.array[index], self.array[smallest] = self.array[smallest], self.array[index]
self._min_heapify(smallest)
class HuffmanNode:
def __init__(self, value = None , frequency = 0):
self.frequency = frequency
self.value = value
self.left = None
self.right = None
def __lt__(self, other):
return self.frequency < other.frequency
def __str__(self):
return f"['{self.value}': {self.frequency}]"
def build_huffman_tree(data):
'''
Build the huffman tree for data
:param data: string data to encode
:return: root node of a huffman tree
'''
frequency_table = {}
for ch in data:
frequency_table[ch] = frequency_table.get(ch , 0) + 1
priority_queue = MinHeap()
for ch , frequency in frequency_table.items():
new_node = HuffmanNode(ch,frequency)
priority_queue.insert(new_node)
while priority_queue.size > 1:
node1 = priority_queue.pop_min()
node2 = priority_queue.pop_min()
new_node = HuffmanNode(None,(node1.frequency + node2.frequency))
new_node.left = node1
new_node.right = node2
priority_queue.insert(new_node)
return priority_queue.get_min()
def generate_code_table(table,node,code):
if not node.left and not node.right:
table[node.value] = code
return table
if node.left:
generate_code_table(table,node.left,code + LEFT_BIT)
if node.right:
generate_code_table(table, node.right , code + RIGHT_BIT)
return table
def huffman_encoding(data):
if data is None or len(data) == 0:
return data, None
tree = build_huffman_tree(data)
code_table = generate_code_table({},tree,"")
encoded_data = ""
for ch in data:
encoded_data += code_table[ch]
return encoded_data,tree
def huffman_decoding(data, tree):
if data is None:
return None
decoded_data = ""
node = tree
for bit in data:
if bit == LEFT_BIT:
node = node.left
elif bit == RIGHT_BIT:
node = node.right
if not node.left and not node.right:
decoded_data += node.value
node = tree
return decoded_data
if __name__ == "__main__":
codes = {}
a_great_sentence = "The bird is the word"
encode = huffman_encoding(a_great_sentence)
print(encode)
decode = huffman_decoding(encode,encode[1])
print(decode)
a_great_sentence = "The bird is not the word"
encode = huffman_encoding(a_great_sentence)
print(encode)
decode = huffman_decoding(encode,encode[1])
print(decode)
a_great_sentence = "The buddy is the world"
encode = huffman_encoding(a_great_sentence)
print(encode)
decode = huffman_decoding(encode,encode[1])
print(decode)
print("The size of the data is: {}\n".format(
sys.getsizeof(a_great_sentence)))
print("The content of the data is: {}\n".format(a_great_sentence))
# encoded_data, tree = huffman_encoding(a_great_sentence)
#print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2))))
#print ("The content of the encoded data is: {}\n".format(encoded_data))
#decoded_data = huffman_decoding(encoded_data, tree)
#print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data)))
#print ("The content of the encoded data is: {}\n".format(decoded_data))
<file_sep>/projeto_modulo2/explanation_4.md
### Design:
<details about implementation such as data structures and algorithms used>
Recusively i check for every single possibility
### Time Complexity:
<Big O notation with brief explanation>
o(2**n)
### Space Complexity:
<Big O notation with brief explanation>
because i have to recursively look in to every single possibility I belive is o(2**n)
<file_sep>/projeto_modulo2/problem_1.py
class LRU_Cache(object):
def __init__(self, capacity):
self.size = 5
self.data = {}
self.calls = []
# Initialize class variables
def get(self, key):
# Retrieve item from provided key. Return -1 if nonexistent.
if key in self.calls:
self.calls.remove(key)
self.calls.append(key)
return self.data.get(key, -1)
def set(self, key, value):
# Set the value if the key is not present in the cache. If the cache is at capacity remove the oldest item.
if self.get(value) == -1:
if self.size == 0:
del self.data[self.calls[0]]
self.calls.remove(self.calls[0])
self.size += 1
self.data[key] = value
self.calls.append(key)
self.size -= 1
#test cases :
our_cache = LRU_Cache(5)
our_cache.set(1, 1)
our_cache.set(2, 2)
our_cache.set(3, 3)
our_cache.set(4, 4)
print(our_cache.get(1)) # returns 1
print(our_cache.get(2)) # returns 2
print(our_cache.get(9)) # returns -1 because 9 is not present in the cache
our_cache.set(5, 5)
our_cache.set(6, 6)
print(our_cache.get(3)) # returns -1 because the cache reached it's capacity and 3 was the least recently used entry
print(our_cache.get(8)) # returns -1 because 8 is not present in the cache
print(our_cache.get(2)) # returns 2
print(our_cache.data) # returns {1: 1, 2: 2, 4: 4, 5: 5, 6: 6}
#output final with all the tests
# (base) andreramossilva@MacBook-Pro projeto_modulo2 % python problem_1.py
# 1
# 2
# -1
# -1
# -1
# 2
# {1: 1, 2: 2, 4: 4, 5: 5, 6: 6}
<file_sep>/projeto_modulo3/explanation_2.md
### Design:
<details about implementation such as data structures and algorithms used>
I tried to apply binary search on this problem, where i search
recursively, breaking down the problem until
I find the solution.
### Time Complexity:
<Big O notation with brief explanation>
O(log N ) binary search would be O(log n) but i have to
search every time i split both sides so i belive is O(N log N) where N is the
amount i have to search until i find it every time i break the problem in two.
### Space Complexity:
<Big O notation with brief explanation>
O(log N )<file_sep>/README.md
# udacity
This project was created during my nanodegree program at udacity
https://www.udacity.com/course/data-structures-and-algorithms-nanodegree--nd256
Down here I will be updating as much as I can with resorces that I found helpfull
Big O :
https://www.youtube.com/watch?v=waPQP2TDOGE
https://www.bigocheatsheet.com/
https://wiki.python.org/moin/TimeComplexity
https://commons.wikimedia.org/wiki/File:Comparison_computational_complexity.svg
https://wiki.python.org/moin/BitwiseOperators
https://www.youtube.com/channel/UCmJz2DV1a3yfgrR7GqRtUUA
# see what is happening behind the scenes
http://pythontutor.com/
<file_sep>/projeto_modulo2/problem_5/problem_5.py
import hashlib
from _datetime import datetime
class Block:
def __init__(self, timestamp, data, prev, prev_hash):
self.timestamp = timestamp
self.data = data
self.previous_hash = prev_hash
self.prev = prev
self.hash = self.calc_hash(timestamp, data )
def calc_hash(self, time, data):
string_toencode = str(time)+str(data)
sha = hashlib.sha256()
hash_str = string_toencode.encode('utf-8')
sha.update(hash_str)
return sha.hexdigest()
class BlockChain:
def __init__(self):
self.head = None
self.tail = None
def add_block(self, data):
now = datetime.today()
timestamp = datetime.timestamp(now)
if self.head != None:
prev = self.tail
self.tail = Block(timestamp, data, prev,prev.previous_hash)
else:
self.head = Block(timestamp, data, 0,0)
self.tail = self.head
def print_block_chain(self):
current_block = self.tail
index = 0
while current_block:
print("Index: ", index)
print("Timestamp: ", datetime.fromtimestamp(current_block.timestamp))
print("data: ", current_block.data)
print("SHA256 Hash: ", current_block.hash)
print("Prev Hash: ", current_block.previous_hash)
current_block = current_block.prev
index += 1
# test case 1 :
new_block = BlockChain()
new_block.add_block("Genesis")
new_block.add_block("arbitrary")
new_block.add_block("2")
new_block.add_block("3")
new_block.add_block("4")
new_block.add_block("5")
new_block.add_block("6")
new_block.add_block("7")
new_block.print_block_chain()
#Example output:
# Index: 0
# Timestamp: 2021-02-06 16:55:08.979261
# data: 7
# SHA256 Hash: fc0cfeabad3d5e784087c5f2ba2c537d1844da0e117604a62a3165183f587a90
# Prev Hash: 0
# Index: 1
# Timestamp: 2021-02-06 16:55:08.979255
# data: 6
# SHA256 Hash: 6c7a92b229674a471c07f0ae30a4973f22feb4c3e66abfdb34524e2690cf91c8
# Prev Hash: 0
# Index: 2
# Timestamp: 2021-02-06 16:55:08.979249
# data: 5
# SHA256 Hash: 047cd00af24967853115bdb2ce881a2e6df74c52a8e61acbc33e5fb08b6c3c0a
# Prev Hash: 0
# Index: 3
# Timestamp: 2021-02-06 16:55:08.979244
# data: 4
# SHA256 Hash: f150314c2d377aa07b52e2b134aeb10fcce777914ae1574ff20ecaa5eaec673d
# Prev Hash: 0
# Index: 4
# Timestamp: 2021-02-06 16:55:08.979237
# data: 3
# SHA256 Hash: abfb80a670d3535b1bf965bc23f43d7046d7eef9fbfeb6440a73d6b4bbf42c35
# Prev Hash: 0
# Index: 5
# Timestamp: 2021-02-06 16:55:08.979230
# data: 2
# SHA256 Hash: 080978d5f29dd7371d06b15ba97bbb683205b830e03775775bb80f80e4ac7701
# Prev Hash: 0
# Index: 6
# Timestamp: 2021-02-06 16:55:08.979220
# data: arbitrary
# SHA256 Hash: 3ac086bacac7af238db3f4f3a51eb8cdd8aa715932323daa3ed3d80a4bf6009f
# Prev Hash: 0
# Index: 7
# Timestamp: 2021-02-06 16:55:08.979172
# data: Genesis
# SHA256 Hash: f5dde666020d473e777479dc36b7dd1b3c7dce938921bf694e9527c470385d11
# Prev Hash: 0
<file_sep>/projeto_modulo2/problem_6/explanation_6.md
### Design:
<details about implementation such as data structures and algorithms used>
For this one I convert first to a list so I can perform in a more simple way the operations;
### Time Complexity:
<Big O notation with brief explanation>
To convert is o(n) and o(n) as well to get the intersection because I have to check the whole input (when I do intersection) so I belive leads to o(2n), when i do union still o(n) to convert, but i belive is o(n) also get the 2 arrays combined and transform it in a set so probably o(n**2)
### Space Complexity:
<Big O notation with brief explanation>
o(n)<file_sep>/projeto_modulo2/explanation_1.md
### Design:
<details about implementation such as data structures and algorithms used>
for this problem I used a dicionary and a list. The idea was to create a list to keep track on the calls made on the items on my cache so I can easily delete the one tha was least used when needed because to search.
### Time Complexity:
<Big O notation with brief explanation>
I search only on the dicionary so is O(1) to find the data
### Space Complexity:
<Big O notation with brief explanation>
is constanst because the input size does not change the amout of space required on each execution.
O(1)<file_sep>/projeto_modulo3/problem_3.py
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
#quicksort inplace
quicksort(input_list)
num_1_str = ''
num_2_str = ''
max_index = 0
max_sum = 0
if len(input_list)<=1:
return input_list
for i in range(len(input_list)):
max_num = input_list.pop()
if i%2==0:
num_1_str+=str(max_num)
else:
num_2_str+=str(max_num)
return [int(num_1_str),int(num_2_str)]
#sorting:
def sort_a_little_bit(items, begin_index, end_index):
left_index = begin_index
pivot_index = end_index
pivot_value = items[pivot_index]
while (pivot_index != left_index):
item = items[left_index]
if item <= pivot_value:
left_index += 1
continue
items[left_index] = items[pivot_index - 1]
items[pivot_index - 1] = pivot_value
items[pivot_index] = item
pivot_index -= 1
return pivot_index
def sort_all(items, begin_index, end_index):
if end_index <= begin_index:
return
pivot_index = sort_a_little_bit(items, begin_index, end_index)
sort_all(items, begin_index, pivot_index - 1)
sort_all(items, pivot_index + 1, end_index)
def quicksort(items):
sort_all(items, 0, len(items) - 1)
def test_function(test_case):
output = rearrange_digits(test_case[0])
solution = test_case[1]
if sum(output) == sum(solution):
print("Pass")
else:
print("Fail")
#test_function([[1, 2, 3, 4, 5], [542, 31]])
test_case1 = [[4, 6, 2, 5, 9, 8], [964, 852]]
test_case2 = [[4, 0, 1, 5, 9, 8], [951, 840]]
test_case3 = [[4, 6, 2, 7, 0, 8], [862, 740]]
test_case4 = [[], []]
test_case5 = [[1, 2], [1, 2]]
test_case6 = [[0, 0], [0, 0]]
test_function(test_case1)
test_function(test_case2)
test_function(test_case3)
test_function(test_case4)
test_function(test_case5)
test_function(test_case6)<file_sep>/projeto_modulo1/submit/Task4.py
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
possible_mkt = []
# all calls made
for call in calls:
possible_mkt.append(call[0])
possible_mkt_set = set(possible_mkt)
# removing the ones who received calls
for call in calls:
if call[1] in possible_mkt_set:
possible_mkt_set.remove(str(call[1]))
# removing the ones who send txt and received
for msg in texts:
if msg[0] in possible_mkt_set:
possible_mkt_set.remove(str(msg[0]))
if msg[1] in possible_mkt_set:
possible_mkt_set.remove(str(msg[1]))
print("These numbers could be telemarketers: ")
# creating list to apply sort()
result_list = list(possible_mkt_set)
result_list.sort()
for number in result_list:
print(number)
# O(2N)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
<file_sep>/projeto_modulo3/explanation_3.md
### Design:
<details about implementation such as data structures and algorithms used>
For this problem my first step is to order the array using quicksort.
Then I use the array as an stack poping the numbers from higher to
lower and creating the number that would have the maximum sum.
### Time Complexity:
<Big O notation with brief explanation>
I belive is (n log n)
### Space Complexity:
<Big O notation with brief explanation>
I also belive here is (n log n)<file_sep>/exercicios_modulo1/teacher.py
names = input("Enter studant names separated by commas ex: Andre, juca , joao: \n") # get and process input for a list of names
assignments = input("Enter assignments counts for the studants separated by commas ex: 1, 7, 10: \n")# get and process input for a list of the number of assignments
grades = input("Enter Grades for the studants separated by commas ex: 7, 10,0: \n") # get and process input for a list of grades
# message string to be used for each student
# HINT: use .format() with this string in your for loop
message = "Hi {},\n\nThis is a reminder that you have {} assignments left to \
submit before you can graduate. You're current grade is {} and can increase \
to {} if you submit all assignments before the due date.\n\n"
print(names,assignments,grades)
list_names = list(names.split(","))
list_assigments = list(assignments.split(","))
list_grades = list(grades.split(","))
pot_grade=[]
#print(list_names,list_assigments,list_grades)
# write a for loop that iterates through each set of names, assignments, and grades to print each student's message
for index in range(len(list_names)):
#print(index)
pot_grade.append(int(list_grades[index])+int(list_assigments[index])*2)
print(message.format(list_names[index],list_assigments[index],list_grades[index],pot_grade[index]))
<file_sep>/projeto_modulo3/problem_1.py
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
# Base cases
if (number == 0 or number == 1):
return number
# Staring from 1, try all numbers until
# i*i is greater than or equal to x.
i = 1;
result = 1
while (result <= number):
i += 1
result = i * i
return i - 1
print ("Pass" if (3 == sqrt(9)) else "Fail")
print ("Pass" if (0 == sqrt(0)) else "Fail")
print ("Pass" if (4 == sqrt(16)) else "Fail")
print ("Pass" if (1 == sqrt(1)) else "Fail")
print ("Pass" if (5 == sqrt(27)) else "Fail")
<file_sep>/projeto_modulo2/problem_6/problem_6.py
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
cur_head = self.head
out_string = ""
while cur_head:
out_string += str(cur_head.value) + " -> "
cur_head = cur_head.next
return out_string
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def size(self):
size = 0
node = self.head
while node:
size += 1
node = node.next
return size
def ll_to_list(llist):
# O(n)
elements_list = []
current_element = llist.head
# getting values from
while current_element:
elements_list.append(current_element.value)
current_element = current_element.next
return elements_list
def union(llist_1, llist_2):
list_1 = ll_to_list(llist_1)
list_2 = ll_to_list(llist_2)
elements_list = list_1 + list_2
elements_set = set(elements_list)
return elements_set
def intersection(llist_1, llist_2):
list_1 = ll_to_list(llist_1)
list_2 = ll_to_list(llist_2)
list_3 = [value for value in list_1 if value in list_2]
return list_3
# Test case 1
linked_list_1 = LinkedList()
linked_list_2 = LinkedList()
element_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 21]
element_2 = [6, 32, 4, 9, 6, 1, 11, 21, 1]
for i in element_1:
linked_list_1.append(i)
for i in element_2:
linked_list_2.append(i)
print (union(linked_list_1, linked_list_2))
print (intersection(linked_list_1, linked_list_2))
# Test case 2
linked_list_3 = LinkedList()
linked_list_4 = LinkedList()
element_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 23]
element_2 = [1, 7, 8, 9, 11, 21, 1]
for i in element_1:
linked_list_3.append(i)
for i in element_2:
linked_list_4.append(i)
print (union(linked_list_3, linked_list_4))
print (intersection(linked_list_3, linked_list_4))
# Test case 3
linked_list_5 = LinkedList()
linked_list_6 = LinkedList()
element_a = []
element_b = [1]
for i in element_a:
linked_list_5.append(i)
for i in element_b:
linked_list_6.append(i)
print (union(linked_list_5, linked_list_6))
print (intersection(linked_list_5, linked_list_6))
# Test case 4
linked_list_7 = LinkedList()
linked_list_8 = LinkedList()
element_a = []
element_b = []
for i in element_a:
linked_list_7.append(i)
for i in element_b:
linked_list_8.append(i)
print (union(linked_list_7, linked_list_8))
print (intersection(linked_list_7, linked_list_8))<file_sep>/projeto_modulo3/problem_2.py
def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
return binary_search_rec(input_list, number, 0, len(input_list)-1)
def binary_search_rec(arr,number,start,end):
mid = start + (end-start)//2
if start >= end:
return -1
elif arr[mid] == number:
return mid
else:
left = binary_search_rec(arr, number, start, mid)
right = binary_search_rec(arr, number, mid+1, end)
if left > -1:
return left
elif right > -1:
return right
else:
return -1
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass")
else:
print("Fail")
#Test CASES
#1
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
#2
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
#3
test_function([[2, 3, 4, 5, 6, 7, 8, 1], 99])
test_function([[2, 3, 4, 5, 6, 7, 8, 1], 10])
#3
test_function([[], 1])
#test_function([[2, 3, 4, 5, 6, 7, 8, 1], 10])
<file_sep>/projeto_modulo1/submit/Task2.py
"""
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
max_time = 0
phone_num_max_time = ''
time_dic = {}
for call in calls:
if time_dic.get(call[0]):
time_dic[call[0]] += int(call[-1])
else:
time_dic[call[0]] = int(call[-1])
if time_dic.get(call[1]):
time_dic[call[1]] += int(call[-1])
else:
time_dic[call[1]] = int(call[-1])
for phone, time in time_dic.items():
if int(max_time) < int(time):
max_time = time
phone_num_max_time = phone
print(" {} spent the longest time, {} seconds, on the phone during September 2016.".format(phone_num_max_time, max_time ))
# O(N)
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
<file_sep>/projeto_modulo3/explanation_6.md
<details about implementation such as data structures and algorithms used>
for this problem i used the approach of a linear search where i
try to find the smallest and largest number
### Time Complexity:
<Big O notation with brief explanation>
o(n)
### Space Complexity:
<Big O notation with brief explanation>
o(1) is constant because i only used constant couple helper variables
and use them to compare there is no extra space being used.<file_sep>/projeto_modulo1/P0/Task1.py
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
telnumbers = []
for message in texts:
if message[0] not in telnumbers:
telnumbers.append(message[0])
if message[1] not in telnumbers:
telnumbers.append(message[1])
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
for call in calls:
if call[0] not in telnumbers:
telnumbers.append(call[0])
if call[1] not in telnumbers:
telnumbers.append(call[1])
#telnumbers is a list with all the unic phonenumbers(messages and phonecalls so i just count how many are in the list)
print("There are {} different telephone numbers in the records.".format(len(telnumbers)))
# O(2N)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
<file_sep>/projeto_modulo2/problem_3/explanation_3.md
### Design:
<details about implementation such as data structures and algorithms used>
For this problem i decided to use a heap to order and then do the huffman algorithm
### Time Complexity:
<Big O notation with brief explanation>
The time complexity of the Huffman algorithm is O(nlogn). Using a heap to store the weight of each tree, each iteration requires O(logn) time to determine the cheapest weight and insert the new weight. There are O(n) iterations, one for each item.
### Space Complexity:
<Big O notation with brief explanation>
I see the space complexity as O(N) because it depende a lot on the size of input and it can grow as much as the input grows.
https://www.geeksforgeeks.org/huffman-coding-greedy-algo-3/
https://people.ok.ubc.ca/ylucet/DS/Huffman.html
https://www.geeksforgeeks.org/min-heap-in-python/
https://www.geeksforgeeks.org/binary-heap/
https://www.youtube.com/watch?v=k72DtCnY4MU
https://www.youtube.com/watch?v=g9YK6sftDi0
<file_sep>/projeto_modulo3/explanation_5.md
### Design:
<details about implementation such as data structures and algorithms used>
I don't know if applies but I will explain anyway.
Basicly I follow the instructions and created a Trie class
adding what was requested.
### Time Complexity:
<Big O notation with brief explanation>
well I belive for the operations requested using a Trie would be
bacause in the worst case i would have to transverse the whole Trie to
add or to search so would be(where l is the length of the word and amout of words):
O(n * l)
### Space Complexity:
<Big O notation with brief explanation>
like i described above the space complexity would also be o(n*l)<file_sep>/Exercicios_modulo2/problem3.py
###
# Problem 3: Huffman Coding
###
import sys
# Constants for the Huffman Tree
LEFT_BIT = "0"
RIGHT_BIT = "1"
class MinHeap():
def __init__(self, capacity=10):
self.array = [None] * capacity
self.size = 0
def insert(self, value):
'''Inserts the provided value into the heap.'''
# If array is at capacity, expand it before inserting new value
if self.size == len(self.array):
new_array = [None] * (2 * len(self.array))
for i, elem in enumerate(self.array):
new_array[i] = elem
self.array = new_array
# Add element at the leftmost open space
index = self.size
self.array[index] = value
# Ensure the heap shape. If the inserted value is less than its predecessors, swap the values as needed.
while (index > 0):
parent_index = (index - 1) // 2
if self.array[index] < self.array[parent_index]:
# Swap the element and its parent
self.array[index], self.array[parent_index] = self.array[parent_index], self.array[index]
index = parent_index
else:
# Order is correct, so stop
break
self.size += 1
def get_min(self):
'''Returns the root (min) element of the heap without removing it.'''
return self.array[0]
def delete_min(self):
'''Removes the root (min) element of the heap.'''
if self.size == 0:
return
# Replace the root with the last element of the heap
self.size -= 1
self.array[0] = self.array[self.size]
self.array[self.size] = None
# Ensure the heap shape. If the root is greater than its successors, swap the values as needed.
self._min_heapify(0)
def pop_min(self):
'''Removes and returns the root (min) element of the heap.'''
min_elem = self.get_min()
self.delete_min()
return min_elem
def _min_heapify(self, index):
left = (2 * index) + 1
right = (2 * index) + 2
smallest = index
if left < self.size and self.array[left] < self.array[smallest]:
smallest = left
if right < self.size and self.array[right] < self.array[smallest]:
smallest = right
if smallest != index:
self.array[index], self.array[smallest] = self.array[smallest], self.array[index]
self._min_heapify(smallest)
class HuffmanNode():
def __init__(self, value = None, frequency = 0):
self.frequency = frequency
self.value = value
self.left = None
self.right = None
def __lt__(self, other):
return self.frequency < other.frequency
def __str__(self):
return f"['{self.value}':{self.frequency}]"
def build_huffman_tree(data):
"""
Build the Huffman tree for the provided data.
:param data: Data to encode.
:return: Root node of the Huffman tree.
"""
# Step 1 : Count the frequency of each character
frequency_table = {}
for ch in data:
frequency_table[ch] = frequency_table.get(ch, 0) + 1
# Step 2: Create "priority queue" (e.g. min-heap)
priority_queue = MinHeap()
for ch, frequency in frequency_table.items():
new_node = HuffmanNode(ch, frequency)
priority_queue.insert(new_node)
# Create the Huffman tree
while priority_queue.size > 1:
# Step 3: Pop-out the two nodes with the minimum frequency
node1 = priority_queue.pop_min()
node2 = priority_queue.pop_min()
# Step 4: Create new node by "combining" the two prior nodes, and insert it into the priority queue
new_node = HuffmanNode(None, (node1.frequency + node2.frequency))
new_node.left = node1
new_node.right = node2
priority_queue.insert(new_node)
# Return the only item in the priority queue.
# Note: Use "get_min" instead of "pop_min" to avoid heapifying unnecessarily.
return priority_queue.get_min()
def generate_code_table(table, node, code):
"""
Helper method to generate the table for the Huffman code by traversing the Huffman tree recursively.
:param table: Table with the Huffman code.
:param node: Starting node (of the Huffman tree) for traversing downward.
:param code: Partial Huffman code so far (from the root until the provided node).
:return: Table with the Huffman code.
"""
# If it is a leaf node, insert code into the table
if not node.left and not node.right:
table[node.value] = code
return table
# Traverse to its child nodes
if node.left:
generate_code_table(table, node.left, code + LEFT_BIT)
if node.right:
generate_code_table(table, node.right, code + RIGHT_BIT)
return table
def huffman_encoding(data):
"""
Encode the provided data using the Huffman Coding.
:param data: Data to encode.
:return: Encoded version of the provided data.
"""
# If data is empty, return it back
if data is None or len(data) == 0:
return data, None
### Phase 1: Build the Huffman Tree
tree = build_huffman_tree(data)
### Phase 2: Generate the encoded data ###
# Traverse tree to generate table
code_table = generate_code_table({}, tree, "")
# Encode the data
encoded_data = ""
for ch in data:
encoded_data += code_table[ch]
return encoded_data, tree
def huffman_decoding(encoded_data, tree):
"""
Decode the provided data using the provided Huffman tree.
:param encoded_data: Encoded data to be decoded with the provided Huffmann tree.
:param tree: Root of the Huffman tree used to encode the provided data.
:return: Decoded version of the provided data.
"""
if encoded_data is None:
return None
decoded_data = ""
node = tree # Start at the root of the tree
for bit in encoded_data:
if bit == LEFT_BIT:
node = node.left
elif bit == RIGHT_BIT:
node = node.right
# If node is a leaf node, append its character to the decoded string
if not node.left and not node.right:
decoded_data += node.value
node = tree # Go back to the root of the tree
return decoded_data
def test_huffman(sentence):
codes = {}
print (f"Size of the data: {sys.getsizeof(sentence)}")
print (f"Content of the data: '{sentence}'")
encoded_data, tree = huffman_encoding(sentence)
if encoded_data and len(encoded_data) > 0:
print (f"Size of the encoded data: {sys.getsizeof(int(encoded_data, base=2))}")
print (f"Content of the encoded data: '{encoded_data}'")
else:
print ("Data was not encoded")
decoded_data = huffman_decoding(encoded_data, tree)
print(f"Size of the decoded data: {sys.getsizeof(decoded_data)}")
print(f"Content of the encoded data: '{decoded_data}'")
print()
if __name__ == "__main__":
# Sample test case #1
test_huffman("AAAAAAABBBCCCCCCCDDEEEEEE")
# Expect: Data of size 74 is encoded to size 32.
# Sample test case #2
test_huffman("The bird is the word")
# Expect: Data of size 69 is encoded to size 36.
# Edge case: Empty string
test_huffman("")
# Expect: Empty string yields "Data was not encoded" and returns empty string.
# (Note: Empty strings seem to have size 49).
# Edge case: None
test_huffman(None)
# Expect: 'None' yields "Data was not encoded" and returns 'None'.
# (Note: None seems to have size 49).
# Test case: Longer sentence
test_huffman("In general, a data compression algorithm reduces the amount of memory (bits) required to represent a "
"message (data)")
# Expect: Data of size 164 is encoded to size 88.
# Test case: Paragraph #1
test_huffman("In general, a data compression algorithm reduces the amount of memory (bits) required to represent a "
"message (data). The compressed data, in turn, helps to reduce the transmission time from a sender to "
"receiver. The sender encodes the data, and the receiver decodes the encoded data. As part of this "
"problem, you have to implement the logic for both encoding and decoding.")
# Expect: Data of size 421 is encoded to size 232.
# Test case: Paragraph #2
test_huffman("Create a new node with a frequency equal to the sum of the two nodes picked in the above step. "
"This new node would become an internal node in the Huffman tree, and the two nodes would become the "
"children. The lower frequency node becomes a left child, and the higher frequency node becomes the "
"right child. Reinsert the newly created node back into the priority queue.")
# Expect: Data of size 417 is encoded to size 232.<file_sep>/projeto_modulo3/explanation_7.md
<details about implementation such as data structures and algorithms used>
Basicly the idea is very close to
how would work the autocomplete ou to find words and etc...
is just a different application using routes.
### Time Complexity:
<Big O notation with brief explanation>
o(N) because I have to "transverse" everytime to add or find,
for example the method lookup i have to walk the tree in order.
### Space Complexity:
<Big O notation with brief explanation>
o(n) as well because the handler method give a little more efficiency
when storing the paths that way saves some space.<file_sep>/projeto_modulo3/problem_4.py
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
zeros = []
twos=[]
ones=[]
for x in input_list:
if x == 0:
zeros.append(x)
elif x == 2:
twos.append(x)
else:
ones.append(x)
result = zeros+ones+twos
return result
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
#3 test Cases
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
test_function([])
test_function([0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2])
test_function([0, 0, 0, 0, 0, 0])<file_sep>/projeto_modulo3/explanation_4.md
### Design:
<details about implementation such as data structures and algorithms used>
I can always expect 0,1 or 2 in the array so I just need to know
who comes first and last. I used a for loop to transverse only one time,
make 3 lists and return them in order.
### Time Complexity:
<Big O notation with brief explanation>
O(n) because i transverse the input once.
### Space Complexity:
<Big O notation with brief explanation>
O(3*n) or O(n) because I have to create 3 small
arrays that together are the size of the original array<file_sep>/projeto_modulo4/student_code.py
from math import sqrt
from queue import PriorityQueue
def shortest_path(M, start, goal):
frontier_queue = PriorityQueue()
prev_link = {start: None}
G = {start: 0}
H = {}
for node, coord in M.intersections.items():
H[node] = calc_dist(M, node, goal)
frontier_queue.put(start, H[start])
while not frontier_queue.empty():
current_node = frontier_queue.get()
if current_node == goal:
reconstruct_path(prev_link, start, goal)
for neighbor in M.roads[current_node]:
g_tentative = G[current_node] + calc_dist(M, current_node, neighbor)
if neighbor not in G or g_tentative < G[neighbor]:
G[neighbor] = g_tentative
f = g_tentative + H[neighbor]
frontier_queue.put(neighbor, f)
prev_link[neighbor] = current_node
return reconstruct_path(prev_link, start, goal)
def calc_dist(M, node1, node2):
x1, y1 = tuple(M.intersections[node1])
x2, y2 = tuple(M.intersections[node2])
dist = sqrt((x1 - x2)**2 + (y1 - y2)**2)
return dist
def reconstruct_path(prev_link, start, goal):
curr = goal
path = [curr]
while curr != start:
curr = prev_link.get(curr, None)
if curr == None:
print("No path between start and goal")
return None
path.append(curr)
path.reverse()
return path<file_sep>/projeto_modulo3/explanation_1.md
### Design:
<details about implementation such as data structures and algorithms used>
Transverse only when is needed and is only one transversal
### Time Complexity:
<Big O notation with brief explanation>
o(log n)
### Space Complexity:
<Big O notation with brief explanation>
o(1) because the the adicional memory does not grow with the input size.<file_sep>/projeto_modulo2/problem_5/explanation_5.md
### Design:
<details about implementation such as data structures and algorithms used>
I used a linked list type of structure to create this, to add a block or get , first or last block is o(1) but to find a specific block would be o(n)
### Time Complexity:
<Big O notation with brief explanation>
To add a block or get , first or last block is o(1)
but to find a specific block would be o(n)
### Space Complexity:
<Big O notation with brief explanation>
o(n)<file_sep>/projeto_modulo2/problem_2/explanation_2.md
### Design:
<details about implementation such as data structures and algorithms used>
For this problem I used arrays to return the lists of paths. that way seems a little more organized.
### Time Complexity:
<Big O notation with brief explanation>
because I have to check for every single possibility do a for
and call a recusive function with a for inside i belive that is o(2**n)
### Space Complexity:
<Big O notation with brief explanation>
i belive that because of the amout of operations it takes and because i have to search for every possibility always incresing by 2 is o(2**n) just like the time complexity | d2fcb5de4f052b048bc132a7a1253282935157d9 | [
"Markdown",
"Python"
]
| 30 | Python | andreramosilva/udacity | 3237dee6f4783066c48edc50cd3f8189a09e8322 | 696f4c04a4e762035a157cde9e253b68a5dafb8f |
refs/heads/master | <repo_name>wdppt/util<file_sep>/vim/README.md
#Alias
alias vi='vim -u /home/vim/vimrc'
alias vim='vim -u /home/vim/vimrc'
#Install plugins
:PluginInstall
<file_sep>/expect.sh
#!/usr/bin/expect -f
user="user"
password="<PASSWORD>"
pub_url=""
set number [lindex $argv 0]
set address [lindex $argv 1]
if { $number == "" } {
puts "Usage: <number>\n"
exit 1
}
if { $number == "100" && $address == "" } {
puts "Usage: <address>\n"
exit 1
}
spawn ssh $user@$pub_url
expect {
"Are you sure you want to continue connecting*" {
send "yes\r"
exp_continue
}
}
expect "$user@$pub_url's password: "
send "$password"
expect "Choose a number : "
send "$number\r"
expect {
"Input IP Address : " {
send "$address\r"
exp_continue
} "Are you sure you want to continue connecting*" {
send "yes\r"
exp_continue
} "*password*" {
send "CU97h:EntaoeRc\r"
exp_continue
} "$user@*" {
send "echo hi\r"
}
}
interact
| f572e31bf35b9072a2463a75d67dc1e4dcfac558 | [
"Markdown",
"Shell"
]
| 2 | Markdown | wdppt/util | afcdd5df04ccdaedc5f6523abc3d39056efb4438 | da9b40167fdb9307744d662103162a72af2c71f9 |
refs/heads/master | <repo_name>SteveBirtles/gophers15<file_sep>/FunctionalUtils/Float.go
package FunctionalUtils
func MapFloat(f func(float64) float64, input []float64) (output []float64) {
output = make([]float64, 0)
for _, x := range input {
output = append(output, f(x))
}
return
}
func FilterFloat(f func(float64) bool, input []float64) (output []float64) {
output = make([]float64, 0)
for _, x := range input {
if f(x) {
output = append(output, x)
}
}
return
}
func ReduceFloat(f func(float64) float64, input []float64) (output float64) {
for _, x := range input {
output += f(x)
}
return
}<file_sep>/main.go
package main
import (
. "./FunctionalUtils"
"fmt"
)
func main() {
list := []int{81, 32, 53, 14, 75, 96, 37, 58, 29, 10}
//ascending := func(a, b int) bool { return a < b }
descending := func(a, b int) bool { return a > b }
sorted := SortInt(descending, list)
fmt.Println(list)
fmt.Println(sorted)
}<file_sep>/FunctionalUtils/Int.go
package FunctionalUtils
func MapInt(f func(int) int, input []int) (output []int) {
output = make([]int, 0)
for _, x := range input {
output = append(output, f(x))
}
return
}
func FilterInt(f func(int) bool, input []int) (output []int) {
output = make([]int, 0)
for _, x := range input {
if f(x) {
output = append(output, x)
}
}
return
}
func EveryInt(f func(int) bool, input []int) bool {
for _, x := range input {
if !f(x) { return false }
}
return true
}
func SomeInt(f func(int) bool, input []int) bool {
for _, x := range input {
if f(x) { return true }
}
return false
}
func RemoveInt(f func(int) bool, input []int) (output []int) {
output = make([]int, 0)
for _, x := range input {
if !f(x) {
output = append(output, x)
}
}
return
}
func PartitionInt(f func(int) bool, input []int) (yes, no []int) {
yes = make([]int, 0)
no = make([]int, 0)
for _, x := range input {
if f(x) {
yes = append(yes, x)
} else {
no = append(no, x)
}
}
return
}
func SortInt(f func(int, int) bool, input []int) (output []int) {
output = make([]int, len(input))
copy(output, input)
for i := 1; i < len(output); i++ {
key := output[i]
j := i - 1
for j >= 0 && f(key, output[j]) {
output[j+1] = output[j]
j = j - 1
}
output[j+1] = key
}
return
}
func ReduceInt(f func(int) int, input []int) (output int) {
for _, x := range input {
output += f(x)
}
return
}
<file_sep>/FunctionalUtils/String.go
package FunctionalUtils
func MapString(f func(string) string, input []string) (output []string) {
output = make([]string, 0)
for _, x := range input {
output = append(output, f(x))
}
return
}
func FilterString(f func(string) bool, input []string) (output []string) {
output = make([]string, 0)
for _, x := range input {
if f(x) {
output = append(output, x)
}
}
return
}
func ReduceString(f func(string) string, input []string) (output string) {
for _, x := range input {
output += f(x)
}
return
} | 18b043ace1419ee95bac475ac0b60671f80f918c | [
"Go"
]
| 4 | Go | SteveBirtles/gophers15 | 589044483d76b1092482f30b3c704de6ff06d7a7 | e74e2a2fcfd2f179a09b94c24bbf19ded369060c |
refs/heads/main | <file_sep>from tkinter import *
import tkinter.messagebox as tkMessageBox
import sqlite3
root = Tk()
root.title("Rostrum")
width = 640
height = 520
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)
def Database():
global conn, cursor
conn = sqlite3.connect("db_member.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT, password TEXT, firstname TEXT, lastname TEXT)")
USERNAME = StringVar()
PASSWORD = StringVar()
FIRSTNAME = StringVar()
LASTNAME = StringVar()
def LoginForm():
global LoginFrame, lbl_result1
LoginFrame = Frame(root)
LoginFrame.pack(side=TOP, pady=80)
Upper_right = Label(LoginFrame,text ='Rostrum Login Page',font=('arial', 20))
Upper_right.place(y=0,x=210)
lbl_username = Label(LoginFrame, text="Username:", font=('arial', 25), bd=18)
lbl_username.grid(row=2)
lbl_password = Label(LoginFrame, text="Password:", font=('arial', 25), bd=18)
lbl_password.grid(row=3)
lbl_result1 = Label(LoginFrame, text="", font=('arial', 18))
lbl_result1.grid(row=4, columnspan=2)
lbl = Label(LoginFrame, text="", font=('arial', 18))
lbl.grid(row=0, column=3)
username = Entry(LoginFrame, font=('arial', 20), textvariable=USERNAME, width=15)
username.grid(row=2, column=1)
password = Entry(LoginFrame, font=('arial', 20), textvariable=PASSWORD, width=15, show="*")
password.grid(row=3, column=1)
btn_login = Button(LoginFrame, text="Login", font=('arial', 18), width=35, command=Login)
btn_login.grid(row=5, columnspan=2, pady=20)
lbl_register = Label(LoginFrame, text="New to Rostrum? Click Here to Create New Account", fg="Blue", font=('arial', 12))
lbl_register.grid(row=6, sticky=W)
lbl_register.bind('<Button-1>', ToggleToRegister)
USERNAME.set("")
PASSWORD.set("")
############################################################################################################## Upload Page
Liturature = StringVar()
def Database2():
global conn2, cursor2, Liturature, UName
conn = sqlite3.connect("db_member.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS `feed2` (mem_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT, Liturature TEXT, likes INTRGER)")
def Upload(Lit):
Database2()
if UName.get() == "":
lbl_result3.config(text="Name is Empty!!! ", fg="orange")
else:
cursor.execute("INSERT INTO `feed2` (username, Liturature, likes) VALUES(?, ?, 0)", (str(UName.get()), str(Lit)))
conn.commit()
lbl_result3.config(text="Liturature Successfully Uploaded!", fg="black")
UName= StringVar()
def UploadPage():
Database2()
global UploadFrame, lbl_result3, USERNAME, Liturature,content,UName
UploadFrame = Frame(root)
UploadFrame.pack(side=TOP, pady=20)
Upper_right = Label(UploadFrame,text ='Rostrum Upload Page',font=('arial', 20))
Upper_right.grid(row=0, column=0)
Uname= Entry(UploadFrame,textvariable=UName ,font=('arial', 15) , width=25)
Uname.grid(row=0, column=1)
lbl_content = Label(UploadFrame, text="Literature:", font=('arial', 25), bd=18)
lbl_content.grid(row=1, column=0)
lbl_result3 = Label(UploadFrame, text="", font=('arial', 18))
lbl_result3.grid(row=2, columnspan=2)
content = Text(UploadFrame, font=('arial', 15),height=12 , width=25)
content.grid(row=1, column=1)
btn_upload = Button(UploadFrame, text="Upload", font=('arial', 18), width=15, command=lambda :Upload(content.get("1.0",END)))
btn_upload.grid(row=3,column=0)
btn_view = Button(UploadFrame, text="Open Feed Page", font=('arial', 18), width=15, command=ToggleToView)
btn_view.grid(row=3,column=1)
lbl_Logout = Button(UploadFrame, text="Log Out", fg="Blue", font=('arial', 12),command=ToggleToLogout)
lbl_Logout.grid(row=6, sticky=W)
def ToggleToLogout(event=None):
cursor.close()
conn.close()
UploadFrame.destroy()
LoginForm()
def ToggleToUpload(event=None):
LoginFrame.destroy()
UploadPage()
################################################################################################################## View Page
Liturature = StringVar()
i=-1
def View():
global i,val
i=-1
cursor.execute("Select Liturature,username,likes,mem_id from `feed2` order by mem_id DESC" )
val=cursor.fetchall()
conn.commit()
Next()
def Like():
global lbl_like,btn_like
lbl_like['text']='Likes: ' + str(int(val[i][2]+1))
cursor.execute("Update `feed2` set likes=likes+1 where mem_id=(?)",(str(val[i][3])))
conn.commit()
btn_like['state']=DISABLED
return 0
def Next():
global i,val,lbl_like,btn_like
i=i+1
if(len(val)<=i):
result2 = tkMessageBox.showinfo('Information', 'No More Lituratures are available')
else:
cont.config(text=val[i][0],fg='black')
uname.config(text=val[i][1],fg='black')
lbl_like.config(text='Likes: '+str(val[i][2]),fg='black')
btn_like['state']=NORMAL
def ViewPage():
global ViewFrame, feed, USERNAME, Liturature, cont,uname,lbl_like,btn_like
ViewFrame = Frame(root)
ViewFrame.pack(side=TOP, pady=20)
Upper_right = Label(ViewFrame,text ='Rostrum View Page',font=('arial', 20))
Upper_right.grid(row=0, column=0)
uname= Label(ViewFrame,text="", width=10)
uname.grid(row=0,column=1)
cont= Label(ViewFrame,text="", font=('arial', 15),wraplength=250,height=12 , width=25)
cont.grid(row=1,column=0)
btn_Next = Button(ViewFrame, text="Next Feed", font=('arial', 18), width=15, command=Next)
btn_Next.grid(row=2, column=0)
lbl_like = Label(ViewFrame,text="Likes : 0",font=('arial', 18),width=15)
lbl_like.grid(row=1,column=1)
btn_like = Button(ViewFrame,text="Like Feed ", font=('arial', 18), width=15, command=Like)
btn_like.grid(row=2, column=1)
lbl_Logout = Button(ViewFrame, text="Log Out", fg="Blue", font=('arial', 12),command=ToggleToLogout2)
lbl_Logout.grid(row=3, column=0)
lbl_upload = Button(ViewFrame, text="Open Upload page", fg="Blue", font=('arial', 12),command=ToggleToUpload2)
lbl_upload.grid(row=3, column=1)
View()
def ToggleToLogout2(event=None):
cursor.close()
conn.close()
ViewFrame.destroy()
LoginForm()
def ToggleToView(event=None):
UploadFrame.destroy()
ViewPage()
def ToggleToUpload2(event=None):
#cursor.close()
#conn.close()
ViewFrame.destroy()
UploadPage()
#################################################################################################################
def RegisterForm():
global RegisterFrame, lbl_result2
RegisterFrame = Frame(root)
RegisterFrame.pack(side=TOP, pady=40)
Upper_right = Label(RegisterFrame,text ='Rostrum Account Creation Page',font=('arial', 20))
Upper_right.place(y=0,x=80)
lbl_username = Label(RegisterFrame, text="Username:", font=('arial', 18), bd=18)
lbl_username.grid(row=1)
lbl_password = Label(RegisterFrame, text="Password:", font=('arial', 18), bd=18)
lbl_password.grid(row=2)
lbl_firstname = Label(RegisterFrame, text="Firstname:", font=('arial', 18), bd=18)
lbl_firstname.grid(row=3)
lbl_lastname = Label(RegisterFrame, text="Lastname:", font=('arial', 18), bd=18)
lbl_lastname.grid(row=4)
lbl_result2 = Label(RegisterFrame, text="", font=('arial', 18))
lbl_result2.grid(row=5, columnspan=2)
lbl = Label(RegisterFrame, text="", font=('arial', 18))
lbl.grid(row=0, column=3)
username = Entry(RegisterFrame, font=('arial', 20), textvariable=USERNAME, width=15)
username.grid(row=1, column=1)
password = Entry(RegisterFrame, font=('arial', 20), textvariable=PASSWORD, width=15, show="*")
password.grid(row=2, column=1)
firstname = Entry(RegisterFrame, font=('arial', 20), textvariable=FIRSTNAME, width=15)
firstname.grid(row=3, column=1)
lastname = Entry(RegisterFrame, font=('arial', 20), textvariable=LASTNAME, width=15)
lastname.grid(row=4, column=1)
btn_login = Button(RegisterFrame, text="Register", font=('arial', 18), width=35, command=Register)
btn_login.grid(row=6, columnspan=2, pady=20)
lbl_login = Label(RegisterFrame, text="Already Have an Account? Click here to Login", fg="Blue", font=('arial', 12))
lbl_login.grid(row=7, sticky=W)
lbl_login.bind('<Button-1>', ToggleToLogin)
def Exit():
result = tkMessageBox.askquestion('System', 'Are you sure you want to exit?', icon="warning")
if result == 'yes':
root.destroy()
exit()
def ToggleToLogin(event=None):
RegisterFrame.destroy()
LoginForm()
def ToggleToRegister(event=None):
LoginFrame.destroy()
RegisterForm()
def Register():
Database()
if USERNAME.get() == "" or PASSWORD.get() == "" or FIRSTNAME.get() == "" or LASTNAME.get() == "":
lbl_result2.config(text="Please complete the required field!", fg="orange")
else:
cursor.execute("SELECT * FROM `member` WHERE `username` = ?", (USERNAME.get(),))
if cursor.fetchone() is not None:
lbl_result2.config(text="Username is already taken", fg="red")
else:
cursor.execute("INSERT INTO `member` (username, password, firstname, lastname) VALUES(?, ?, ?, ?)", (str(USERNAME.get()), str(PASSWORD.get()), str(FIRSTNAME.get()), str(LASTNAME.get())))
conn.commit()
USERNAME.set("")
PASSWORD.set("")
FIRSTNAME.set("")
LASTNAME.set("")
lbl_result2.config(text="Successfully Created!", fg="black")
#cursor.close()
#conn.close()
def Login():
Database()
if USERNAME.get == "" or PASSWORD.get() == "":
lbl_result1.config(text="Please complete the required field!", fg="orange")
else:
cursor.execute("SELECT * FROM `member` WHERE `username` = ? and `password` = ?", (USERNAME.get(), PASSWORD.get()))
if cursor.fetchone() is not None:
lbl_result1.config(text="You Successfully Login", fg="blue")
ToggleToUpload()
else:
lbl_result1.config(text="Invalid Username or password", fg="red")
LoginForm()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=Exit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
if __name__ == '__main__':
root.mainloop()
<file_sep>This is a TkInter Python based Application for local literature Sharing
GUI-Tkinter
Database-SQLite
| d626cfe2c5390f157adb87fca0b1de654868fceb | [
"Markdown",
"Python"
]
| 2 | Python | Nama-Venkata-Vishwak/Rostrum-LearningHub | 73595053ccee044cbabb57f69c472dbaf2b94705 | 00337f362a90e3b3f113341e0aafbcc60684fe96 |
refs/heads/master | <repo_name>designrubenz/tic-tac-toe-rb-002<file_sep>/bin/tictactoe
#!/usr/bin/env ruby
board = Array.new(9, " ")
require_relative '../lib/welcome'
require_relative '../lib/tic_tac_toe'
play(board)
<file_sep>/lib/tic_tac_toe.rb
WIN_COMBINATIONS = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[6,4,2]
]
def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def move(board, position, char)
board[position.to_i-1] = char
end
def position_taken?(board, position)
board[position.to_i].strip != ""
end
def valid_move?(board, position)
return false if position.to_i.to_s != position.to_s
!(position_taken?(board, position.to_i-1))
end
def turn(board)
begin
print "\nPlayer #{current_player(board)}, please enter position 1-9: "
position = gets.chomp.to_i
puts
end until position && position > 0 && position <10
move(board, position, current_player(board)) if valid_move?(board, position)
# require 'pry'c;binding.pry
end
def turn_count(board)
board.select{|b| b.strip!=""}.size
end
def current_player(board)
turn_count(board)%2 == 0 ? "X":"O"
end
def won?(board)
WIN_COMBINATIONS.each do |wc|
x_winner = wc.select{|wc| board[wc].strip == "X"}
o_winner = wc.select{|wc| board[wc].strip == "O"}
return x_winner if x_winner == wc
return o_winner if o_winner == wc
end
false
end
def full?(board)
board.select{|b| b.strip !=""}.size == 9
end
def draw?(board)
full?(board) && won?(board)==false
end
def over?(board)
draw?(board) || won?(board)
end
def winner(board)
return board[won?(board)[0]] if won?(board)
end
def play(board)
while !(over?(board))
display_board(board)
turn(board)
end
display_board(board)
puts
puts won?(board) ? "Congratulations #{winner(board)}!" : "Cats Game!"
# puts "Congratulations #{winner(board)}!" if won?(board)
end
| e556dfb5b87a1646cda00b9e29b3b1f82df0627c | [
"Ruby"
]
| 2 | Ruby | designrubenz/tic-tac-toe-rb-002 | 714a192e58a783dc094d8b1d9ead80294ef2a226 | 51007c418f94cd42e4a30f53f41f31645088c243 |
refs/heads/master | <repo_name>buchuitoudegou/CG-HW8<file_sep>/src/create_window/CreateWindow.cpp
#include "CreateWindow.hpp"
void CreateWindow::framebufferSizeCallback(GLFWwindow* window, int width, int height) {
glViewport(0, 0, width, height);
}
void CreateWindow::processInput(GLFWwindow* window) {
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
}
}
GLFWwindow* CreateWindow::createWindow() {
// init glfw
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
// load window
if (window == NULL) {
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return NULL;
}
glfwMakeContextCurrent(window);
// load GLAD
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout << "Failed to initialize GLAD" << std::endl;
return NULL;
}
// window size change
glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);
return window;
}<file_sep>/src/create_window/CreateWindow.hpp
#ifndef CREATE_WINDOW_HPP
#define CREATE_WINDOW_HPP
#include "../headers.h";
namespace CreateWindow {
#define SCR_WIDTH 800
#define SCR_HEIGHT 800
void framebufferSizeCallback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow* window);
GLFWwindow* createWindow();
}
#endif
<file_sep>/src/headers.h
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
<file_sep>/README.md
# CG-HW8
implementation of drawing a bezier curve
## run
`make & make run`
## dependencies
- glfw
- glad<file_sep>/makefile
src = src
bin = bin
build = build
CFLAGS = -std=c++11 -g -w
objects := $(build)/glad.o $(build)/main.o $(build)/create_window.o\
$(build)/shader.o
target := $(bin)/main
$(target) : $(objects)
g++ $(objects) -o $@ -lglfw -lm $(CFLAGS)
# glad
$(build)/glad.o : $(src)/glad.c
g++ $< -o $@ $(CFLAGS) -c
# main
$(build)/main.o : $(src)/main.cpp
g++ $< -o $@ $(CFLAGS) -c
# create_window
$(build)/create_window.o : $(src)/create_window/CreateWindow.cpp $(src)/create_window/CreateWindow.hpp
g++ $< -o $@ $(CFLAGS) -c
# shader
$(build)/shader.o : $(src)/shader.cpp $(src)/shader.h
g++ $< -o $@ $(CFLAGS) -c
clean:
@rm -rf bin/
@rm -rf build/
mkdir build/
mkdir bin/
run:
bin/main<file_sep>/src/main.cpp
#include "headers.h"
#include "create_window/CreateWindow.hpp"
#include <vector>
#include <utility>
#include <cmath>
#include "shader.h"
#include <iostream>
using namespace std;
vector<pair<float, float> > ctrlPoints;
double dynamicT = 0;
// float lastFrame = 0, curFrame = 0;
// bool finish = true;
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods);
vector<pair<float, float> > bezier(vector<pair<float, float> >& points);
double bernstein(int i, int n, double t);
int factorial(int num);
void drawCurve(Shader* shader, vector<pair<float, float> >& points);
void drawLine(Shader*, pair<float, float>&, pair<float, float>&);
void drawDynamicProcedure(Shader*);
int main() {
GLFWwindow* window = CreateWindow::createWindow();
glfwSetMouseButtonCallback(window, mouse_button_callback);
Shader shader("./src/glsl/shader.vs", "./src/glsl/shader.fs");
while (!glfwWindowShouldClose(window)) {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
if (ctrlPoints.size() > 2) {
for (int i = 0; i < ctrlPoints.size() - 1; ++i) {
drawLine(&shader, ctrlPoints[i], ctrlPoints[i + 1]);
}
auto bezierPoints = bezier(ctrlPoints);
drawCurve(&shader, bezierPoints);
drawDynamicProcedure(&shader);
}
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
}
vector<pair<float, float> > bezier(vector<pair<float, float> >& points) {
vector<pair<float, float>> resultPoints;
int n = points.size() - 1;
for (double t = 0; t <= 1; t += 0.00005) {
pair<float, float> targetPoint;
for (int i = 0; i <= n; i++) {
double B = bernstein(i, n, t);
pair<float, float> curPoint = points[i];
targetPoint.first += curPoint.first * B;
targetPoint.second += curPoint.second * B;
}
resultPoints.push_back(targetPoint);
}
return resultPoints;
}
double bernstein(int i, int n, double t) {
double B = factorial(n) / (factorial(i) * factorial(n - i));
B = B * pow(t, i) * pow((1 - t), (n - i));
return B;
}
int factorial(int num) {
int ans = 1;
for (int i = 1; i <= num; i++)
ans *= i;
return ans;
}
void drawLine(Shader* shader, pair<float, float>& p1, pair<float, float>& p2) {
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
float vertices[6] = {
p1.first, p1.second, 0.0f,
p2.first, p2.second, 0.0f
};
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STREAM_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
shader->use();
shader->setVec4("drawColor", glm::vec4(1, 0, 0, 1));
glDrawArrays(GL_LINE_STRIP, 0, 2);
glBindVertexArray(0);
glDeleteBuffers(1, &VBO);
glDeleteVertexArrays(1, &VAO);
}
void drawCurve(Shader* shader, vector<pair<float, float> >& points) {
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
vector<float> vertices;
for (int i = 0; i < points.size(); ++i) {
vertices.push_back(points[i].first);
vertices.push_back(points[i].second);
vertices.push_back(0.0f);
}
float* glVertices = new float[vertices.size()];
for (int i = 0; i < vertices.size(); ++i) {
glVertices[i] = vertices[i];
}
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, points.size() * 3 * sizeof(float), glVertices, GL_STREAM_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
shader->use();
shader->setVec4("drawColor", glm::vec4(1, 0, 0, 1));
glDrawArrays(GL_POINTS, 0, points.size());
glBindVertexArray(0);
delete[] glVertices;
glDeleteBuffers(1, &VBO);
glDeleteVertexArrays(1, &VAO);
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) {
ctrlPoints.pop_back();
dynamicT = 0;
// finish = false;
}
else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
double tempX = 0, tempY = 0;
glfwGetCursorPos(window, &tempX, &tempY);
tempX = (-1) + (tempX / SCR_WIDTH) * 2;
tempY = (-1)*((-1) + (tempY / SCR_HEIGHT) * 2);
pair<float, float> p;
p.first = tempX;
p.second = tempY;
ctrlPoints.push_back(p);
dynamicT = 0;
// finish = false;
}
}
void drawDynamicProcedure(Shader* shader) {
const double t = dynamicT;
vector<pair<float, float> > prePoints(ctrlPoints);
while (prePoints.size() != 0) {
vector<pair<float, float> > tmp(prePoints);
prePoints.clear();
for (int j = 0; j < tmp.size() - 1; ++j) {
pair<float, float> p;
auto fir = tmp[j];
auto sec = tmp[j + 1];
p.first = t * sec.first + (1 - t) * fir.first;
p.second = t * sec.second + (1 - t) * fir.second;
prePoints.push_back(p);
}
for (int j = 0; prePoints.size() >= 1 && j < prePoints.size() - 1; j++) {
drawLine(shader, prePoints[j], prePoints[j + 1]);
}
}
if (dynamicT + 0.005 > 1) {
dynamicT = 1;
}
else {
dynamicT += 0.005;
// cout << dynamicT << endl;
}
// if (dynamicT == 1 && !finish) {
// curFrame = glfwGetTime();
// cout << "--------------" << curFrame - lastFrame << "--------------" << endl;
// lastFrame = curFrame;
// finish = true;
// } else if (dynamicT == 1) {
// curFrame = glfwGetTime();
// lastFrame = curFrame;
// }
}<file_sep>/doc/report.md
# 计算机图形学第八次作业
```
姓名:刘俊峰
学号:16340150
```
## 要求
### Basic:
1. 用户能通过左键点击添加Bezier曲线的控制点,右键点击则对当前添加的最后一个控制点进行消除
2. 工具根据鼠标绘制的控制点实时更新Bezier曲线。
Hint: 大家可查询捕捉mouse移动和点击的函数方法
### Bonus:
1. 可以动态地呈现Bezier曲线的生成过程。
## 实验步骤
### 实现bezier曲线算法
```cpp
vector<pair<float, float>> resultPoints;
int n = points.size() - 1;
for (double t = 0; t <= 1; t += 0.00005) {
pair<float, float> targetPoint;
for (int i = 0; i <= n; i++) {
double B = bernstein(i, n, t);
pair<float, float> curPoint = points[i];
targetPoint.first += curPoint.first * B;
targetPoint.second += curPoint.second * B;
}
resultPoints.push_back(targetPoint);
}
return resultPoints;
```
这里步长为0.0005,动态计算出bezier曲线的每个点的坐标,根据这些坐标,我们就可以用gl_points图元将他们画出。
### 鼠标点击事件
```cpp
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) {
...
}
else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
double tempX = 0, tempY = 0;
glfwGetCursorPos(window, &tempX, &tempY);
...
```
这里用到的是glfw的鼠标左右键按压事件,并用glfwGetCursorPos找到鼠标的位置。
### Bonus: 动态呈现bezier曲线绘制过程
利用插值的方法,递归画出不同层的折线段。
```cpp
const double t = dynamicT;
vector<pair<float, float> > prePoints(ctrlPoints);
while (prePoints.size() != 0) {
vector<pair<float, float> > tmp(prePoints);
prePoints.clear();
for (int j = 0; j < tmp.size() - 1; ++j) {
pair<float, float> p;
auto fir = tmp[j];
auto sec = tmp[j + 1];
p.first = t * sec.first + (1 - t) * fir.first;
p.second = t * sec.second + (1 - t) * fir.second;
prePoints.push_back(p);
}
for (int j = 0; prePoints.size() >= 1 && j < prePoints.size() - 1; j++) {
drawLine(shader, prePoints[j], prePoints[j + 1]);
}
}
if (dynamicT + 0.005 > 1) {
dynamicT = 1;
}
else {
dynamicT += 0.005;
// cout << dynamicT << endl;
}
```
最内层循环就是核心的插值算法,找出它内层线段的端点位置,并画出来。直到无法找到两个端点为止。
## 实验截图

 | 8ce53375b869d0d38cd93b321a8e80d343f31da3 | [
"Markdown",
"Makefile",
"C++"
]
| 7 | C++ | buchuitoudegou/CG-HW8 | 7b9ebb29f7f3f972d26d6197b368158961eec3b6 | ca67cf1060f0fd7fd07f9101a3bdab5358bf81f7 |
refs/heads/master | <repo_name>anwei881110/DAOProject<file_sep>/src/com/superstar/service/junit/IEmpServiceTest.java
package com.superstar.service.junit;
import static org.junit.Assert.*;
import java.awt.List;
import java.sql.SQLClientInfoException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import junit.framework.TestCase;
import org.junit.Test;
import com.superstar.factory.DAOFactory;
import com.superstar.factory.ServiceFactory;
import com.superstar.vo.Emp;
public class IEmpServiceTest {
private static int empno;
static{
empno= new Random().nextInt(1000);//动态生成empno数据
}
@Test
public void testInsert() {
Emp vo=new Emp();
vo.setEmpno(empno);
vo.setEname("程"+empno) ;
vo.setJob("摄"+empno);
vo.setHiredate(new Date());
vo.setSal(110.0);
vo.setComm(5.0);
try {
TestCase.assertTrue(ServiceFactory.getIEmpServiceInstance().insert(vo));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testUpdate() {
Emp vo=new Emp();
vo.setEmpno(1111);
vo.setEname("程"+empno) ;
vo.setJob("摄"+empno);
vo.setHiredate(new Date());
vo.setSal(110.0);
vo.setComm(5.0);
try {
TestCase.assertTrue(ServiceFactory.getIEmpServiceInstance().update(vo));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGet() {
try {
TestCase.assertNotNull(ServiceFactory.getIEmpServiceInstance().get(7369));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testDelete() {
Set<Integer> idSet=new HashSet<Integer>();
idSet.add(1111);
try {
TestCase.assertTrue(ServiceFactory.getIEmpServiceInstance().delete(idSet));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testList() {
try {
TestCase.assertNotNull(ServiceFactory.getIEmpServiceInstance().list());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testListIntIntStringString() {
try {
Map<String, Object> map=ServiceFactory.getIEmpServiceInstance().list(2,5, "job", "");
int count =(Integer) map.get("empCount");
java.util.List<Emp> all=(java.util.List<Emp>)map.get("allEmps");
TestCase.assertTrue(count>0||all.size()>0);
// System.out.println(count);
// System.out.println(all.get(1).getEname());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/src/com/superstar/dao/IDeptDAO.java
/**
*
*/
package com.superstar.dao;
import java.util.List;
import java.util.Set;
import com.superstar.vo.Dept;
/**
* @作者:Administrator
* @创建日期:2017-4-5
*/
public interface IDeptDAO extends IDAO<Integer,Dept> {
/*
//采用统一的借口继承模式来写
public boolean doCreate(Dept vo) throws Exception;
public boolean doUpdate(Dept vo) throws Exception;
public boolean doRemoveBatch(Set<Integer> ids) throws Exception;
public Dept findById(Integer id) throws Exception;
public List<Dept> findAll() throws Exception;
*/
}
<file_sep>/src/com/superstar/vo/Emp.java
/**
*
*/
package com.superstar.vo;
import java.io.Serializable;
import java.util.Date;
import com.superstar.dbc.DatebaseConnection;
/**
* @作者:Administrator
* @创建日期:2017-3-29
*/
public class Emp implements Serializable {
private Integer empno;
private String ename;
private String job;
private Date hiredate;
private Double sal;
private Double comm;
/**
* @return the empno
*/
public Integer getEmpno() {
return empno;
}
/**
* @param empno the empno to set
*/
public void setEmpno(Integer empno) {
this.empno = empno;
}
/**
* @return the ename
*/
public String getEname() {
return ename;
}
/**
* @param ename the ename to set
*/
public void setEname(String ename) {
this.ename = ename;
}
/**
* @return the job
*/
public String getJob() {
return job;
}
/**
* @param job the job to set
*/
public void setJob(String job) {
this.job = job;
}
/**
* @return the hiredate
*/
public Date getHiredate() {
return hiredate;
}
/**
* @param hiredate the hiredate to set
*/
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
/**
* @return the sal
*/
public Double getSal() {
return sal;
}
/**
* @param sal the sal to set
*/
public void setSal(Double sal) {
this.sal = sal;
}
/**
* @return the comm
*/
public Double getComm() {
return comm;
}
/**
* @param comm the comm to set
*/
public void setComm(Double comm) {
this.comm = comm;
}
}
<file_sep>/src/com/superstar/dao/IEmpDAO.java
/**
*
*/
package com.superstar.dao;
import java.util.List;
import java.util.Set;
import com.superstar.vo.Emp;
/**
* @作者:Administrator
* @创建日期:2017-3-29
*/
public interface IEmpDAO {
/**
* 实现数据库增加操作
* @param vo 包含了要增加数据库的vo对象
* @return 数据保存成功返回true,否则则返回false
* @throws Exception SQL执行异常
*/
public boolean doCreat(Emp vo) throws Exception;
/**
* 实现数据库修改操作,本次修改是根据id进行全部字段数据的修改
* @param vo 包含了本次要修改数据的信息,一定要提供ID内容<br>
* @return 数据修改成功返回true,否则则返回false
* @throws Exception SQL执行异常
*/
public boolean doUpdate(Emp vo) throws Exception;
/**
* 执行数据的批量操作,所有要删除的数据以set集合的形式保存
* @param ids 包含了所有要删除的数据ID,不包含有重复内容
* @return 删除成功返回true(删除的数据个数与要删除的数据个数相同),否则<br>
* 返回false。
* @throws Exception SQL执行异常
*/
public boolean doRemoveBatch(Set<Integer> ids) throws Exception;
/**
* 通过ID查找制定的雇员信息
* @param id 要查找的雇员编号
* @return 如果雇员信息存在,则以vo对象返回查到的雇员信息,否则则返回null
* @throws Exception SQL执行异常
*/
public Emp findById(Integer id) throws Exception;
/**
* 查询指定数据表全部记录,并且以集合的形式返回
* @return 如果表中有数据,则所有的数据会封装为VO对象而后面利用List集合返回,<br>
* 如果没有数据,那么集合的长度为0(size()==0,不是null)
* @throws Exception SQL执行异常
*/
public List<Emp> findAll() throws Exception; //这里版本问题还是什么原因 修订有错误!! List<Emp> 不正确
/**
* 分页进行数据的模糊查询,查询结果以集合的形式返回
* @param currentPage 当前所在页数
* @param linsize 每页显示数据行数
* @param column 要进行模糊查询的数据列
* @param KeyWord 模糊查询的关键字
* @return 如果查询到数据,则所有的数据会封装在VO对象而后利用List集合返回,<br>
* 如果没有数据,那么集合的长度为0(size()==0,不是null)
* @throws Exception SQL执行异常
*/
public List<Emp> findEsAllSpilt(Integer currentPage,Integer linsize, String column,String KeyWord) throws Exception;
/**
* 进行模糊查询的数据统计
* @param column 要进行模糊查询的列名称
* @param keyWord 模糊查询的关键字
* @return 返回查询统计数量,如果没有数据则返回0
* @throws Exception SQL执行异常
*/
public Integer getAllCount(String column,String keyWord) throws Exception;
}<file_sep>/src/com/superstar/vo/Dept.java
/**
*
*/
package com.superstar.vo;
import java.io.Serializable;
/**
* @作者:Administrator
* @创建日期:2017-4-5
*/
public class Dept implements Serializable {
private Integer deptno;
private String dname;
/**
* @return the deptno
*/
public Integer getDeptno() {
return deptno;
}
/**
* @param deptno the deptno to set
*/
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
/**
* @return the dname
*/
public String getDname() {
return dname;
}
/**
* @param dname the dname to set
*/
public void setDname(String dname) {
this.dname = dname;
}
/**
* @return the loc
*/
public String getLoc() {
return loc;
}
/**
* @param loc the loc to set
*/
public void setLoc(String loc) {
this.loc = loc;
}
private String loc;
}
<file_sep>/src/com/superstar/dao/IDAO.java
/**
*
*/
package com.superstar.dao;
import java.util.List;
import java.util.Set;
/**
* 定义公共查询DAO操作借口标准,基本功能包括:<br>
* 增加、修改、删除、查询、查询全部、数据统计、分页显示等操作
* @作者:Administrator
* @创建日期:2017-4-5
* @param <K> 表示要操作的主键类型,由子接口实现
* @param <V>表示要操作的VO类型,由子接口实现
*/
public interface IDAO<K,V> {
/**
* 实现数据的增加操作
* @param vo 包含要增加数据的VO对象
* @return 数据保存成功则返回true,否则返回false
* @throws Exception SQL执行异常
*/
public boolean doCreate(V vo) throws Exception;
/**
* 实现数据的修改操作,本次修改是根据id进行全部字段数据的修改
* @param vo 包含了要修改数据的信息,一定要提供有ID内容
* @return 数据修改成功返回true,否则返回false
* @throws Exception SQL执行异常
*/
public boolean doUpdate(V vo) throws Exception;
/**
* 执行数据的批量删除操作,所有要删除的数据以set集合形式保存
* @param ids 包含了所有要删除的数据ID,不包含有重复内容
* @return 删除成功返回true(删除的数据个数与要删除的数据个数相同),否则发挥false
* @throws Exception SQL执行异常
*/
public boolean doRemoveBatch(Set<K> ids) throws Exception;
/**
* 根据雇员编号查询雇员信息
* @param id 要查询雇员的id
* @return 如果雇员信息存在,则数据将以VO类对象的形式返回,如果雇员数据不存在,<br>
* 则返回false
* @throws Exception SQL执行异常
*/
public V findById(K id) throws Exception;
/**
* 查询指定数据表全部记录,并且以集合的形式返回
* @return 如果表中有数据,则所有的数据会封装为VO对象而后面利用List集合返回,<br>
* 如果没有数据,那么集合的长度为0(size()==0,不是null)
* @throws Exception SQL执行异常
*/
public List<V> findAll() throws Exception;
/**
* 分页进行数据的模糊查询,查询结果以集合的形式返回
* @param currentPage 当前所在页数
* @param linsize 每页显示数据行数
* @param column 要进行模糊查询的数据列
* @param KeyWord 模糊查询的关键字
* @return 如果查询到数据,则所有的数据会封装在VO对象而后利用List集合返回,<br>
* 如果没有数据,那么集合的长度为0(size()==0,不是null)
* @throws Exception SQL执行异常
*/
public List<V> findAllSplit(Integer currentPage,Integer linesize, String column, String KeyWord) throws Exception;
/**
* 进行模糊查询的数据统计
* @param column 要进行模糊查询的列名称
* @param keyWord 模糊查询的关键字
* @return 返回查询统计数量,如果没有数据则返回0
* @throws Exception SQL执行异常
*/
public Integer getAllCount(String column,String KeyWord) throws Exception;
}
| 972ec072a05beda165bc974c205602f697b89942 | [
"Java"
]
| 6 | Java | anwei881110/DAOProject | 15570785caf804a380d3f4acaf2e2bc491ab8813 | 1aabc3f82406371f1947e04f5edc453ceeade2e1 |
refs/heads/master | <repo_name>piero2908/AVR-TIMER1<file_sep>/main.c
/*
* Uso_timer1.c
*
* Created: 04/10/2018 08:18:57 a.m.
* Author : Laptop
*/ //Aprendiendo a utilizar el TMR1 del ATMEGA328P
#define F_CPU 2000000 //Crystal 16 Mhz, Div_by_8 -> 2Mhz
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
volatile uint8_t tmr1_overflow_count = 0;
ISR(TIMER1_OVF_vect){
tmr1_overflow_count++;
if(tmr1_overflow_count >= 61){ //Blinking led de 2 seg
PORTD ^= 0xFF;
tmr1_overflow_count = 0;
}
}
void tmr1_config(){
TCCR1B |= (1<<CS10)|(0<<CS11)|(0<<CS12); //Prescaler = 1;
TIMSK1 |= (1<<TOIE1);
//TIFR1 |= (X<<TOV1); ->Flag
sei();
TCNT1 = 0x0000;
}
void pin_config(){
DDRD = (0xFF<<DDRD);
}
int main(void)
{
pin_config();
tmr1_config();
while (1)
{
}
}
| 430d47ab42b9058ece51d180598b06b3a84156b3 | [
"C"
]
| 1 | C | piero2908/AVR-TIMER1 | 8770f14888ffdc2388977639e4b0519b154ba26e | 96cbae0c47235c7f12f5412c59ec65b53b9c0c32 |
refs/heads/master | <file_sep>package mdns-pub
import (
"github.com/davecheney/mdns"
"flag"
"log"
"fmt"
"net"
)
func mustPublish(rr string) {
if err := mdns.Publish(rr); err != nil {
log.Fatal(`Unable to publish record "%s": %v`, rr, err)
}
}
func usage() {
log.Fatal("Usage: mdns-pub [-t] <address> <name> [service] [port]")
flag.PrintDefaults()
os.Exit(2)
}
var expiry int
func init() {
flag.IntVar( &expiry, "e", 60, "Set the record timeout in seconds"
}
func reverseaddr(addr string) (arpa string, err error) {
ip := net.ParseIP(addr)
if ip == nil {
return "", "unrecognized address"
}
if ip.To4() != nil {
return itoa(int(ip[15])) + "." + itoa(int(ip[14])) + "." + itoa(int(ip[13])) + "." +
itoa(int(ip[12])) + ".in-addr.arpa.", nil
}
// Must be IPv6
buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
// Add it, in reverse, to the buffer
for i := len(ip) - 1; i >= 0; i-- {
v := ip[i]
buf = append(buf, hexDigit[v&0xF])
buf = append(buf, '.')
buf = append(buf, hexDigit[v>>4])
buf = append(buf, '.')
}
// Append "ip6.arpa." and return (buf already has the final .)
buf = append(buf, "ip6.arpa."...)
return string(buf), nil
}
func main() {
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) < 2 {
fmt.Println("Must specify at least Adress and Name")
usage()
os.Exit(1)
}
if len(args) == 3 {
fmt.Println("Must provide a port for service registry")
usage()
os.Exit
}
address, name := args[0], args[1]
if ! net.ParseIP(address) {
fmt.Println("Adress is not invalid: ", address)
}
mustPublish(name + ". " + timeout + " IN A " + address)
mustPublish(reverseaddr(address) + " " + timeout + " IN PTR " + name + ".")
/* A simple example. Publish an A record for my router at 192.168.1.254.
mustPublish("router.local. 60 IN A 192.168.1.254")
mustPublish("254.1.168.192.in-addr.arpa. 60 IN PTR router.local.")
// A more compilcated example. Publish a SVR record for ssh running on port
// 22 for my home NAS.
// Publish an A record as before
mustPublish("stora.local. 60 IN A 192.168.1.200")
mustPublish("192.168.3.11.in-addr.arpa. 60 IN PTR stora.local.")
// Publish a PTR record for the _ssh._tcp DNS-SD type
mustPublish("_ssh._tcp.local. 60 IN PTR stora._ssh._tcp.local.")
// Publish a SRV record tying the _ssh._tcp record to an A record and a port.
mustPublish("stora._ssh._tcp.local. 60 IN SRV 0 0 22 stora.local.")
// Most mDNS browsing tools expect a TXT record for the service even if there
// are not records defined by RFC 2782.
mustPublish(`stora._ssh._tcp.local. 60 IN TXT ""`)
// Bind this service into the list of registered services for dns-sd.
mustPublish("_service._dns-sd._udp.local. 60 IN PTR _ssh._tcp.local.")
*/
select {}
}
| 07d1906686bbd0e8be23e4a40d8a9aa6be068be9 | [
"Go"
]
| 1 | Go | spheromak/mdns-announce | f3b4be557ef6bff4272d779af6e662b856480301 | 916cf984fad6735de944b5ee7bb7086061876cd0 |
refs/heads/master | <file_sep>package udemy.model;
import java.awt.List;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class DBManager {
private static final String DB_URL = "jdbc:mysql://localhost:3306/udemy";
private static final String USER_NAME = "udemyUser";
private static final String PASSWORD = "123";
private static Connection connection;
public static Connection getConnection() {
if (connection == null) {
try {
connection = DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
} catch (SQLException e) {
System.out.println("Failed to connect todatabase");
e.printStackTrace();
}
}
return connection;
}
public static User loginUser(String inputUserName, String inputPassword) {
String query = "select * from users where user_name = ? and password = ?";
PreparedStatement preparedStatement = null;
try {
preparedStatement = getConnection().prepareStatement(query);
preparedStatement.setString(1, inputUserName);
preparedStatement.setString(2, inputPassword);
User user = null;
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
long id = result.getLong("id");
String userName = result.getString("user_name");
String password = result.getString("password");
String firstName = result.getString("first_name");
String lastName = result.getString("last_name");
int gender = result.getInt("gender");
int type = result.getInt("type");
user = new User(id, userName, password, firstName, lastName, gender, type);
}
return user;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static boolean addUser(String userName, String password, String firstName, String lastName,
int gender, int type) {
boolean successFlag = false;
String query = "insert into users(user_name, password, first_name, last_name, gender, type)"
+ "values(?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = null;
try {
preparedStatement = getConnection().prepareStatement(query);
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
preparedStatement.setString(3, firstName);
preparedStatement.setString(4, lastName);
preparedStatement.setInt(5, gender);
preparedStatement.setInt(6, type);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected == 0) {
successFlag = false;
} else {
successFlag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return successFlag;
}
public static long getUserId(String userName) {
long id = -1;
String query = "select id from users where user_name = ?";
PreparedStatement preparedStatement = null;
try {
preparedStatement = getConnection().prepareStatement(query);
preparedStatement.setString(1, userName);
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
id = result.getLong("id");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return id;
}
public static long getUserCourseId(long userId, long courseId) {
long id = -1;
String query = "select id from users_courses where user_id = ? and course_id = ?";
PreparedStatement preparedStatement = null;
try {
preparedStatement = getConnection().prepareStatement(query);
preparedStatement.setLong(1, userId);
preparedStatement.setLong(2, courseId);
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
id = result.getLong("id");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return id;
}
public static ArrayList<Course> getAllCourses() {
ArrayList<Course> courses = new ArrayList<Course>();
String query = "select id, name, instructor_id from courses";
Statement statement = null;
try {
statement = getConnection().createStatement();
ResultSet result = statement.executeQuery(query);
while (result.next()) {
Course course = new Course(result.getLong("id"), result.getString("name"),
result.getLong("instructor_id"));
courses.add(course);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return courses;
}
public static ArrayList<Category> getAllCategories() {
ArrayList<Category> categories = new ArrayList<Category>();
String query = "select id, name from categories";
Statement statement = null;
try {
statement = getConnection().createStatement();
ResultSet result = statement.executeQuery(query);
while (result.next()) {
Category category = new Category(result.getLong("id"), result.getString("name"));
categories.add(category);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return categories;
}
public static boolean addCourse(String courseName, long categoryId, long instructorId) {
boolean successFlag = false;
String query = "insert into courses(name, category_id, instructor_id)"
+ "values(?, ?, ?)";
PreparedStatement preparedStatement = null;
try {
preparedStatement = getConnection().prepareStatement(query);
preparedStatement.setString(1, courseName);
preparedStatement.setLong(2, categoryId);
preparedStatement.setLong(3, instructorId);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected == 0) {
successFlag = false;
} else {
successFlag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return successFlag;
}
public static long getCourseId(String courseName, long categoryId) {
long id = -1;
String query = "select id from courses where name = ? and category_id = ?";
PreparedStatement preparedStatement = null;
try {
preparedStatement = getConnection().prepareStatement(query);
preparedStatement.setString(1, courseName);
preparedStatement.setLong(2, categoryId);
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
id = result.getLong("id");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return id;
}
public static boolean enrollNewCourse(long userId, long courseId) {
boolean successFlag = false;
String query = "insert into users_courses(user_id, course_id)"
+ "values(?, ?)";
PreparedStatement preparedStatement = null;
try {
preparedStatement = getConnection().prepareStatement(query);
preparedStatement.setLong(1, userId);
preparedStatement.setLong(2, courseId);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected == 0) {
successFlag = false;
} else {
successFlag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return successFlag;
}
public static ArrayList<Course> getEnrolledCoursesByUserId(Long userId) {
ArrayList<Course> courses = new ArrayList<Course>();
String query = "select c.id, c.name, c.instructor_id, u.user_name\n" +
"FROM users_courses uc, courses c, users u\n" +
"where uc.user_id = ?\n" +
"and uc.course_id = c.id\n" +
"and c.instructor_id = u.id";
PreparedStatement preparedStatement = null;
try {
preparedStatement = getConnection().prepareStatement(query);
preparedStatement.setLong(1, userId);
ResultSet result = preparedStatement.executeQuery();
while (result.next()) {
//public Course(long id, String name, long instructorId, String instructorName
Course course = new Course(result.getLong("id"), result.getString("name"),
result.getLong("instructor_id"), result.getString("user_name"));
courses.add(course);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return courses;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package udemy.view;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import udemy.controller.BusinessException;
import udemy.controller.Service;
import udemy.model.UsersTypesEnum;
import udemy.model.genderEnum;
/**
*
* @author Tarek
*/
public class Register extends javax.swing.JFrame {
/**
* Creates new form Register
*/
public Register() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
genderRadioGroup = new javax.swing.ButtonGroup();
accountTypeRadioGroup = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
userNameLabel = new javax.swing.JLabel();
userNameTextField = new javax.swing.JTextField();
passwordTextField = new javax.swing.JTextField();
repeatPasswordTextField = new javax.swing.JTextField();
firstNameTextField = new javax.swing.JTextField();
repeatPasswordLabel = new javax.swing.JLabel();
firstNameLabel = new javax.swing.JLabel();
passwordLabel = new javax.swing.JLabel();
lastNameLabel = new javax.swing.JLabel();
lastNameTextField = new javax.swing.JTextField();
maleRadioButton = new javax.swing.JRadioButton();
femaleRadioButton = new javax.swing.JRadioButton();
genderLabel = new javax.swing.JLabel();
accountTypeLabel = new javax.swing.JLabel();
studentRadioButton = new javax.swing.JRadioButton();
teacherRadioButton = new javax.swing.JRadioButton();
submitButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("jLabel1");
userNameLabel.setText("UserName:");
userNameTextField.setColumns(15);
passwordTextField.setColumns(15);
repeatPasswordTextField.setColumns(15);
firstNameTextField.setColumns(15);
firstNameTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
firstNameTextFieldActionPerformed(evt);
}
});
repeatPasswordLabel.setText("Repeat password");
firstNameLabel.setText("First Name:");
passwordLabel.setText("Password:");
lastNameLabel.setText("Last Name:");
lastNameTextField.setColumns(15);
genderRadioGroup.add(maleRadioButton);
maleRadioButton.setSelected(true);
maleRadioButton.setText("male");
genderRadioGroup.add(femaleRadioButton);
femaleRadioButton.setText("female");
genderLabel.setText("Gender:");
accountTypeLabel.setText("Account Type:");
accountTypeRadioGroup.add(studentRadioButton);
studentRadioButton.setSelected(true);
studentRadioButton.setText("Student");
accountTypeRadioGroup.add(teacherRadioButton);
teacherRadioButton.setText("Teacher");
submitButton.setText("Sumbit");
submitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(167, 167, 167)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(repeatPasswordLabel)
.addComponent(passwordLabel)
.addComponent(userNameLabel)
.addComponent(firstNameLabel)
.addComponent(lastNameLabel)
.addComponent(genderLabel)
.addComponent(accountTypeLabel))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(userNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(repeatPasswordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(firstNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lastNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(maleRadioButton)
.addComponent(studentRadioButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(teacherRadioButton)
.addComponent(femaleRadioButton)))))
.addGroup(layout.createSequentialGroup()
.addGap(82, 82, 82)
.addComponent(submitButton)))
.addContainerGap(64, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(userNameLabel)
.addComponent(userNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(passwordLabel)
.addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(repeatPasswordLabel)
.addComponent(repeatPasswordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(firstNameLabel)
.addComponent(firstNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lastNameLabel)
.addComponent(lastNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(genderLabel)
.addComponent(maleRadioButton)
.addComponent(femaleRadioButton))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(accountTypeLabel)
.addComponent(studentRadioButton)
.addComponent(teacherRadioButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
.addComponent(submitButton)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void firstNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_firstNameTextFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_firstNameTextFieldActionPerformed
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitButtonActionPerformed
int gender = (maleRadioButton.isSelected())? genderEnum.MALE.getCode() : genderEnum.FEMALE.getCode();
int accountType = (studentRadioButton.isSelected())? UsersTypesEnum.STUDENT.getCode() : UsersTypesEnum.TEACHER.getCode();
try {
Service.addNewUser(userNameTextField.getText(), passwordTextField.getText(), repeatPasswordTextField.getText(),
firstNameTextField.getText(), lastNameTextField.getText(),gender , accountType);
JOptionPane.showMessageDialog(this, "You have successfully registered");
Login login = new Login();
login.setVisible(true);
this.setVisible(false);
} catch (BusinessException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}//GEN-LAST:event_submitButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Register().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel accountTypeLabel;
private javax.swing.ButtonGroup accountTypeRadioGroup;
private javax.swing.JRadioButton femaleRadioButton;
private javax.swing.JLabel firstNameLabel;
private javax.swing.JTextField firstNameTextField;
private javax.swing.JLabel genderLabel;
private javax.swing.ButtonGroup genderRadioGroup;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel lastNameLabel;
private javax.swing.JTextField lastNameTextField;
private javax.swing.JRadioButton maleRadioButton;
private javax.swing.JLabel passwordLabel;
private javax.swing.JTextField passwordTextField;
private javax.swing.JLabel repeatPasswordLabel;
private javax.swing.JTextField repeatPasswordTextField;
private javax.swing.JRadioButton studentRadioButton;
private javax.swing.JButton submitButton;
private javax.swing.JRadioButton teacherRadioButton;
private javax.swing.JLabel userNameLabel;
private javax.swing.JTextField userNameTextField;
// End of variables declaration//GEN-END:variables
}
<file_sep>use udemy;
# table users
insert into users(user_name, password, first_name, last_name, gender, type)
values('Ahmed', 'a123', 'Ahmed', 'Ali', 0, 0);
insert into users(user_name, password, first_name, last_name, gender, type)
values('Mona', 'm123', 'Mona', 'Mohamed', 1, 0);
insert into users(user_name, password, first_name, last_name, gender, type)
values('Sherif', 's123', 'Sherif', 'Shady', 0, 0);
insert into users(user_name, password, first_name, last_name, gender, type)
values('Basma', '<PASSWORD>', 'Basma', 'Bendary', 1, 0);
insert into users(user_name, password, first_name, last_name, gender, type)
values('Hassan', 'h123', 'Hassan', 'Haytham', 0 , 1);
insert into users(user_name, password, first_name, last_name, gender, type)
values('Radwa', '<PASSWORD>', 'Radwa', 'Ramy', 1, 1);
#table categories
insert into categories(name)
values('Programming');
insert into categories(name)
values('Web Development');
insert into categories(name)
values('Mobile applications');
insert into categories(name)
values('Data mining');
#table courses
insert into courses(name, category_id, instructor_id)
values('Java', 1, 6);
insert into courses(name, category_id, instructor_id)
values('Android', 3, 6);
insert into courses(name, category_id, instructor_id)
values('Introduction to data mining', 4, 5);
#table users_courses
insert into users_courses(user_id, course_id)
values(1, 1);
insert into users_courses(user_id, course_id)
values(1,2);
insert into users_courses(user_id, course_id)
values(1,3);
insert into users_courses(user_id, course_id)
values(2,1);
insert into users_courses(user_id, course_id)
values(2,2);
insert into users_courses(user_id, course_id)
values(3,1);<file_sep>package udemy.controller;
import javax.swing.JComboBox;
import udemy.model.CategoriesComboBoxModel;
import udemy.model.Category;
import udemy.view.Login;
public class Main {
public static void main(String[] args) throws BusinessException{
JComboBox<Category>categorisComboBox = new JComboBox<Category>();
categorisComboBox.setModel(new CategoriesComboBoxModel(Service.getAllCategories()));
new Login().setVisible(true);
}
}
<file_sep>create user 'udemyUser'@'localhost' identified by '123';
grant all privileges on *.* to 'udemyUser'@'localhost';
create database udemy;
use udemy;
create table users(
id int(10) primary key auto_increment,
user_name varchar(10) unique not null,
password varchar(20) not null,
first_name varchar(10) not null,
last_name varchar(10) not null,
gender tinyint(1) not null,
type tinyint(1) not null -- 0 for student, 1 for teacher
);
create table categories(
id int(10) primary key auto_increment,
name varchar(100) not null
);
create table courses(
id int(10) primary key auto_increment,
name varchar(100) not null,
category_id int(10) not null,
instructor_id int(10) not null,
foreign key (category_id) references categories(id),
foreign key (instructor_id) references users(id)
);
create table users_courses(
id int(10) primary key auto_increment,
user_id int(10) not null,
course_id int(10) not null,
foreign key (user_id) references users(id),
foreign key (course_id) references courses(id)
);<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package udemy.model;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
/**
*
* @author Tarek
*/
public class CoursesComboBoxModel extends DefaultComboBoxModel<Course>{
ArrayList<Course> items;
public CoursesComboBoxModel(ArrayList<Course> items){
this.items = items;
setSelectedItem(items.get(0));
}
@Override
public Course getElementAt(int index) {
return items.get(index);
}
@Override
public int getSize() {
return items.size();
}
}
| 4c871c255312f4ec73ed547bc9f26a84dee02064 | [
"Java",
"SQL"
]
| 6 | Java | TarekGamal/udemy-project | 4efdc5bc80cbfac68843689316328bb03c5f0a36 | 63f1634171a108d0e08dd72e921ea5892322dbd9 |
refs/heads/master | <repo_name>CymbalFM/GreenPlace<file_sep>/background.js
chrome.extension.getBackgroundPage().console.log('foo');
chrome.extension.onRequest.addListener(function(request) {
chrome.extension.getBackgroundPage().console.log('foo');
});<file_sep>/parse.js
;(function(console) {
// We don't want this script operating on our own page
// otherwise actually choosing a provider will result
// in an infinite loop of replacement
if (window.location.href.indexOf('://cymbal.fm') !== -1) {
return;
}
const body = document.querySelector('body');
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
parse();
}
});
});
setTimeout(() => {
observer.observe(body, { childList: true, subtree: true })
}, 1500)
function linkSoundCloud(uri) {
return fetch(uri).then((r) => {
return r.text()
}).then((html) => {
const regex = /\"publisher_metadata":\{\"id\"\:(\d+)/ig
const match = regex.exec(html);
if (!match) {
return Promise.reject('Bad link');
} else {
return match[1];
}
})
}
function rejectFalsy(val) {
if (val) {
return Promise.resolve(val);
} else {
return Promise.reject('No val found');
}
}
function getSpotifyId(uri) {
const uri1 = decodeURIComponent(uri).split(':track:')[1];
const uri2 = decodeURIComponent(uri).split('/embed/track/')[1]
return rejectFalsy(uri1 || uri2);
}
function getSpotifyAlbumId(uri) {
const uri1 = decodeURIComponent(uri).split(':album:')[1];
const uri2 = decodeURIComponent(uri).split('/embed/album/')[1]
return rejectFalsy(uri1 || uri2);
}
function getAppleId(uri) {
return rejectFalsy(decodeURIComponent(uri).split('?')[0].split('/song/')[1]);
}
function getAppleAlbumId(uri) {
return rejectFalsy(decodeURIComponent(uri).split('?')[0].split('/album/')[1]);
}
function getEmbedURL(id) {
return `https://cymbal.fm/up/${id}`
};
function getAlbumEmbedURL(id) {
return `http://trinity.cymbal.fm/ua/${id}`
};
function parse() {
const frames = document.querySelectorAll('iframe');
frames.forEach((f) => {
const frameSrc = f.src.replace('http://', '').replace('https://', '');
let trackid;
let song;
if (frameSrc.indexOf('spotify:track') !== -1 || frameSrc.indexOf('/embed/track/') !== -1) {
getSpotifyId(frameSrc).then((id) => {
trackid = id;
return fetch(`https://api.cymbal.fm/api/v1/songs/sources?source=spotify&source_ids[]=${id}`)
.then((r) => {
return r.json();
}).then((j) => {
song = j[trackid];
f.src = getEmbedURL(song.id);
f.style.height = '';
f.height = 178;
});
})
} else if (frameSrc.indexOf('spotify:album') !== -1) {
getSpotifyAlbumId(frameSrc).then((id) => {
return fetch(`https://api.cymbal.fm/api/v1/albums?source=spotify&source_id=${id}`)
.then((r) => {
return r.json();
}).then((album) => {
f.src = getAlbumEmbedURL(album.id);
f.style.height = '';
f.height = 415;
});
})
} else if (frameSrc.indexOf('tools.applemusic.com') !== -1) {
if (frameSrc.indexOf('/album/') !== -1) {
getAppleAlbumId(frameSrc).then((id) => {
return fetch(`https://api.cymbal.fm/api/v1/albums?source=apple&source_id=${id}`)
.then((r) => {
return r.json();
}).then((album) => {
f.src = getAlbumEmbedURL(album.id);
f.style.height = '';
f.height = 415;
});
});
} else if (frameSrc.indexOf('/song/') !== -1) {
getAppleId(frameSrc).then((id) => {
trackid = id;
return fetch(`https://api.cymbal.fm/api/v1/songs/sources?source=apple&source_ids[]=${id}`)
.then((r) => {
return r.json();
}).then((j) => {
song = j[trackid];
f.src = getEmbedURL(song.id);
f.style.height = '';
f.height = 178;
});
});
}
}
})
}
parse();
})(window.console); | d21866698f11435b567377dc539e3ef49c5d1160 | [
"JavaScript"
]
| 2 | JavaScript | CymbalFM/GreenPlace | d62b15ac8e1a74b6a9815c8c69ba77cce51f8f41 | 982296f42bd5154cce3ac3ec21be0c7ddd7cbd0a |
refs/heads/master | <repo_name>ATechnoHazard/mess-attendance<file_sep>/app/src/main/java/org/firehound/messattendance/fragments/OwnerDetailsFragment.kt
package org.firehound.messattendance.fragments
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import kotlinx.android.synthetic.main.fragment_details.*
import kotlinx.android.synthetic.main.fragment_owner_details.*
import kotlinx.android.synthetic.main.fragment_owner_details.view.*
import org.firehound.messattendance.R
import org.firehound.messattendance.utils.toast
/**
* A simple [Fragment] subclass.
*/
class OwnerDetailsFragment : Fragment(), AdapterView.OnItemSelectedListener {
var mess = ""
private val messList = arrayListOf("Select your mess", "Darling Mess", "PR Mess", "SKC Mess", "Food Park", "Foodcy")
override fun onNothingSelected(p0: AdapterView<*>?) {
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, id: Long) {
mess = messList[position]
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_owner_details, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val arrayAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, messList)
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
ownerMessSpinner.adapter = arrayAdapter
ownerMessSpinner.onItemSelectedListener = this
ownerDetailsSubmitButton.setOnClickListener {
if (mess == "" || mess == messList[0]) {
Toast.makeText(context!!, "Select your mess!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
if (view.passwordTIL.editText?.text.toString() != "password") {
requireContext().toast("Incorrect password!")
return@setOnClickListener
}
val sharedPref = activity!!.getSharedPreferences(DetailsFragment.prefId, Context.MODE_PRIVATE)
with(sharedPref.edit()) {
putString("OWNER_MESS", mess)
commit()
}
activity!!.supportFragmentManager.beginTransaction()
.replace(R.id.frag_container, OwnerFragment()).disallowAddToBackStack().commit()
}
}
}
<file_sep>/app/src/main/java/org/firehound/messattendance/models/Student.kt
package org.firehound.messattendance.models
class Student {
var regNo: String? = null
var meal = mutableMapOf("breakfast" to false, "lunch" to false, "dinner" to false)
constructor(regNo: String) {
this.regNo = regNo
}
constructor() {}
}
<file_sep>/app/src/main/java/org/firehound/messattendance/activities/SelectionActivity.kt
package org.firehound.messattendance.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_student_selection.*
import org.firehound.messattendance.R
import org.firehound.messattendance.fragments.DetailsFragment
import org.firehound.messattendance.fragments.OwnerDetailsFragment
import org.firehound.messattendance.fragments.OwnerFragment
import org.firehound.messattendance.fragments.StudentFragment
class SelectionActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_student_selection)
setSupportActionBar(toolbar2)
val isStudent = intent.getBooleanExtra("isStudent", true)
if (isStudent) {
toolbar2.title = "Student options"
supportFragmentManager.beginTransaction().replace(R.id.frag_container, DetailsFragment()).commit()
} else {
toolbar2.title = "Owner options"
supportFragmentManager.beginTransaction().replace(R.id.frag_container, OwnerDetailsFragment()).commit()
}
}
}
<file_sep>/app/src/main/java/org/firehound/messattendance/models/DateEntry.kt
package org.firehound.messattendance.models
import java.util.*
class DateEntry {
var date: String? = null
var students: ArrayList<Student>? = null
constructor(date: String, students: ArrayList<Student>) {
this.date = date
this.students = students
}
constructor() {}
}<file_sep>/app/src/main/java/org/firehound/messattendance/activities/MainActivity.kt
package org.firehound.messattendance.activities
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import org.firehound.messattendance.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
toolbar.title = "Mess Attendance"
studentButton.setOnClickListener {
val intent = Intent(this, SelectionActivity::class.java)
intent.putExtra("isStudent", true)
startActivity(intent)
}
ownerButton.setOnClickListener {
val intent = Intent(this, SelectionActivity::class.java)
intent.putExtra("isStudent", false)
startActivity(intent)
}
}
}
<file_sep>/app/src/main/java/org/firehound/messattendance/fragments/DetailsFragment.kt
package org.firehound.messattendance.fragments
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import kotlinx.android.synthetic.main.fragment_details.*
import kotlinx.android.synthetic.main.fragment_details.view.*
import org.firehound.messattendance.R
import org.firehound.messattendance.utils.toast
class DetailsFragment : Fragment(), AdapterView.OnItemSelectedListener {
companion object {
val prefId = "com.firehound.messattendance.PREFS"
}
var mess = ""
private val messList = arrayListOf("Select your mess", "Darling Mess", "PR Mess", "SKC Mess", "Food Park", "Foodcy")
override fun onNothingSelected(p0: AdapterView<*>?) {
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, id: Long) {
mess = messList[position]
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_details, container, false)
}
@SuppressLint("DefaultLocale")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val arrayAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, messList)
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
messSpinner.adapter = arrayAdapter
messSpinner.onItemSelectedListener = this
detailsSubmitButton.setOnClickListener {
val regNo = regNoEditText.text
if (mess == "" || mess == messList[0]) {
Toast.makeText(context!!, "Select your mess!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
if (view.passwordTIL.editText?.text.toString().toLowerCase() != regNo.toString().toLowerCase()) {
requireContext().toast("Incorrect password!")
return@setOnClickListener
}
val sharedPref = activity!!.getSharedPreferences(prefId, Context.MODE_PRIVATE)
with(sharedPref.edit()) {
putString("REG_NO", regNo.toString())
putString("MESS", mess)
commit()
}
activity!!.supportFragmentManager.beginTransaction()
.replace(R.id.frag_container, StudentFragment()).disallowAddToBackStack().commit()
}
}
}
<file_sep>/app/src/main/java/org/firehound/messattendance/models/Meal.kt
package org.firehound.messattendance.models
class Meal {
var mealName: String? = null
var willAttend: Boolean = false
constructor() {}
constructor(mealName: String, willAttend: Boolean) {
this.mealName = mealName
this.willAttend = willAttend
}
}
<file_sep>/app/src/main/java/org/firehound/messattendance/models/MessEntry.kt
package org.firehound.messattendance.models
import java.util.ArrayList
class MessEntry {
var messName: String? = null
var date: ArrayList<DateEntry>? = null
constructor(messName: String, date: ArrayList<DateEntry>) {
this.messName = messName
this.date = date
}
constructor() {}
}
<file_sep>/app/src/main/java/org/firehound/messattendance/models/RetrofitInstance.kt
package org.firehound.messattendance.models
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
object RetrofitFactory {
private const val BASE_URL = "https://json-csv.com/api"
fun makeRetrofitService(): RetrofitService {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create())
.build().create(RetrofitService::class.java)
}
}<file_sep>/settings.gradle
include ':app'
rootProject.name='Mess Attendance'
<file_sep>/app/src/main/java/org/firehound/messattendance/models/RetrofitService.kt
package org.firehound.messattendance.models
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.POST
interface RetrofitService {
@POST("/getcsv")
suspend fun getCsv(@Body body: ArrayList<MessEntry>): Response<String>
}<file_sep>/app/src/main/java/org/firehound/messattendance/fragments/OwnerFragment.kt
package org.firehound.messattendance.fragments
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.fragment_owner.*
import org.firehound.messattendance.R
import org.firehound.messattendance.adapters.StudentListAdapter
import org.firehound.messattendance.models.MessEntry
import org.firehound.messattendance.models.Student
import org.firehound.messattendance.utils.toast
import java.text.SimpleDateFormat
import java.util.*
class OwnerFragment : Fragment() {
private val entries = mutableListOf<String>()
private var studentList = mutableListOf<Student>()
private lateinit var adapter: StudentListAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_owner, container, false)
}
@RequiresApi(Build.VERSION_CODES.N)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val db = FirebaseFirestore.getInstance()
super.onViewCreated(view, savedInstanceState)
val prefs = activity!!.getSharedPreferences(DetailsFragment.prefId, Context.MODE_PRIVATE)
val mess = prefs.getString("OWNER_MESS", "NOT_FOUND")
adapter = StudentListAdapter(studentList)
displayStudents.adapter = adapter
displayStudents.layoutManager = LinearLayoutManager(requireContext())
if (mess == "NOT_FOUND") {
activity!!.supportFragmentManager.beginTransaction()
.replace(R.id.frag_container, OwnerDetailsFragment())
.disallowAddToBackStack()
.commit()
}
getDataButton.setOnClickListener {
val dateString = SimpleDateFormat("dd.MM.yyyy").format(Date())
Log.d(this.tag, dateString)
studentList.clear()
val docRef = db.collection(mess!!).get()
docRef.addOnSuccessListener { documents ->
entries.clear()
for (document in documents) {
val entry = document.toObject(MessEntry::class.java)
entry.date?.forEach {
Log.d("TAG", "${it.date} $dateString")
if (it.date!! == dateString) {
studentList.addAll(it.students!!)
}
}
Log.d("TAG", "$studentList")
adapter.notifyDataSetChanged()
}
if (studentList.isEmpty()) {
requireContext().toast("No entries found for today!")
}
}
}
}
}
<file_sep>/app/src/main/java/org/firehound/messattendance/fragments/StudentFragment.kt
package org.firehound.messattendance.fragments
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.firebase.Timestamp
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.fragment_student.*
import org.firehound.messattendance.R
import org.firehound.messattendance.models.DateEntry
import org.firehound.messattendance.models.MessEntry
import org.firehound.messattendance.models.Student
import org.firehound.messattendance.utils.toast
import java.text.SimpleDateFormat
import java.util.*
class StudentFragment : Fragment() {
var isAttending = false
var meal = ""
data class Elem(
val isAttending: Boolean,
val regNo: String,
val time: Timestamp
)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_student, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val db = FirebaseFirestore.getInstance()
super.onViewCreated(view, savedInstanceState)
val prefs = activity!!.getSharedPreferences(DetailsFragment.prefId, Context.MODE_PRIVATE)
val regNo = prefs.getString("REG_NO", "NOT_FOUND")
val mess = prefs.getString("MESS", "NOT_FOUND")
if (regNo == "NOT_FOUND" || mess == "NOT_FOUND") {
activity!!.supportFragmentManager.beginTransaction()
.replace(R.id.frag_container, DetailsFragment()).disallowAddToBackStack().commit()
}
when (Calendar.getInstance().get(Calendar.HOUR_OF_DAY)) {
in 7..9 -> {
timeText.text = "Attendance for breakfast"
meal = "breakfast"
}
in 12..14 -> {
timeText.text = "Attendance for lunch"
meal = "lunch"
}
in 19..21 -> {
timeText.text = "Attendance for dinner"
meal = "dinner"
}
else -> {
timeText.text = "There's no meal available right now"
radioGroup.visibility = View.GONE
submitButton.visibility = View.GONE
}
}
radioGroup.setOnCheckedChangeListener { _, checkedId ->
isAttending = checkedId == radioAttend.id
}
submitButton.setOnClickListener {
val dateString = SimpleDateFormat("dd.MM.yyyy").format(Date())
val docRef = db.collection(mess!!).document(dateString)
docRef.get().addOnSuccessListener { documentSnapshot ->
var entry = documentSnapshot.toObject(MessEntry::class.java)
if (entry == null) {
val dates = arrayListOf(
DateEntry(
dateString, arrayListOf(
Student(regNo!!)
)
)
)
dates[0].students?.get(0)?.meal?.put(meal, isAttending)
entry = MessEntry(
mess,
dates
)
db.collection(mess).document(dateString).set(entry)
} else {
var studExists = false
var dateExists = false
entry.date?.forEach {
if (it.date == dateString) { // if today's date matches
dateExists = true
it.students?.forEach { student ->
if (student.regNo == regNo) { // if current student exists
studExists = true
student.meal[meal] = isAttending
}
}
}
}
if (!dateExists) {
val student = Student(regNo!!)
student.meal[meal] = isAttending
entry.date?.add(
DateEntry(
dateString,
arrayListOf(student)
)
)
}
if (!studExists && dateExists) {
entry.date?.forEach {
if (it.date == dateString) {
val student = Student(regNo!!)
student.meal[meal] = isAttending
it.students?.add(student)
}
}
}
}
docRef.set(entry)
requireContext().toast("Successfully submitted.")
}
}
}
}
<file_sep>/app/src/main/java/org/firehound/messattendance/adapters/StudentListAdapter.kt
package org.firehound.messattendance.adapters
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.recyclerview_item.view.*
import org.firehound.messattendance.R
import org.firehound.messattendance.models.Student
class StudentListAdapter(private var studentList: MutableList<Student>) :
RecyclerView.Adapter<StudentViewHolder>() {
@SuppressLint("InflateParams")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.recyclerview_item, null)
return StudentViewHolder(view)
}
override fun getItemCount() = studentList.size
override fun onBindViewHolder(holder: StudentViewHolder, position: Int) {
holder.itemView.regNoText.text = studentList[position].regNo
holder.itemView.isComingBreakfast.text = if (studentList[position].meal["breakfast"]!!) "Will attend breakfast" else "Won't attend breakfast"
holder.itemView.isComingLunch.text = if (studentList[position].meal["lunch"]!!) "Will attend lunch" else "Won't attend lunch"
holder.itemView.isComingDinner.text = if (studentList[position].meal["dinner"]!!) "Will attend dinner" else "Won't attend dinner"
}
}
class StudentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) | 55ebec78e0d87a29c9983c4eef8f64710e49ccc1 | [
"Kotlin",
"Gradle"
]
| 14 | Kotlin | ATechnoHazard/mess-attendance | fb2a6b8defdc9d186574e259fc265dff27313c70 | 61bb7a349fa55e752040321efb29c418c29802e8 |
refs/heads/master | <file_sep>using System.Threading.Tasks;
namespace BlazorApp7.Data
{
public interface IMyService
{
Task<string> GetInfoAsync(string id);
}
/*
* THIS METHOD IS CALLED TWICE
*/
public class MyService : IMyService
{
public async Task<string> GetInfoAsync(string id)
{
await Task.Run(() => { });
return "";
}
}
}<file_sep>using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorApp7.Data
{
public class KairosUser : IdentityUser
{
public string Firstname { get; set; }
public string Lastname { get; set; }
}
public class MyBlazorDbContext : IdentityDbContext<KairosUser>
{
public MyBlazorDbContext(DbContextOptions<MyBlazorDbContext> options) : base(options)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BlazorApp7.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Identity;
namespace BlazorApp7.Shared
{
public class NavbarBase : ComponentBase
{
[Inject] protected IMyService _service { get; set; }
protected string UserName { get; set; }
/*
_service.GetInfoAsync will be called twice from OnInitializedAsync
*/
protected override async Task OnInitializedAsync()
{
var a = await _service.GetInfoAsync("");
}
/*
_service.GetInfoAsync will be called once from OnInitializedAsync
*/
/*
protected override async Task OnAfterRenderAsync(bool firstRender)
{
var a = await _service.GetInfoAsync("");
}
*/
}
}
| 890dec93eac648ecf0f3002035baea983bb1e1c0 | [
"C#"
]
| 3 | C# | Blackleones/BlazorTest | 10292a85e399cdce85c82f5e026729838cb0eab7 | 6b3c0cf09171c3f4591902497c48bc0d665131dd |
refs/heads/master | <file_sep>FROM oraclelinux:8-slim
ARG TF_VERSION
ARG TERRAFORM_PROVIDER_ORACLERDBMS
LABEL maintainer="<NAME> <<EMAIL>>"
ENV TFTX_PATH /usr/share/terraform/plugins/local/tf/oraclerdbms/${TERRAFORM_PROVIDER_ORACLERDBMS}/linux_amd64/
COPY ./hashicorp.asc .
COPY terraform-provider-oraclerdbms.asc .
RUN microdnf install oracle-instantclient-release-el8 unzip && \
microdnf install oracle-instantclient-basic -y && \
gpg --import hashicorp.asc && \
gpg --import terraform-provider-oraclerdbms.asc && \
echo -e "5\ny\n" | gpg --command-fd 0 --no-tty --expert --edit-key 16EC794E20F4607EC3D345A72D24FF69F5762CA2 trust && \
echo -e "5\ny\n" | gpg --command-fd 0 --no-tty --expert --edit-key <KEY> trust && \
curl -sS -o terraform_${TF_VERSION}_linux_amd64.zip https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_amd64.zip \
--next -o terraform_${TF_VERSION}_SHA256SUMS https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS \
--next -o terraform_${TF_VERSION}_SHA256SUMS.sig https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS.sig && \
echo "$(grep terraform_${TF_VERSION}_linux_amd64.zip terraform_${TF_VERSION}_SHA256SUMS)" >> SHA256SUMS && \
gpg --verify terraform_${TF_VERSION}_SHA256SUMS.sig terraform_${TF_VERSION}_SHA256SUMS && \
sha256sum -c SHA256SUMS && \
mkdir -p $TFTX_PATH && \
curl -sS -o $TFTX_PATH/terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.zip \
https://storage.googleapis.com/terraform-provider-oraclerdbms/linux_amd64/terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.zip \
--next -o $TFTX_PATH/terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.SHA256 \
https://storage.googleapis.com/terraform-provider-oraclerdbms/linux_amd64/terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.SHA256 \
--next -o $TFTX_PATH/terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.SHA256.sig \
https://storage.googleapis.com/terraform-provider-oraclerdbms/linux_amd64/terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.SHA256.sig && \
cd $TFTX_PATH/ && \
gpg --verify terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.SHA256.sig \
terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.SHA256 && \
sha256sum -c terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.SHA256 && \
unzip $TFTX_PATH/terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.zip && \
chmod +x terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS} && \
rm $TFTX_PATH/terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.SHA256 \
$TFTX_PATH/terraform-provider-oraclerdbms_v${TERRAFORM_PROVIDER_ORACLERDBMS}.SHA256.sig && \
cd / && \
unzip terraform_${TF_VERSION}_linux_amd64.zip -d /usr/local/bin && \
rm -f terraform* SHA256SUMS hashicorp.asc && \
microdnf remove oracle-instantclient-release-el8 unzip && \
microdnf clean all && \
adduser -m -d /home/terraform terraform && \
chown -R terraform:terraform /home/terraform && \
mkdir -p /terraform && \
chown -R terraform:terraform /terraform
ENV LD_LIBRARY_PATH /usr/lib/oracle/21/client64
ENV ORACLE_HOME /usr/lib/oracle/21/client64
ENV TNS_ADMIN /home/terraform
USER terraform
WORKDIR /terraform
ENTRYPOINT ["terraform"]<file_sep>package oraclerdbms
import (
"log"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
/*
This version of oraclerdbms_block_change_tracking resource does not support OMF and ASM
*/
func resourceBlockChangeTracking() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateBlockChangeTracking,
Delete: resourceOracleRdbmsDeleteBlockChangeTracking,
Read: resourceOracleRdbmsReadBlockChangeTracking,
Update: resourceOracleRdbmsUpdateBlockChangeTracking,
Schema: map[string]*schema.Schema{
"status": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
/*
How should we handle if we use omf to not generate diff
*/
"file_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
}
}
func resourceOracleRdbmsCreateBlockChangeTracking(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsCreateBlockChangeTracking")
client := meta.(*oracleHelperType).Client
resourceBct := oraclehelper.ResourceBlockChangeTracking{
FileName: d.Get("file_name").(string),
}
err := client.BlockChangeTrackingService.EnableBlockChangeTracking(resourceBct)
if err != nil {
d.SetId("")
return err
}
d.SetId("cbt")
cbt, err := client.BlockChangeTrackingService.ReadBlockChangeTracking()
if err != nil {
d.SetId("")
return err
}
d.Set("file_name", cbt.FileName)
return nil
}
func resourceOracleRdbmsDeleteBlockChangeTracking(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsDeleteBlockChangeTracking")
client := meta.(*oracleHelperType).Client
err := client.BlockChangeTrackingService.DisableBlockChangeTracking()
if err != nil {
d.SetId("")
return err
}
return nil
}
func resourceOracleRdbmsReadBlockChangeTracking(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsReadBlockChangeTracking")
client := meta.(*oracleHelperType).Client
cbt, err := client.BlockChangeTrackingService.ReadBlockChangeTracking()
if err != nil {
d.SetId("")
return err
}
d.Set("status", cbt.Status)
d.Set("file_name", cbt.FileName)
return nil
}
func resourceOracleRdbmsUpdateBlockChangeTracking(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsUpdateBlockChangeTracking")
if d.HasChange("status") {
}
return nil
}
<file_sep>package oraclerdbms
import (
"fmt"
"log"
"strings"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceGrantSystemPrivilege() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateGrantSystemPrivilege,
Delete: resourceOracleRdbmsDeleteGrantSystemPrivilege,
Read: resourceOracleRdbmsReadGrantSystemPrivilege,
Update: nil,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"grantee": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"privilege": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
},
}
}
func resourceOracleRdbmsCreateGrantSystemPrivilege(d *schema.ResourceData, meta interface{}) error {
log.Println("[INFO] resourceOracleRdbmsCreateGrantSystemPrivilege")
var resourceGrantSystemPrivilege oraclehelper.ResourceGrantSystemPrivilege
client := meta.(*oracleHelperType).Client
resourceGrantSystemPrivilege.Grantee = d.Get("grantee").(string)
resourceGrantSystemPrivilege.Privilege = d.Get("privilege").(string)
err := client.GrantService.GrantSysPriv(resourceGrantSystemPrivilege)
if err != nil {
d.SetId("")
return err
}
id := grantSysPrivID(d.Get("grantee").(string), d.Get("privilege").(string))
d.SetId(id)
return resourceOracleRdbmsReadGrantSystemPrivilege(d, meta)
}
func resourceOracleRdbmsDeleteGrantSystemPrivilege(d *schema.ResourceData, meta interface{}) error {
log.Println("[INFO] resourceOracleRdbmsDeleteGrantSystemPrivilege")
var resourceGrantSystemPrivilege oraclehelper.ResourceGrantSystemPrivilege
client := meta.(*oracleHelperType).Client
resourceGrantSystemPrivilege.Grantee = d.Get("grantee").(string)
resourceGrantSystemPrivilege.Privilege = d.Get("privilege").(string)
err := client.GrantService.RevokeSysPriv(resourceGrantSystemPrivilege)
if err != nil {
return err
}
return nil
}
func resourceOracleRdbmsReadGrantSystemPrivilege(d *schema.ResourceData, meta interface{}) error {
log.Printf("[INFO] resourceOracleRdbmsReadGrantSystemPrivilege grantee:%s\n", d.Get("grantee"))
var resourceGrantSystemPrivilege oraclehelper.ResourceGrantSystemPrivilege
client := meta.(*oracleHelperType).Client
//ToDo Break out as a function ??
splitSystemPrivilege := strings.Split(d.Id(), "-")
grantee := splitSystemPrivilege[0]
privilege := splitSystemPrivilege[1]
resourceGrantSystemPrivilege.Grantee = grantee
sysPrivs, err := client.GrantService.ReadGrantSysPrivs(resourceGrantSystemPrivilege)
if err != nil {
d.SetId("")
return err
}
if _, ok := sysPrivs[privilege]; !ok {
d.SetId("")
return nil
}
d.Set("grantee", grantee)
d.Set("privilege", privilege)
return nil
}
func grantSysPrivID(grantee string, privilege string) string {
return fmt.Sprintf("%s-%s", grantee, privilege)
}
<file_sep>package oraclerdbms
import (
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
func TestAccUser(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccUserConfigBasic,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_user.test", "username", "USER666"),
),
},
resource.TestStep{
Config: testAccUserConfigBasicUpdate,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_user.test", "default_tablespace", "SYSTEM"),
resource.TestCheckResourceAttr("oraclerdbms_user.test", "account_status", "LOCKED"),
resource.TestCheckResourceAttr("oraclerdbms_user.test", "quota.%", "1"),
resource.TestCheckResourceAttr("oraclerdbms_user.test", "quota.SYSTEM", "10M"),
),
},
},
})
}
func TestAccUser_importBasic(t *testing.T) {
resourceName := "oraclerdbms_user.test"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
//CheckDestroy: testAccCheckInstanceDestroy,
Steps: []resource.TestStep{
{
Config: testAccUserConfigBasic,
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
const (
testAccUserConfigBasic = `
resource "oraclerdbms_user" "test" {
username = "USER666"
default_tablespace = "USERS"
account_status = "OPEN"
quota = {
SYSTEM = "10M"
}
}
`
testAccUserConfigBasicUpdate = `
resource "oraclerdbms_user" "test" {
username = "USER666"
default_tablespace = "SYSTEM"
account_status = "LOCKED"
quota = {
SYSTEM = "10M"
}
}
`
)
<file_sep>package oraclerdbms
import (
"fmt"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"log"
// "strings"
)
func resourceAutotask() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateAutotask,
Delete: resourceOracleRdbmsDeleteAutotask,
Read: resourceOracleRdbmsReadAutotask,
Update: resourceOracleRdbmsUpdateAutotask,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"client_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"status": &schema.Schema{
Type: schema.TypeBool,
Required: true,
},
},
}
}
func resourceOracleRdbmsCreateAutotask(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsCreateAutotask")
client := meta.(*oracleHelperType).Client
var err error
if d.Get("status").(bool) {
err = client.AutoTaskService.EnableAutoTask(oraclehelper.ResourceAutoTask{
ClientName: d.Get("client_name").(string),
Status: "YES"},
)
} else {
err = client.AutoTaskService.EnableAutoTask(oraclehelper.ResourceAutoTask{
ClientName: d.Get("client_name").(string),
Status: "NO"},
)
}
d.SetId(d.Get("client_name").(string))
return err
}
func resourceOracleRdbmsDeleteAutotask(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsDeleteAutotask")
return nil
}
func resourceOracleRdbmsReadAutotask(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsReadAutotask")
client := meta.(*oracleHelperType).Client
resourceAutoTask, err := client.AutoTaskService.ReadAutoTask(oraclehelper.ResourceAutoTask{
ClientName: d.Get("client_name").(string),
})
fmt.Print("INFO")
if err != nil {
return err
}
d.Set("status", resourceAutoTask.Status)
return nil
}
func resourceOracleRdbmsUpdateAutotask(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsUpdateAutotask")
client := meta.(*oracleHelperType).Client
var err error
if d.Get("status").(bool) {
err = client.AutoTaskService.EnableAutoTask(oraclehelper.ResourceAutoTask{
ClientName: d.Get("client_name").(string),
})
} else {
err = client.AutoTaskService.DisableAutoTask(oraclehelper.ResourceAutoTask{
ClientName: d.Get("client_name").(string),
})
}
return err
}
<file_sep>package oraclerdbms
import (
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"testing"
)
func TestAccDatabase(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccDatabaseConfigBasic,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_database.database", "forcelogging", "YES"),
),
},
},
})
}
func TestAccDatabase_importBasic(t *testing.T) {
resourceName := "oraclerdbms_database.database"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDatabaseConfigBasic,
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
const testAccDatabaseConfigBasic = `
resource "oraclerdbms_database" "database" {
forcelogging = "YES"
flashback = "NO"
}
`
<file_sep>package oraclerdbms
import (
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
func TestAccProfile(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccProfileConfigBasic,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_profile.test", "profile", "TEST01"),
),
},
},
})
}
func TestAccProfile_importBasic(t *testing.T) {
resourceName := "oraclerdbms_profile.test"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccProfileConfigBasic,
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
const testAccProfileConfigBasic = `
resource "oraclerdbms_profile" "test" {
profile = "TEST01"
}
`
<file_sep>package oraclerdbms
import (
"fmt"
"log"
"strings"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceGrantRolePrivilege() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateGrantRolePrivilege,
Delete: resourceOracleRdbmsDeleteGrantRolePrivilege,
Read: resourceOracleRdbmsReadGrantRolePrivilege,
Update: nil,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"grantee": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"role": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
},
}
}
func resourceOracleRdbmsCreateGrantRolePrivilege(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsCreateGrantRolePrivilege")
var resourceGrantRolePrivilege oraclehelper.ResourceGrantRolePrivilege
client := meta.(*oracleHelperType).Client
resourceGrantRolePrivilege.Grantee = d.Get("grantee").(string)
resourceGrantRolePrivilege.Role = d.Get("role").(string)
err := client.GrantService.GrantRolePriv(resourceGrantRolePrivilege)
if err != nil {
d.SetId("")
return err
}
id := grantRolePrivID(d.Get("grantee").(string), d.Get("role").(string))
d.SetId(id)
return resourceOracleRdbmsReadGrantRolePrivilege(d, meta)
}
func resourceOracleRdbmsDeleteGrantRolePrivilege(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsDeleteGrantRolePrivilege")
var resourceGrantRolePrivilege oraclehelper.ResourceGrantRolePrivilege
client := meta.(*oracleHelperType).Client
resourceGrantRolePrivilege.Grantee = d.Get("grantee").(string)
resourceGrantRolePrivilege.Role = d.Get("role").(string)
err := client.GrantService.RevokeRolePriv(resourceGrantRolePrivilege)
if err != nil {
return err
}
return nil
}
func resourceOracleRdbmsReadGrantRolePrivilege(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] resourceOracleRdbmsReadGrantRolePrivilege grantee:%s\n", d.Get("grantee"))
var resourceGrantRolePrivilege oraclehelper.ResourceGrantRolePrivilege
client := meta.(*oracleHelperType).Client
//ToDo Break out as a function ??
splitRolerivilege := strings.Split(d.Id(), "-")
grantee := splitRolerivilege[0]
role := splitRolerivilege[1]
resourceGrantRolePrivilege.Grantee = grantee
rolePrivs, err := client.GrantService.ReadGrantRolePrivs(resourceGrantRolePrivilege)
if err != nil {
d.SetId("")
return err
}
if _, ok := rolePrivs[role]; !ok {
d.SetId("")
return nil
}
d.Set("grantee", grantee)
d.Set("role", role)
return nil
}
func grantRolePrivID(grantee string, role string) string {
return fmt.Sprintf("%s-%s", grantee, role)
}
<file_sep>package oraclerdbms
import (
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
func TestAccStatsGlobal(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccStatsConfigBasiGlobal,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_stats.statstest", "preference_value", "PARTITION"),
),
},
resource.TestStep{
Config: testAccStatsConfigBasicGlobalUpdate,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_stats.statstest", "preference_value", "AUTO"),
),
},
},
})
}
func TestAccStatsTable(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccStatsConfigBasicTable,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_stats.statstable", "preference_value", "PARTITION"),
),
},
resource.TestStep{
Config: testAccStatsConfigBasicTableUpdate,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_stats.statstable", "preference_value", "GLOBAL"),
),
},
},
})
}
const (
testAccStatsConfigBasiGlobal = `
resource "oraclerdbms_stats" "statstest" {
preference_name = "GRANULARITY"
preference_value = "PARTITION"
}
`
testAccStatsConfigBasicGlobalUpdate = `
resource "oraclerdbms_stats" "statstest" {
preference_name = "GRANULARITY"
preference_value = "AUTO"
}
`
testAccStatsConfigBasicTable = `
# TEST table in schema need to exists...
resource "oraclerdbms_stats" "statstable" {
owner_name = "SYSTEM"
table_name = "TEST"
preference_name = "GRANULARITY"
preference_value = "PARTITION"
}
`
testAccStatsConfigBasicTableUpdate = `
# TEST table in schema need to exists...
resource "oraclerdbms_stats" "statstable" {
owner_name = "SYSTEM"
table_name = "TEST"
preference_name = "GRANULARITY"
preference_value = "GLOBAL"
}
`
)
<file_sep>package oraclerdbms
import (
"log"
"strings"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceRole() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateRole,
Delete: resourceOracleRdbmsDeleteRole,
Read: resourceOracleRdbmsReadRole,
Update: nil,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"role": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
},
}
}
func resourceOracleRdbmsCreateRole(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsCreateRole")
client := meta.(*oracleHelperType).Client
resourceRole := oraclehelper.ResourceRole{
Role: d.Get("role").(string),
}
err := client.RoleService.CreateRole(resourceRole)
if err != nil {
d.SetId("")
return err
}
d.SetId(d.Get("role").(string))
return resourceOracleRdbmsReadRole(d, meta)
}
func resourceOracleRdbmsDeleteRole(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsDeleteRole")
client := meta.(*oracleHelperType).Client
resourceRole := oraclehelper.ResourceRole{
Role: d.Id(),
}
err := client.RoleService.DropRole(resourceRole)
if err != nil {
d.SetId("")
return err
}
return nil
}
func resourceOracleRdbmsReadRole(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsReadRole")
client := meta.(*oracleHelperType).Client
resourceRole := oraclehelper.ResourceRole{
Role: d.Id(),
}
role, err := client.RoleService.ReadRole(resourceRole)
if err != nil {
d.SetId("")
return err
}
d.Set("role", role.Role)
return nil
}
func resourceOracleRdbmsUpdateRole(d *schema.ResourceData, meta interface{}) error {
return nil
}
<file_sep>package oraclerdbms
import (
"fmt"
"log"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)
type oracleHelperType struct {
Client *oraclehelper.Client
}
// Provider ....
func Provider() terraform.ResourceProvider {
log.Println("[DEBUG] Initializing oraclerdbms ResourceProvider")
return &schema.Provider{
Schema: map[string]*schema.Schema{
"service": &schema.Schema{
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("ORACLE_SERVICE", nil),
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value == "" {
errors = append(errors, fmt.Errorf("service must not be an empty string"))
}
return
},
},
"dbhost": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ORACLE_DBHOST", nil),
},
"dbport": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("ORACLE_DBPORT", nil),
},
"username": &schema.Schema{
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("ORACLE_USERNAME", nil),
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value == "" {
errors = append(errors, fmt.Errorf("Username must not be an empty string"))
}
return
},
},
"password": &schema.Schema{
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("ORACLE_PASSWORD", nil),
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value == "" {
errors = append(errors, fmt.Errorf("Username must not be an empty string"))
}
return
},
},
},
ResourcesMap: map[string]*schema.Resource{
"oraclerdbms_autotask": resourceAutotask(),
"oraclerdbms_block_change_tracking": resourceBlockChangeTracking(),
"oraclerdbms_database": resourceDatabase(),
"oraclerdbms_grant_object_privilege": resourceGrantObjectPrivilege(),
"oraclerdbms_grant_role_privilege": resourceGrantRolePrivilege(),
"oraclerdbms_grant_system_privilege": resourceGrantSystemPrivilege(),
"oraclerdbms_parameter": resourceParameter(),
"oraclerdbms_profile": resourceProfile(),
"oraclerdbms_profile_limit": resourceProfileLimit(),
"oraclerdbms_role": resourceRole(),
"oraclerdbms_stats": resourceStats(),
"oraclerdbms_user": resourceUser(),
},
ConfigureFunc: providerConfigure,
}
}
func providerConfigure(d *schema.ResourceData) (interface{}, error) {
var config oraclehelper.Cfg
if d.Get("username").(string) != "" {
config.Username = d.Get("username").(string)
}
if d.Get("password").(string) != "" {
config.Password = d.Get("password").(string)
}
if d.Get("dbhost").(string) != "" {
config.DbHost = d.Get("dbhost").(string)
}
if d.Get("dbport").(string) != "" {
config.DbPort = d.Get("dbport").(string)
}
if d.Get("service").(string) != "" {
config.DbService = d.Get("service").(string)
}
client, err := oraclehelper.NewClient(config)
if err != nil {
return nil, err
}
log.Println("[DEBUG] Initializing Oracle DB Helper client")
return &oracleHelperType{
Client: client,
}, nil
}
<file_sep># README
## Pull Docker image
```shell
docker pull ba78/terraform-provider-oraclerdbms:0.3.0
```
## Setup tf alias
```shell
alias tf="docker run \
-u $(id -u $(whoami)):$(id -g $(whoami)) \
-v $(pwd):/opt/tf \
-w /opt/tf \
--rm \
-e ORACLE_DBHOST \
-e ORACLE_DBPORT \
-e ORACLE_SERVICE \
-e ORACLE_USERNAME \
-e ORACLE_PASSWORD \
-e TF_LOG \
-e HOME=/home/tf \
-it \
ba78/terraform-provider-oraclerdbms:0.3.0"
```
## init
tf init
## plan
```shell
tf plan
```
### output
```
C02WH1TKHTD5:example bjorn.ahl$ tf plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
------------------------------------------------------------------------
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
+ oraclerdbms_grant_role_privilege.grantroleprivs
id: <computed>
grantee: "${ORACLERDBMS_USER.EXAMPLE_USER.ID}"
role: "${ORACLERDBMS_ROLE.EXAMPLE_ROLE.ID}"
+ oraclerdbms_grant_system_privilege.syspriv_create_session
id: <computed>
grantee: "${ORACLERDBMS_USER.EXAMPLE_USER.ID}"
privilege: "CREATE SESSION"
+ oraclerdbms_profile.profile
id: <computed>
profile: "DEMO01"
+ oraclerdbms_profile_limit.profile_idle_time
id: <computed>
profile: "${oraclerdbms_profile.profile.id}"
resource_name: "IDLE_TIME"
value: "33"
+ oraclerdbms_role.example_role
id: <computed>
role: "EXAMPLE_ROLE"
+ oraclerdbms_stats.granularity_auto
id: <computed>
preference_name: "GRANULARITY"
preference_value: "AUTO"
+ oraclerdbms_user.example_user
id: <computed>
account_status: "OPEN"
default_tablespace: "USERS"
profile: "${ORACLERDBMS_PROFILE.PROFILE.ID}"
temporary_tablespace: <computed>
username: "EXAMPLE_USER"
Plan: 7 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
```
## Apply
```shell
tf apply
```
### output
```
C02WH1TKHTD5:example bjorn.ahl$ tf apply
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
+ oraclerdbms_grant_role_privilege.grantroleprivs
id: <computed>
grantee: "${ORACLERDBMS_USER.EXAMPLE_USER.ID}"
role: "${ORACLERDBMS_ROLE.EXAMPLE_ROLE.ID}"
+ oraclerdbms_grant_system_privilege.syspriv_create_session
id: <computed>
grantee: "${ORACLERDBMS_USER.EXAMPLE_USER.ID}"
privilege: "CREATE SESSION"
+ oraclerdbms_profile.profile
id: <computed>
profile: "DEMO01"
+ oraclerdbms_profile_limit.profile_idle_time
id: <computed>
profile: "${oraclerdbms_profile.profile.id}"
resource_name: "IDLE_TIME"
value: "33"
+ oraclerdbms_role.example_role
id: <computed>
role: "EXAMPLE_ROLE"
+ oraclerdbms_stats.granularity_auto
id: <computed>
preference_name: "GRANULARITY"
preference_value: "AUTO"
+ oraclerdbms_user.example_user
id: <computed>
account_status: "OPEN"
default_tablespace: "USERS"
profile: "${ORACLERDBMS_PROFILE.PROFILE.ID}"
temporary_tablespace: <computed>
username: "EXAMPLE_USER"
Plan: 7 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
oraclerdbms_stats.granularity_auto: Creating...
preference_name: "" => "GRANULARITY"
preference_value: "" => "AUTO"
oraclerdbms_role.example_role: Creating...
role: "" => "EXAMPLE_ROLE"
oraclerdbms_profile.profile: Creating...
profile: "" => "DEMO01"
oraclerdbms_stats.granularity_auto: Creation complete after 0s (ID: STATS-GLOBAL-GRANULARITY)
oraclerdbms_profile.profile: Creation complete after 0s (ID: DEMO01)
oraclerdbms_profile_limit.profile_idle_time: Creating...
profile: "" => "DEMO01"
resource_name: "" => "IDLE_TIME"
value: "" => "33"
oraclerdbms_user.example_user: Creating...
account_status: "" => "OPEN"
default_tablespace: "" => "USERS"
profile: "" => "DEMO01"
temporary_tablespace: "" => "<computed>"
username: "" => "EXAMPLE_USER"
oraclerdbms_profile_limit.profile_idle_time: Creation complete after 0s (ID: DEMO01-IDLE_TIME)
oraclerdbms_role.example_role: Creation complete after 0s (ID: EXAMPLE_ROLE)
oraclerdbms_user.example_user: Creation complete after 0s (ID: EXAMPLE_USER)
oraclerdbms_grant_system_privilege.syspriv_create_session: Creating...
grantee: "" => "EXAMPLE_USER"
privilege: "" => "CREATE SESSION"
oraclerdbms_grant_role_privilege.grantroleprivs: Creating...
grantee: "" => "EXAMPLE_USER"
role: "" => "EXAMPLE_ROLE"
oraclerdbms_grant_system_privilege.syspriv_create_session: Creation complete after 0s (ID: EXAMPLE_USER-CREATE SESSION)
oraclerdbms_grant_role_privilege.grantroleprivs: Creation complete after 0s (ID: EXAMPLE_USER-EXAMPLE_ROLE)
Apply complete! Resources: 7 added, 0 changed, 0 destroyed.
```
<file_sep>package oraclerdbms
import (
"fmt"
"log"
"strings"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceProfileLimit() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateProfileLimit,
Delete: resourceOracleRdbmsDeleteProfileLimit,
Read: resourceOracleRdbmsReadProfileLimit,
Update: resourceOracleRdbmsUpdateProfileLimit,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"resource_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"value": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"profile": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceOracleRdbmsCreateProfileLimit(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsCreateProfile")
var resourceProfile oraclehelper.ResourceProfile
client := meta.(*oracleHelperType).Client
resourceProfile.Profile = d.Get("profile").(string)
resourceProfile.ResourceName = d.Get("resource_name").(string)
resourceProfile.Limit = d.Get("value").(string)
client.ProfileService.UpdateProfile(resourceProfile)
d.SetId(getProfileLimitID(d.Get("profile").(string), d.Get("resource_name").(string)))
return resourceOracleRdbmsUpdateProfileLimit(d, meta)
}
func resourceOracleRdbmsDeleteProfileLimit(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsDeleteProfile")
var resourceProfile oraclehelper.ResourceProfile
resourceProfile.Profile = d.Get("profile").(string)
resourceProfile.ResourceName = d.Get("resource_name").(string)
client := meta.(*oracleHelperType).Client
client.ProfileService.ResetProfileResourceLimite(resourceProfile)
return nil
}
func resourceOracleRdbmsReadProfileLimit(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsReadProfile")
//ToDo Break out as a function ??
splitProfileLimit := strings.Split(d.Id(), "-")
profile := splitProfileLimit[0]
resourceName := splitProfileLimit[1]
resourceProfile := oraclehelper.ResourceProfile{
Profile: profile,
}
client := meta.(*oracleHelperType).Client
profileLimit, _ := client.ProfileService.ReadProfile(resourceProfile)
d.Set("value", profileLimit[resourceName])
d.Set("profile", profileLimit["PROFILE"])
d.Set("resource_name", resourceName)
return nil
}
func resourceOracleRdbmsUpdateProfileLimit(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsUpdateProfile")
client := meta.(*oracleHelperType).Client
resourceProfile := oraclehelper.ResourceProfile{
Profile: d.Get("profile").(string),
ResourceName: d.Get("resource_name").(string),
Limit: d.Get("value").(string),
}
client.ProfileService.UpdateProfile(resourceProfile)
return resourceOracleRdbmsReadProfileLimit(d, meta)
}
func getProfileLimitID(profile string, resourceName string) string {
return fmt.Sprintf("%s-%s", profile, resourceName)
}
<file_sep>package oraclerdbms
import (
"log"
"strings"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceUser() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateUser,
Delete: resourceOracleRdbmsDeleteUser,
Read: resourceOracleRdbmsReadUser,
Update: resourceOracleRdbmsUpdateUser,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
SchemaVersion: 1,
MigrateState: resourceOracleRdbmsUserMigrate,
Schema: map[string]*schema.Schema{
"username": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"account_status": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "OPEN",
},
"profile": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"default_tablespace": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"temporary_tablespace": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"quota": &schema.Schema{
Type: schema.TypeMap,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
},
},
}
}
func resourceOracleRdbmsCreateUser(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsCreateUser")
var user oraclehelper.ResourceUser
client := meta.(*oracleHelperType).Client
if d.Get("username").(string) != "" {
user.Username = d.Get("username").(string)
}
if d.Get("account_status").(string) != "" {
v := d.Get("account_status").(string)
switch {
case v == "OPEN":
user.AccountStatus = "UNLOCK"
case v == "LOCKED":
user.AccountStatus = "LOCK"
case strings.HasPrefix(v, "EXPIRED"):
user.AccountStatus = "EXPIRED"
}
}
if d.Get("profile").(string) != "" {
user.Profile = d.Get("profile").(string)
}
if d.Get("default_tablespace").(string) != "" {
user.DefaultTablespace = d.Get("default_tablespace").(string)
}
if d.Get("temporary_tablespace").(string) != "" {
user.TemporaryTablespace = d.Get("temporary_tablespace").(string)
}
quotaMap := map[string]string{}
if v, ok := d.GetOk("quota"); ok {
for key, value := range v.(map[string]interface{}) {
quotaMap[key] = value.(string)
}
user.Quota = quotaMap
}
client.UserService.CreateUser(user)
d.SetId(d.Get("username").(string))
return resourceOracleRdbmsUpdateUser(d, meta)
}
func resourceOracleRdbmsDeleteUser(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsDeleteUser")
var user oraclehelper.ResourceUser
client := meta.(*oracleHelperType).Client
user.Username = d.Id()
err := client.UserService.DropUser(user)
if err != nil {
log.Fatalf("Error droping user err msg: %v", err)
}
return nil
}
func resourceOracleRdbmsReadUser(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsReadUser")
var resourceUser oraclehelper.ResourceUser
client := meta.(*oracleHelperType).Client
resourceUser.Username = d.Id()
user, err := client.UserService.ReadUser(resourceUser)
log.Printf("[DEBUG] Resource read user user: %v\n", user)
if err != nil {
log.Printf("[ERROR] readuser failed: %v\n", err)
d.SetId("")
return nil
}
if user.Username == "" {
log.Println("exit username nil")
d.SetId("")
return nil
}
if user == nil {
log.Println("exit user nil")
d.SetId("")
return nil
}
if user.Username != "" {
d.Set("username", user.Username)
}
if user.AccountStatus != "" {
switch {
case user.AccountStatus == "OPEN":
d.Set("account_status", user.AccountStatus)
case user.AccountStatus == "LOCKED":
d.Set("account_status", user.AccountStatus)
case strings.HasPrefix(user.AccountStatus, "EXPIRED"):
d.Set("account_status", "EXPIRED")
}
}
if user.DefaultTablespace != "" {
d.Set("default_tablespace", user.DefaultTablespace)
}
if user.DefaultTablespace != "" {
d.Set("temporary_tablespace", user.TemporaryTablespace)
}
if user.Profile != "" {
d.Set("profile", user.Profile)
}
if len(user.Quota) > 0 {
d.Set("quota", user.Quota)
}
return nil
}
func resourceOracleRdbmsUpdateUser(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsUpdateUser")
if !d.IsNewResource() {
var resourceUser oraclehelper.ResourceUser
client := meta.(*oracleHelperType).Client
if d.Get("username").(string) != "" {
resourceUser.Username = d.Get("username").(string)
}
if d.HasChange("profile") {
resourceUser.Profile = d.Get("profile").(string)
}
if d.HasChange("default_tablespace") {
resourceUser.DefaultTablespace = d.Get("default_tablespace").(string)
}
if d.HasChange("temporary_tablespace") {
resourceUser.TemporaryTablespace = d.Get("temporary_tablespace").(string)
}
if d.HasChange("account_status") {
v := d.Get("account_status").(string)
switch {
case v == "OPEN":
resourceUser.AccountStatus = "UNLOCK"
case v == "LOCKED":
resourceUser.AccountStatus = "LOCK"
case strings.HasPrefix(v, "EXPIRED"):
resourceUser.AccountStatus = "EXPIRED"
}
}
quotaMap := map[string]string{}
if v, ok := d.GetOk("quota"); ok {
for key, value := range v.(map[string]interface{}) {
quotaMap[key] = value.(string)
}
resourceUser.Quota = quotaMap
}
client.UserService.ModifyUser(resourceUser)
}
return resourceOracleRdbmsReadUser(d, meta)
}
<file_sep>package oraclerdbms
import (
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
func TestAccBlockChangeTracking(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccCbt,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_block_change_tracking.cbt", "status", "ENABLED"),
),
},
},
})
}
const testAccCbt = `
resource "oraclerdbms_block_change_tracking" "cbt" {
status = "ENABLED"
file_name = "/opt/oracle/product/12.2.0.1/dbhome_1/dbs/bb"
}
`
<file_sep>module github.com/dbgeek/terraform-provider-oraclerdbms
require (
github.com/dbgeek/terraform-oracle-rdbms-helper v0.5.0
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/terraform-plugin-sdk v1.16.0
)
go 1.13
<file_sep># Terraform oraclerdbms provider changelog
## 0.5.3 (October 8, 2020)
* Bumping terraform-oracle-rdbms-helper to v0.5.0
* Dependency bumping terraform-plugin-sdk
## 0.5.2 (January 3, 2020)
* Bumping terraform-oracle-rdbms-helper to v0.4.2
## 0.5.1 (January 2, 2020)
* Bumping terraform-oracle-rdbms-helper to v0.4.1
## 0.5.0 (September 27, 2019)
* As of September 2019, Terraform provider developers importing the Go module github.com/hashicorp/terraform, known as Terraform Core, should switch to github.com/hashicorp/terraform-plugin-sdk, the Terraform Plugin SDK, instead.
## 0.4.0 (September 24, 2019)
* Adding support for terraform 0.12
## 0.3.2 (February, 14, 2019)
* Bumping terraform-oracle-rdbms-helper to v0.3.1
* Add resource oraclerdbms_block_change_tracking.
* Does not support OMF.
* Switch to go mod
## 0.3.1 (December, 08, 2018)
* Adding database resource to handle force logging and flashback
* Adding autotask resource to enable/disable sql tuning advisor, auto optimizer stats collection, auto space advisor
## 0.3.0 (November 27, 2018)
* Bumping terraform-oracle-rdbms-helper to v0.2.8.1
* Adding support for user account_status , open, locked, expired
* Adding support for user resource quota
* Removing password attribute from resource user
## 0.2.9 (November 15, 2018)
* Bumping terraform-oracle-rdbms-helper to v0.2.7
* Adding support to delete resource operation.
* objects_sha256 & privs_sha256 from string to map to track sha256 per privilege
## 0.2.8 (November 13, 2018)
* Updating vendoring for terraform-oracle-rdbms-helper to v0.2.5
* Implement resource oraclerdbms_stats
## 0.2.7 (November 12, 2018)
* Changing name on struct that olding the OracleApi from providerConfiguration to oracleHelperType
* Generate a diff if privs_sha256 is not equal to objects_sha256
## 0.2.6 (November 9, 2018)
* using the GetHashSchemaPrivsToUser to get diff
## 0.2.5 (November 9, 2018)
* Updating vendoring for terraform-oracle-rdbms-helper to 0.2.3
## 0.2.4 (November 9, 2018)
* Adding some logging for debuging
## 0.2.3 (November 8, 2018)
* Updating vendoring for terraform-oracle-rdbms-helper to 0.2.2
* First alpha release of grant schema to user. Just support tables and now it revokes/grants everything the grant if there is something diff
## 0.2.2 (November 2, 2018)
* Updating vendoring for terraform-oracle-rdbms-helper to 0.2.1
## 0.2.1 (October 24, 2018)
NOTES:
* Implement Importer for all the resources
## 0.2.0 (October 22, 2018)
NOTES:
### resource_profile_limite
* Store in upercase in the state
* Changes attribute profile_id => profile
* Changes attribute limit => resource_name
## 0.1.1 (October 18, 2018)
NOTES:
uppdating go vendoring
## 0.1.0 (October 15, 2018)
NOTES:
* resource_grant_object_privileges
* resource_grant_role_privilege
* resource_grant_system_privilege
* resource_parameter
* resource_profile
* resource_profile_limit
* resource_role
* resource_user<file_sep>Terraform Provider
==================
- Website: https://www.terraform.io
- [](https://gitter.im/hashicorp-terraform/Lobby)
- Mailing list: [Google Groups](http://groups.google.com/group/terraform-tool)
<img src="https://cdn.rawgit.com/hashicorp/terraform-website/master/content/source/assets/images/logo-hashicorp.svg" width="600px">
Maintainers
-----------
This provider plugin is **not** maintained by the Terraform team at [HashiCorp](https://www.hashicorp.com/).
Requirements
------------
- [Terraform](https://www.terraform.io/downloads.html) 0.10.x
- [Go](https://golang.org/doc/install) 1.8 (to build the provider plugin)go-oci8[()]
- [go-oci8](https://github.com/mattn/go-oci8)
- [terraform-oracle-rdbms-helper](https://github.com/dbgeek/terraform-oracle-rdbms-helper)
Usage
---------------------
```terraform
# For example, restrict oraclerdbms version in 0.1.x
provider "oraclerdbms" {
version = "~> 0.1"
}
resource "oraclerdbms_profile" "test" {
profile = "TEST01"
}
resource "oraclerdbms_profile_limit" "test1" {
resource_name = "IDLE_TIME"
value = "33"
profile = "${oraclerdbms_profile.test.id}"
}
resource "oraclerdbms_user" "testuser" {
username = "TESTUSER"
default_tablespace = "USERS"
profile = "${oraclerdbms_profile.test.id}
}
resource "oraclerdbms_grant_system_privilege" "grantsysprivs" {
grantee = "${oraclerdbms_user.testuser.id}"
privilege = "CREATE SESSION"
}
resource "oraclerdbms_role" "roletest" {
role = "TESTROLE"
}
resource "oraclerdbms_grant_role_privilege" "grantroleprivs" {
grantee = "${oraclerdbms_user.testuser.id}"
role = "${oraclerdbms_role.roletest.id}"
}
```
Building The Provider
---------------------
Clone repository to: `$GOPATH/src/github.com/dbgeek/terraform-provider-oraclerdbms`
```sh
$ mkdir -p $GOPATH/src/github.com/dbgeek/terraform-provider-oraclerdbms; cd $GOPATH/src/github.com/dbgeek
$ git clone <EMAIL>:dbgeek/terraform-provider-oraclerdbms
```
Enter the provider directory and build the provider
```sh
$ cd $GOPATH/src/github.com/dbgeek/terraform-provider-oraclerdbms
$ make build
```
Using the provider
----------------------
## Fill in for each provider
Developing the Provider
---------------------------
If you wish to work on the provider, you'll first need [Go](http://www.golang.org) installed on your machine (version 1.8+ is *required*). You'll also need to correctly setup a [GOPATH](http://golang.org/doc/code.html#GOPATH), as well as adding `$GOPATH/bin` to your `$PATH`.
To compile the provider, run `make build`. This will build the provider and put the provider binary in the `$GOPATH/bin` directory.
```sh
$ make bin
...
$ $GOPATH/bin/terraform-provider-oraclerdbms
...
```
In order to test the provider, you can simply run `make test`.
```sh
$ make test
```
In order to run the full suite of Acceptance tests, run `make testacc`.
*Note:* Acceptance tests create real resources, and often cost money to run.
```sh
$ make testacc
```
<file_sep># terraform oraclerdbms in Docker
## build
```sh
./build
```
## example run
Example how to run oracle_rdbms using docker. This is an raw example. To make more usable we need to build some bash script wrapper around the the docker run commands.
We need to have ORACLE_SERVICE set to the tnsnames.ora entry we want to use and we need also set ORACLE_USERNAME & ORACLE_PASSWORD for which db user and password we should use.
`TNS_NAMES` need also be exported to the the path where your tnsnames.ora is.
### terraform init
```text
docker run \
-v $(pwd):/terraform \
-v "$TNS_ADMIN/tnsnames.ora":/home/terraform/tnsnames.ora \
-e ORACLE_SERVICE \
-e ORACLE_USERNAME \
-e ORACLE_PASSWORD \
tf-oraclerdbms:0.5.3.1 init
Initializing the backend...
Initializing provider plugins...
- Finding local/tf/oraclerdbms versions matching "~> 0.1"...
- Installing local/tf/oraclerdbms v0.5.3...
- Installed local/tf/oraclerdbms v0.5.3 (unauthenticated)
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
```
### terraform plan
```text
docker run \
-v $(pwd):/terraform \
-v $TNS_ADMIN/tnsnames.ora:/home/terraform/tnsnames.ora \
-e ORACLE_SERVICE \
-e ORACLE_USERNAME \
-e ORACLE_PASSWORD \
tf-oraclerdbms:0.5.3.1 plan -out=terraform.tfplan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
------------------------------------------------------------------------
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# oraclerdbms_profile.app_profile will be created
+ resource "oraclerdbms_profile" "app_profile" {
+ id = (known after apply)
+ profile = "APP_PROFILE"
}
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
This plan was saved to: terraform.tfplan
To perform exactly these actions, run the following command to apply:
terraform apply "terraform.tfplan"
```
### terraform apply
```text
docker run \
-v $(pwd):/terraform \
-v $TNS_ADMIN/tnsnames.ora:/home/terraform/tnsnames.ora \
-e ORACLE_SERVICE \
-e ORACLE_USERNAME \
-e ORACLE_PASSWORD \
tf-oraclerdbms:0.5.3.1 apply "terraform.tfplan"
oraclerdbms_profile.app_profile: Creating...
oraclerdbms_profile.app_profile: Creation complete after 0s [id=APP_PROFILE]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.
State path: terraform.tfstate
```
<file_sep>package oraclerdbms
import (
"fmt"
"log"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)
func resourceOracleRdbmsGrantObjectPrivilegeMigrate(
v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
switch v {
case 0:
log.Println("[INFO] Found oraclerdbms GrantObjectPrivilege v0; migrating to v1")
return migrateGrantObjectPrivilegeV0toV1(is)
default:
return is, fmt.Errorf("Unexpected schema version: %d", v)
}
}
func migrateGrantObjectPrivilegeV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) {
if is.Empty() || is.Attributes == nil {
log.Println("[DEBUG] Empty State; nothing to migrate.")
return is, nil
}
log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes)
is.Attributes["privs_sha256.%"] = "1"
is.Attributes["privs_sha256.select"] = is.Attributes["privs_sha256"]
delete(is.Attributes, "privs_sha256")
is.Attributes["objects_sha256.%"] = "1"
is.Attributes["objects_sha256.select"] = is.Attributes["objects_sha256"]
delete(is.Attributes, "objects_sha256")
log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes)
return is, nil
}
<file_sep>package oraclerdbms
import (
"log"
"strings"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)
func resourceParameter() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateParameter,
Delete: resourceOracleRdbmsDeleteParameter,
Read: resourceOracleRdbmsReadParameter,
Update: resourceOracleRdbmsUpdateParameter,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"value": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"update_comment": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"scope": &schema.Schema{
Type: schema.TypeString,
Optional: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
ValidateFunc: validation.StringInSlice([]string{
"memory",
"spfile",
"both",
}, true),
Default: "both",
},
},
}
}
// CreateParameter ..
func resourceOracleRdbmsCreateParameter(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] CreateParameter")
var resourceParameter oraclehelper.ResourceParameter
if d.Get("update_comment").(string) != "" {
resourceParameter.Comment = d.Get("update_comment").(string)
}
resourceParameter.Name = d.Get("name").(string)
resourceParameter.Value = d.Get("value").(string)
resourceParameter.Scope = d.Get("scope").(string)
client := meta.(*oracleHelperType).Client
client.ParameterService.SetParameter(resourceParameter)
d.SetId(d.Get("name").(string))
return resourceOracleRdbmsUpdateParameter(d, meta)
}
// DeleteParameter ..
func resourceOracleRdbmsDeleteParameter(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] DeleteParameter")
var resourceParameter oraclehelper.ResourceParameter
client := meta.(*oracleHelperType).Client
resourceParameter.Name = d.Id()
client.ParameterService.ResetParameter(resourceParameter)
d.SetId("")
return nil
}
// ReadParameter ..
func resourceOracleRdbmsReadParameter(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] ReadParameter")
var resourceParameter oraclehelper.ResourceParameter
client := meta.(*oracleHelperType).Client
resourceParameter.Name = d.Id()
parm, err := client.ParameterService.Read(resourceParameter)
if err != nil {
log.Fatal("READERROR")
d.SetId("")
}
if parm.Value == parm.DefaultValue {
log.Printf("[DEBUG] ReadParameter Is default, value: %s state value: %s\n", parm.Value, d.Get("value").(string))
d.SetId("")
return nil
}
d.Set("value", parm.Value)
d.Set("name", parm.Name)
if d.Get("scope").(string) == "" {
d.Set("scope", "BOTH")
}
log.Printf("[DEBUG] name: %s, value: %s, defaultvalue: %s \n", parm.Name, parm.Value, parm.DefaultValue)
return nil
}
// UpdateParameter ..@
func resourceOracleRdbmsUpdateParameter(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] UpdateParameter")
var resourceParameter oraclehelper.ResourceParameter
if d.Get("update_comment").(string) != "" {
resourceParameter.Comment = d.Get("update_comment").(string)
}
resourceParameter.Name = d.Id()
resourceParameter.Value = d.Get("value").(string)
if !d.IsNewResource() {
client := meta.(*oracleHelperType).Client
client.ParameterService.SetParameter(resourceParameter)
}
return resourceOracleRdbmsReadParameter(d, meta)
}
<file_sep>package oraclerdbms
import (
"log"
"strings"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceProfile() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateProfile,
Delete: resourceOracleRdbmsDeleteProfile,
Read: resourceOracleRdbmsReadProfile,
Update: nil,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"profile": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
},
}
}
func resourceOracleRdbmsCreateProfile(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsCreateProfile")
var resourceProfile oraclehelper.ResourceProfile
client := meta.(*oracleHelperType).Client
resourceProfile.Profile = d.Get("profile").(string)
client.ProfileService.CreateProfile(resourceProfile)
d.SetId(d.Get("profile").(string))
return resourceOracleRdbmsReadProfile(d, meta)
}
func resourceOracleRdbmsDeleteProfile(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsDeleteProfile")
var resourceProfile oraclehelper.ResourceProfile
client := meta.(*oracleHelperType).Client
resourceProfile.Profile = d.Id()
client.ProfileService.DeleteProfile(resourceProfile)
return nil
}
func resourceOracleRdbmsReadProfile(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsReadProfile")
var resourceProfile oraclehelper.ResourceProfile
client := meta.(*oracleHelperType).Client
resourceProfile.Profile = d.Id()
rawProfile, err := client.ProfileService.ReadProfile(resourceProfile)
if err != nil {
log.Printf("[ERROR] ReadProfile failed")
return err
}
profile := rawProfile["PROFILE"]
d.Set("profile", profile)
return nil
}
func resourceOracleRdbmsUpdateProfile(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsUpdateProfile")
return resourceOracleRdbmsReadProfile(d, meta)
}
<file_sep>#!/usr/bin/env bash
# shellcheck disable=SC1091
source image.env
docker build --build-arg TF_VERSION="${TF_VERSION}" \
--build-arg TERRAFORM_PROVIDER_ORACLERDBMS="${TERRAFORM_PROVIDER_ORACLERDBMS}" \
-t tf-oraclerdbms:"${VERSION}" .
<file_sep>package oraclerdbms
import (
"os"
"testing"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)
var testAccProviders map[string]terraform.ResourceProvider
var testAccProvider *schema.Provider
var client oraclehelper.Client
func init() {
testAccProvider = Provider().(*schema.Provider)
testAccProvider.ConfigureFunc = providerConfigure
testAccProviders = map[string]terraform.ResourceProvider{
"oraclerdbms": testAccProvider,
}
}
func TestProvider(t *testing.T) {
if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}
func TestProvider_impl(t *testing.T) {
var _ terraform.ResourceProvider = Provider()
}
func testAccPreCheck(t *testing.T) {
for _, name := range []string{"ORACLE_USERNAME", "ORACLE_PASSWORD", "ORACLE_DBHOST", "ORACLE_DBPORT", "ORACLE_SERVICE"} {
if v := os.Getenv(name); v == "" {
t.Fatal("ORACLE_USERNAME, ORACLE_PASSWORD,ORACLE_PASSWORD, ORACLE_DBHOST,ORACLE_DBPORT, ORACLE_SERVICE must be set for acceptance tests")
}
}
}
<file_sep>package oraclerdbms
import (
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
func TestAccGrantRolePrivs(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccGrantRolePrivsConfigBasic,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_grant_role_privilege.grantroleprivs", "role", "ROLEPRIVS"),
),
},
},
})
}
func TestAccGrantRolePrivs_importBasic(t *testing.T) {
resourceName := "oraclerdbms_grant_role_privilege.grantroleprivs"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccGrantRolePrivsConfigBasic,
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
const testAccGrantRolePrivsConfigBasic = `
resource "oraclerdbms_grant_role_privilege" "grantroleprivs" {
grantee = "${oraclerdbms_user.userrolepriv.id}"
role = "${oraclerdbms_role.roleprivstest.id}"
}
resource "oraclerdbms_user" "userrolepriv" {
username = "USERROLEPRIVS"
default_tablespace = "USERS"
}
resource "oraclerdbms_role" "roleprivstest" {
role = "ROLEPRIVS"
}
`
<file_sep>package oraclerdbms
import (
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
var (
autoTasks = [3]string{"sql tuning advisor", "auto optimizer stats collection", "auto space advisor"}
)
func TestAccAutotask(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccGAutotaskConfigBasic,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_autotask.autotask", "status", "true"),
),
},
},
})
}
const testAccGAutotaskConfigBasic = `
resource "oraclerdbms_autotask" "autotask" {
client_name = "sql tuning advisor"
status = true
}
`
<file_sep>package oraclerdbms
import (
"fmt"
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)
func TestAccGrantObjPrivs(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccGrantObjPrivsConfigBasic,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_grant_object_privilege.grantobjtest", "owner", "SYSTEM"),
),
},
resource.TestStep{
Config: testAccGrantObjPrivsConfigBasic2,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_grant_object_privilege.grantobjtest", "owner", "SYSTEM"),
),
},
},
})
}
func TestAccGrantObjPrivsOnSchema(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
CheckDestroy: testGrantOnSchemaAddCleanUp(),
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccGrantObjPrivsOnSchemaConfigBasic,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_grant_object_privilege.grantobjschematest", "owner", "SYSTEM"),
),
},
},
})
}
func TestAccGrantObjPrivs_importBasic(t *testing.T) {
resourceName := "oraclerdbms_grant_object_privilege.grantobjtest"
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccGrantObjPrivsConfigBasic,
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func testDBVersion() resource.TestCheckFunc {
return func(s *terraform.State) error {
oracleHelper := testAccProvider.Meta().(*oracleHelperType)
fmt.Printf("[DEBUG] This Dbversion %s\n", oracleHelper.Client.DBVersion)
return nil
}
}
func testGrantOnSchemaAddSetup() resource.TestCheckFunc {
return func(s *terraform.State) error {
client := testAccProvider.Meta().(*oracleHelperType).Client
client.DBClient.Exec("CREATE TABLE SYSTEM.TST_TBL1(col number)")
return nil
}
}
func testGrantOnSchemaAddTable() resource.TestCheckFunc {
return func(s *terraform.State) error {
client := testAccProvider.Meta().(*oracleHelperType).Client
client.DBClient.Exec("CREATE TABLE SYSTEM.TST_TBL2(col number)")
return nil
}
}
func testGrantOnSchemaAddCleanUp() resource.TestCheckFunc {
return func(s *terraform.State) error {
client := testAccProvider.Meta().(*oracleHelperType).Client
client.DBClient.Exec("DROP TABLESYSTEM.TST_TBL1")
client.DBClient.Exec("DROP TABLE SYSTEM.TST_TBL2")
return nil
}
}
func testAccGrantObjPrivsOnSchemaConfigBasicDiff() string {
return `
resource "oraclerdbms_grant_object_privilege" "grantobjschematest" {
grantee = "${oraclerdbms_user.userobjpriv2.id}"
privilege = ["SELECT","UPDATE"]
owner = "SYSTEM"
object_type = "TABLE"
}
resource "oraclerdbms_user" "userobjpriv2" {
username = "USER99"
default_tablespace = "USERS"
}
`
}
const (
testAccGrantObjPrivsConfigBasic = `
resource "oraclerdbms_grant_object_privilege" "grantobjtest" {
grantee = "${oraclerdbms_user.userobjpriv.id}"
privilege = ["SELECT","UPDATE"]
owner = "SYSTEM"
object = "TEST"
}
resource "oraclerdbms_user" "userobjpriv" {
username = "USER999"
default_tablespace = "USERS"
}
`
testAccGrantObjPrivsConfigBasic2 = `
resource "oraclerdbms_grant_object_privilege" "grantobjtest" {
grantee = "${oraclerdbms_user.userobjpriv.id}"
privilege = ["SELECT"]
owner = "SYSTEM"
object = "TEST"
}
resource "oraclerdbms_user" "userobjpriv" {
username = "USER999"
default_tablespace = "USERS"
}
`
testAccGrantObjPrivsOnSchemaConfigBasic = `
resource "oraclerdbms_grant_object_privilege" "grantobjschematest" {
grantee = "${oraclerdbms_user.userobjpriv2.id}"
privilege = ["SELECT","UPDATE"]
owner = "SYSTEM"
object_type = "TABLE"
}
resource "oraclerdbms_user" "userobjpriv2" {
username = "USER99"
default_tablespace = "USERS"
}
`
testAccGrantObjPrivsOnSchemaConfigBasic2 = `
resource "oraclerdbms_grant_object_privilege" "grantobjschematest" {
grantee = "${oraclerdbms_user.userobjpriv2.id}"
privilege = ["SELECT"]
owner = "SYSTEM"
object_type = "TABLE"
}
resource "oraclerdbms_user" "userobjpriv2" {
username = "USER99"
default_tablespace = "USERS"
}
`
)
<file_sep>package oraclerdbms
import (
"fmt"
"log"
"strings"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceStats() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateStats,
Delete: resourceOracleRdbmsDeleteStats,
Read: resourceOracleRdbmsReadStats,
Update: resourceOracleRdbmsUpdateStats,
Schema: map[string]*schema.Schema{
"preference_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"owner_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"table_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"preference_value": &schema.Schema{
Type: schema.TypeString,
Required: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
},
}
}
func resourceOracleRdbmsCreateStats(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsCreateStats")
client := meta.(*oracleHelperType).Client
switch {
case d.Get("owner_name").(string) == "" && d.Get("table_name").(string) == "":
log.Println("[DEBUG] global")
resourceStats := oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
Pvalu: d.Get("preference_value").(string),
}
err := client.StatsService.SetGlobalPre(resourceStats)
if err != nil {
d.SetId("")
return err
}
id := fmt.Sprintf("STATS-GLOBAL-%s", d.Get("preference_name").(string))
d.SetId(id)
case d.Get("owner_name").(string) != "" && d.Get("table_name").(string) == "":
log.Println("[DEBUG] schema")
resourceStats := oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
OwnName: d.Get("owner_name").(string),
Pvalu: d.Get("preference_value").(string),
}
err := client.StatsService.SetSchemaPre(resourceStats)
if err != nil {
d.SetId("")
return err
}
id := fmt.Sprintf("STATS-%s-%s", d.Get("owner_name").(string), d.Get("preference_name").(string))
d.SetId(id)
case d.Get("owner_name").(string) != "" && d.Get("table_name").(string) != "":
log.Println("[DEBUG] table")
resourceStats := oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
OwnName: d.Get("owner_name").(string),
TaBName: d.Get("table_name").(string),
Pvalu: d.Get("preference_value").(string),
}
err := client.StatsService.SetTabPre(resourceStats)
if err != nil {
d.SetId("")
return err
}
id := fmt.Sprintf("STATS-TABLE-%s-%s", d.Get("table_name").(string), d.Get("preference_name").(string))
d.SetId(id)
}
return nil
}
func resourceOracleRdbmsDeleteStats(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsDeleteStats")
client := meta.(*oracleHelperType).Client
switch {
case d.Get("owner_name").(string) == "" && d.Get("table_name").(string) == "":
log.Println("[DEBUG] global")
/*
No solution how to reset a parameter global to default :/
DBMS_STATS.RESET_GLOBAL_PREF_DEFAULTS; resets all parameters to default :/
*/
case d.Get("owner_name").(string) != "" && d.Get("table_name").(string) == "":
log.Println("[DEBUG] schema")
resourceStats := oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
}
result, err := client.StatsService.ReadGlobalPre(resourceStats)
if err != nil {
d.SetId("")
return err
}
err = client.StatsService.SetSchemaPre(oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
OwnName: d.Get("owner_name").(string),
Pvalu: result.Pvalu,
})
if err != nil {
d.SetId("")
return err
}
case d.Get("owner_name").(string) != "" && d.Get("table_name").(string) != "":
log.Println("[DEBUG] table")
resourceStats := oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
}
result, err := client.StatsService.ReadGlobalPre(resourceStats)
if err != nil {
d.SetId("")
return err
}
err = client.StatsService.SetTabPre(oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
OwnName: d.Get("owner_name").(string),
TaBName: d.Get("table_name").(string),
Pvalu: result.Pvalu,
})
if err != nil {
d.SetId("")
return err
}
}
return nil
}
func resourceOracleRdbmsReadStats(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsReadStats")
client := meta.(*oracleHelperType).Client
switch {
case d.Get("owner_name").(string) == "" && d.Get("table_name").(string) == "":
log.Println("[DEBUG] global")
resourceStats := oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
}
result, err := client.StatsService.ReadGlobalPre(resourceStats)
if err != nil {
d.SetId("")
return err
}
d.Set("preference_value", result.Pvalu)
case d.Get("owner_name").(string) != "" && d.Get("table_name").(string) == "":
log.Println("[DEBUG] schema")
/*
Oracle have no support for this
*/
case d.Get("owner_name").(string) != "" && d.Get("table_name").(string) != "":
log.Println("[DEBUG] table")
resourceStats := oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
OwnName: d.Get("owner_name").(string),
TaBName: d.Get("table_name").(string),
}
result, err := client.StatsService.ReadTabPref(resourceStats)
if err != nil {
d.SetId("")
return err
}
d.Set("preference_value", result.Pvalu)
}
return nil
}
func resourceOracleRdbmsUpdateStats(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsUpdateStats")
client := meta.(*oracleHelperType).Client
switch {
case d.Get("owner_name").(string) == "" && d.Get("table_name").(string) == "":
log.Println("[DEBUG] global")
resourceStats := oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
Pvalu: d.Get("preference_value").(string),
}
err := client.StatsService.SetGlobalPre(resourceStats)
if err != nil {
d.SetId("")
return err
}
case d.Get("owner_name").(string) != "" && d.Get("table_name").(string) == "":
log.Println("[DEBUG] schema")
resourceStats := oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
OwnName: d.Get("owner_name").(string),
Pvalu: d.Get("preference_value").(string),
}
err := client.StatsService.SetSchemaPre(resourceStats)
if err != nil {
d.SetId("")
return err
}
case d.Get("owner_name").(string) != "" && d.Get("table_name").(string) != "":
log.Println("[DEBUG] table")
resourceStats := oraclehelper.ResourceStats{
Pname: d.Get("preference_name").(string),
OwnName: d.Get("owner_name").(string),
TaBName: d.Get("table_name").(string),
Pvalu: d.Get("preference_value").(string),
}
err := client.StatsService.SetTabPre(resourceStats)
if err != nil {
d.SetId("")
return err
}
}
return nil
}
<file_sep>package oraclerdbms
import (
"fmt"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"log"
"strings"
)
func resourceDatabase() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateDatabase,
Delete: resourceOracleRdbmsDeleteDatabase,
Read: resourceOracleRdbmsReadDatabase,
Update: resourceOracleRdbmsUpdateDatabase,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"forcelogging": &schema.Schema{
Type: schema.TypeString,
Required: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) {
v := strings.ToUpper(val.(string))
if !(v == "NO" || v == "YES") {
errs = append(errs, fmt.Errorf("%q must be YES or NO, got: %s", key, v))
}
return
},
},
"flashback": &schema.Schema{
Type: schema.TypeString,
Required: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) {
v := strings.ToUpper(val.(string))
if !(v == "YES" || v == "NO") {
errs = append(errs, fmt.Errorf("%q must be YES or NO, got: %s", key, v))
}
return
},
},
},
}
}
func resourceOracleRdbmsCreateDatabase(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsCreateDatabase")
client := meta.(*oracleHelperType).Client
resourceDatabase := oraclehelper.ResourceDatabase{
ForceLogging: d.Get("forcelogging").(string),
FlashBackOn: d.Get("flashback").(string),
}
err := client.DatabaseService.ModifyDatabase(resourceDatabase)
if err != nil {
return err
}
database, _ := client.DatabaseService.ReadDatabase()
d.SetId(database.Name)
return nil
}
func resourceOracleRdbmsDeleteDatabase(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsDeleteDatabase")
return nil
}
func resourceOracleRdbmsReadDatabase(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsReadDatabase")
client := meta.(*oracleHelperType).Client
resourceDatabase, err := client.DatabaseService.ReadDatabase()
if err != nil {
return err
}
d.Set("flashback", resourceDatabase.FlashBackOn)
d.Set("forcelogging", resourceDatabase.ForceLogging)
return nil
}
func resourceOracleRdbmsUpdateDatabase(d *schema.ResourceData, meta interface{}) error {
log.Println("[DEBUG] resourceOracleRdbmsUpdateDatabase")
client := meta.(*oracleHelperType).Client
resourceDatabase := oraclehelper.ResourceDatabase{}
if d.HasChange("flashback") {
resourceDatabase.FlashBackOn = d.Get("flashback").(string)
}
if d.HasChange("forcelogging") {
resourceDatabase.ForceLogging = d.Get("forcelogging").(string)
}
err := client.DatabaseService.ModifyDatabase(resourceDatabase)
if err != nil {
return err
}
return nil
}
<file_sep>package oraclerdbms
import (
"fmt"
"log"
"strings"
"github.com/dbgeek/terraform-oracle-rdbms-helper/oraclehelper"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceGrantObjectPrivilege() *schema.Resource {
return &schema.Resource{
Create: resourceOracleRdbmsCreateGrantObjectPrivilege,
Delete: resourceOracleRdbmsDeleteGrantObjectPrivilege,
Read: resourceOracleRdbmsReadGrantObjectPrivilege,
Update: nil,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
CustomizeDiff: updateComputed,
SchemaVersion: 1,
MigrateState: resourceOracleRdbmsGrantObjectPrivilegeMigrate,
Schema: map[string]*schema.Schema{
"grantee": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"owner": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.ToLower(old) == strings.ToLower(new)
},
},
"object": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"object_type": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
"privilege": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Required: true,
ForceNew: true,
StateFunc: func(val interface{}) string {
return strings.ToUpper(val.(string))
},
},
// This need to be changes to TypeSet. There is mutiple of privileges that need to be checked. Now only support SELECT
"objects_sha256": &schema.Schema{
Type: schema.TypeMap,
Elem: &schema.Schema{Type: schema.TypeString},
ForceNew: true,
Computed: true,
},
// This need to be changes to TypeSet. There is mutiple of privileges that need to be checked. Now only support SELECT
"privs_sha256": &schema.Schema{
Type: schema.TypeMap,
Elem: &schema.Schema{Type: schema.TypeString},
ForceNew: true,
Computed: true,
},
},
}
}
func updateComputed(d *schema.ResourceDiff, meta interface{}) error {
log.Println("[INFO] updateComputed")
if d.Get("object").(string) == "" {
log.Println("[INFO] updateComputed inside sha256 calc")
objMap := map[string]string{}
if v, ok := d.GetOk("objects_sha256"); ok {
for key, value := range v.(map[string]interface{}) {
objMap[key] = value.(string)
}
}
privsMap := map[string]string{}
if v, ok := d.GetOk("privs_sha256"); ok {
for key, value := range v.(map[string]interface{}) {
privsMap[key] = value.(string)
}
}
for k, v := range objMap {
if privsMap[k] != v {
d.SetNewComputed("objects_sha256")
d.SetNewComputed("privs_sha256")
break
}
}
}
/*if d.Get("privs_sha256").(string) != d.Get("objects_sha256").(string) {
d.SetNewComputed("objects_sha256")
d.SetNewComputed("privs_sha256")
}*/
//log.Printf("[DEBUG] updateComputed,privs_sha256: %s, objects_sha256: %s\n", d.Get("privs_sha256").(string), d.Get("objects_sha256").(string))
return nil
}
func resourceOracleRdbmsCreateGrantObjectPrivilege(d *schema.ResourceData, meta interface{}) error {
log.Println("[INFO] resourceOracleRdbmsCreateGrantObjectPrivilege")
var privilegesList []string
client := meta.(*oracleHelperType).Client
rawPrivileges := d.Get("privilege")
rawPrivilegesList := rawPrivileges.(*schema.Set).List()
for _, v := range rawPrivilegesList {
str := v.(string)
privilegesList = append(privilegesList, str)
}
/*
If object attribute is set the we do the privilege on object level
*/
if d.Get("object").(string) != "" {
log.Println("[INFO] resourceOracleRdbmsCreateGrantObjectPrivilege Object level flow")
resourceGrantObjectPrivilege := oraclehelper.ResourceGrantObjectPrivilege{
Grantee: d.Get("grantee").(string),
Owner: d.Get("owner").(string),
ObjectName: d.Get("object").(string),
Privilege: privilegesList,
}
err := client.GrantService.GrantObjectPrivilege(resourceGrantObjectPrivilege)
if err != nil {
d.SetId("")
return err
}
id := grantObjectPrivID(d.Get("grantee").(string), d.Get("owner").(string), d.Get("object").(string))
d.SetId(id)
return resourceOracleRdbmsReadGrantObjectPrivilege(d, meta)
}
/*
initial we only handle object_type = TABLE for privileges on schema level.
*/
switch {
case d.Get("object_type").(string) == "TABLE":
resourceGrantObjectPrivilege := oraclehelper.ResourceGrantObjectPrivilege{
Grantee: d.Get("grantee").(string),
Owner: d.Get("owner").(string),
ObjectName: d.Get("object").(string),
Privilege: privilegesList,
}
err := client.GrantService.GrantTableSchemaToUser(resourceGrantObjectPrivilege)
if err != nil {
d.SetId("")
return err
}
id := grantObjectPrivID(d.Get("grantee").(string), d.Get("owner").(string), d.Get("object").(string))
//var hash map[string]string
hash := make(map[string]string)
for _, v := range privilegesList {
hash[v], err = client.GrantService.GetHashSchemaPrivsToUser(oraclehelper.ResourceGrantObjectPrivilege{
Grantee: d.Get("grantee").(string),
Owner: d.Get("owner").(string),
ObjectName: d.Get("object").(string),
Privilege: []string{v},
})
if err != nil {
return err
}
}
d.Set("objects_sha256", hash)
d.Set("privs_sha256", hash)
id = grantObjectPrivID(d.Get("grantee").(string), d.Get("owner").(string), d.Get("owner").(string)) // hash)
d.SetId(id)
return resourceOracleRdbmsReadGrantObjectPrivilege(d, meta)
}
return nil
}
func resourceOracleRdbmsDeleteGrantObjectPrivilege(d *schema.ResourceData, meta interface{}) error {
log.Println("[INFO] resourceOracleRdbmsDeleteGrantObjectPrivilege")
var privilegesList []string
client := meta.(*oracleHelperType).Client
rawPrivileges := d.Get("privilege")
rawPrivilegesList := rawPrivileges.(*schema.Set).List()
for _, v := range rawPrivilegesList {
str := v.(string)
privilegesList = append(privilegesList, str)
}
if d.Get("object").(string) != "" {
resourceGrantObjectPrivilege := oraclehelper.ResourceGrantObjectPrivilege{
Grantee: d.Get("grantee").(string),
Owner: d.Get("owner").(string),
ObjectName: d.Get("object").(string),
Privilege: privilegesList,
}
err := client.GrantService.RevokeObjectPrivilege(resourceGrantObjectPrivilege)
if err != nil {
return err
}
return nil
}
resourceGrantObjectPrivilege := oraclehelper.ResourceGrantObjectPrivilege{
Grantee: d.Get("grantee").(string),
Owner: d.Get("owner").(string),
Privilege: privilegesList,
}
err := client.GrantService.RevokeTableSchemaFromUser(resourceGrantObjectPrivilege)
if err != nil {
return err
}
return nil
}
func resourceOracleRdbmsReadGrantObjectPrivilege(d *schema.ResourceData, meta interface{}) error {
log.Printf("[INFO] resourceOracleRdbmsReadGrantObjectPrivilege grantee:%s\n", d.Get("grantee"))
var privilegesList []string
rawPrivileges := d.Get("privilege")
rawPrivilegesList := rawPrivileges.(*schema.Set).List()
for _, v := range rawPrivilegesList {
str := v.(string)
privilegesList = append(privilegesList, str)
}
client := meta.(*oracleHelperType).Client
splitGrantObjectPrivilege := strings.Split(d.Id(), "-")
grantee := splitGrantObjectPrivilege[0]
owner := splitGrantObjectPrivilege[1]
object := splitGrantObjectPrivilege[2]
/*
If object attribute is set the we do the privilege on object level or if owner & grantee not set
we asume that we trying to import a resource
*/
if d.Get("object").(string) != "" || (d.Get("owner").(string) == "" && d.Get("grantee").(string) == "") {
log.Printf("[INFO] resourceOracleRdbmsReadGrantObjectPrivilege inside object level")
resourceGrantObjectPrivilege := oraclehelper.ResourceGrantObjectPrivilege{
Grantee: grantee,
Owner: owner,
ObjectName: object,
}
grantedObject, err := client.GrantService.ReadGrantObjectPrivilege(resourceGrantObjectPrivilege)
if err != nil {
log.Printf("[INFO] ReadGrantObjectPrivilege failed with error: %v", err)
d.SetId("")
return err
}
log.Printf("[INFO] ReadGrantObjectPrivilege returned: %v\n", grantedObject)
d.Set("grantee", grantee)
d.Set("owner", owner)
d.Set("object", object)
d.Set("privilege", grantedObject.Privileges)
objHash := make(map[string]string)
privHash := make(map[string]string)
for _, v := range grantedObject.Privileges {
objHash[v] = owner
privHash[v] = object
}
d.Set("objects_sha256", objHash)
d.Set("privs_sha256", privHash)
return nil
}
/*
Doing the privilege on schema level. For now we only handle tables on schema level
*/
log.Println("[INFO] resourceOracleRdbmsReadGrantObjectPrivilege schema level")
switch {
case d.Get("object_type").(string) == "TABLE":
log.Println("[INFO] resourceOracleRdbmsReadGrantObjectPrivilege schema level on table level")
privsHash := make(map[string]string)
tableHash := make(map[string]string)
for _, v := range privilegesList {
resourceGrantObjectPrivilege := oraclehelper.ResourceGrantObjectPrivilege{
Grantee: grantee,
Owner: owner,
Privilege: []string{v},
}
pHash, err := client.GrantService.GetHashSchemaPrivsToUser(resourceGrantObjectPrivilege)
privsHash[v] = pHash
log.Printf("[INFO] resourceOracleRdbmsReadGrantObjectPrivilege hash: %s object: %s \n", privsHash, object)
if err != nil {
return err
}
tableHash[v], err = client.GrantService.GetHashSchemaAllTables(resourceGrantObjectPrivilege)
if err != nil {
return err
}
if !d.IsNewResource() {
d.Set("objects_sha256", tableHash)
d.Set("privs_sha256", privsHash)
}
}
return nil
}
return nil
}
func grantObjectPrivID(grantee string, owner string, object string) string {
return fmt.Sprintf("%s-%s-%s", grantee, owner, object)
}
<file_sep>package oraclerdbms
import (
"fmt"
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)
func TestAccParameter(t *testing.T) {
fmt.Println("[INFO] TestAccParameter")
var parameterRsID string
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccParameterCheckDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccParameterConfigBasic,
Check: resource.ComposeTestCheckFunc(testAccParameterCheck(
"oraclerdbms_parameter.test", ¶meterRsID),
),
},
resource.TestStep{
Config: testAccParameterConfigBasic2,
Check: resource.ComposeTestCheckFunc(
testAccParameterCheck("oraclerdbms_parameter.test", ¶meterRsID),
resource.TestCheckResourceAttr("oraclerdbms_parameter.test", "value", "444"),
),
},
},
})
}
func testAccParameterCheck(rn string, name *string) resource.TestCheckFunc {
return func(s *terraform.State) error {
fmt.Println("[INFO] testAccParameterCheck")
rs, ok := s.RootModule().Resources[rn]
if !ok {
return fmt.Errorf("resource not found: %s", rn)
}
if rs.Primary.ID == "" {
return fmt.Errorf("parameter id not set")
}
fmt.Printf("[INFO] rn: %v \n", rn)
*name = rs.Primary.ID
return nil
}
}
func testAccParameterCheckDestroy(s *terraform.State) error {
fmt.Println("[INFO] testAccParameterCheckDestroy")
for _, rs := range s.RootModule().Resources {
fmt.Printf("[INFO] resource type: %v \n", rs.Primary.Attributes)
if rs.Type != "oraclerdbms_parameter" {
fmt.Println("[INFO] rs type != oraclerdbms_parameter")
continue
}
}
return nil
}
func TestAccParameter_importBasic(t *testing.T) {
resourceName := "oraclerdbms_parameter.test"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccParameterConfigBasic,
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
const testAccParameterConfigBasic = `
resource "oraclerdbms_parameter" "test" {
name = "undo_retention"
value = "666"
}
`
const testAccParameterConfigBasic2 = `
resource "oraclerdbms_parameter" "test" {
name = "undo_retention"
value = "444"
update_comment = "acc test of comment"
}
`
<file_sep>package oraclerdbms
import (
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
func TestAccGrantSysPrivs(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccGrantSysPrivsConfigBasic,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_grant_system_privilege.grantsysprivs", "privilege", "CREATE SESSION"),
),
},
},
})
}
func TestAccGrantSysPrivs_importBasic(t *testing.T) {
resourceName := "oraclerdbms_grant_system_privilege.grantsysprivs"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccGrantSysPrivsConfigBasic,
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
const testAccGrantSysPrivsConfigBasic = `
resource "oraclerdbms_grant_system_privilege" "grantsysprivs" {
grantee = "${oraclerdbms_user.usersyspriv.id}"
privilege = "CREATE SESSION"
}
resource "oraclerdbms_user" "usersyspriv" {
username = "USER999"
default_tablespace = "USERS"
}
`
<file_sep>package oraclerdbms
import (
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)
func TestAccProfileLimit(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccProfileLimitConfigBasic,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("oraclerdbms_profile_limit.test1", "value", "33"),
),
},
},
})
}
func TestAccProfileLimit_importBasic(t *testing.T) {
resourceName := "oraclerdbms_profile_limit.test1"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccProfileLimitConfigBasic,
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
const testAccProfileLimitConfigBasic = `
resource "oraclerdbms_profile" "test1" {
profile = "TEST666"
}
resource "oraclerdbms_profile_limit" "test1" {
resource_name = "IDLE_TIME"
value = "33"
profile = "${oraclerdbms_profile.test1.id}"
}
`
| 60c38c98d95b311e3ab388e898cf4f0611347956 | [
"Markdown",
"Go",
"Go Module",
"Dockerfile",
"Shell"
]
| 33 | Dockerfile | dbgeek/terraform-provider-oraclerdbms | 467d5cf3e6ebd896bf8375a6312afef969ff89b5 | cc3d07517f510704171e2f6575f726261c0081f9 |
refs/heads/master | <file_sep># https://satijalab.org/seurat/v3.0/pbmc3k_tutorial.html
### This is more or less I first attemp to do a Seurat Pipeline.
## coming soon.
<file_sep>## walkthrough installation of required software and R packages
############## Software installation ##############
## get miniconda3
wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh
bash miniconda.sh
## add to .bashrc
export PATH=/home/gascui/miniconda3/bin:$PATH
# make sure to have correct python and conda
which conda
which python
## install R
conda install -c r r
## install Jupyter Labs
conda install -c conda-forge jupyterlab
## run jupyter labs and create jupyter notebook
jupyter lab --no-browser --port 2323 &
## install R kernel for jupyter
conda install -c r r-irkernel
## check everything
which conda
which R
which python
which jupyter
############## Seurat 3.0 installation ##############
## install Seurat 3.0 ##
install.packages('devtools')
devtools::install_github(repo = 'satijalab/seurat', ref = 'release/3.0')
### If you have a problem with Seurat dependencies to 'hdf5r', this is a go-around solution. Worked for me.
install.packages("remotes")
remotes::install_github("UCSF-TI/fake-hdf5r")
devtools::install_github(repo = 'satijalab/seurat', ref = 'release/3.0')
library('Seurat')
#### install UMAP in python ####
pip install umap-learn
### More to come.
<file_sep># single_cell
A desperate attemp to do bioinformatics
<file_sep>post your notebooks here =)
| 7bbef4dd00c8bd81f2ec9ceb9738ba0134fb75d6 | [
"Markdown",
"R"
]
| 4 | R | gabrielascui/single_cell | 11a147557dce2c101658c7d6fee24ec0c7a3b59e | f6f5d256499511a50afdee732f5415f0f66fa88d |
refs/heads/main | <file_sep>const initialState = {count : 0, data: "hardik"};
function appReducer (state=initialState, action) {
switch(action.type) {
case 'Increment_async':
return {
count: state.count + 1,
data: action.payload
};
case 'Decrement_async':
return {count: state.count - 1, data: action.payload};
default:
return state
}
}
export default appReducer;<file_sep>import {combineReducers} from 'redux';
import appReducer from './reducer';
import loggedReducer from './logged';
const rootReducer = combineReducers({
counterState:appReducer,
loggedState:loggedReducer
});
export default rootReducer;<file_sep>import React, { useState } from 'react';
import { Formik, Field, Form, ErrorMessage, FormikConfig, FormikValues } from 'formik';
import * as Yup from 'yup';
import '../App.css';
const SignupForm = () => {
return (
<FormikStepper
initialValues={{ firstName: '', lastName: '', email: '' }}
// onSubmit={() => {
// // setTimeout(() => {
// // alert(JSON.stringify(values, null, 2));
// // setSubmitting(false);
// // }, 400);
// }}
>
<div validationschema={Yup.object({
firstName: Yup.string()
.max(15, 'Must be 15 characters or less')
.required('firstName Required'),
lastName: Yup.string()
.max(20, 'Must be 20 characters or less')
.required('lastName Required'),
email: Yup.string()
.email('Invalid email address')
.required('email Required')
})}>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" type="text" />
<span className="error"><ErrorMessage name="firstName" /></span>
<label htmlFor="lastName">Last Name</label>
<Field name="lastName" type="text" />
<span className="error"><ErrorMessage name="lastName" /></span>
<label htmlFor="email">Email Address</label>
<Field name="email" type="email" />
<span className="error"><ErrorMessage name="email" /></span>
</div>
<div validationschema={Yup.object({
money: Yup.number().when('millions', {
is: true,
then: Yup.number().required().min(1_000_000, 'ache se daal tu miillionier h'),
otherwise: Yup.number().required()
})
})}>
<label htmlFor="millions">Are you Millionier</label>
<Field name="millions" id="millions" type="checkbox"/>
<span className="error"><ErrorMessage name="millions" /></span>
<label htmlFor="money">Enter Money</label>
<Field name="money" type="number" />
<span className="error"><ErrorMessage name="money" /></span>
</div>
<div validationschema={Yup.object({
desc: Yup.string().required('desc required')
})}>
<label htmlFor="desc">Address</label>
<Field name="desc" type="text" />
<span className="error"><ErrorMessage name="desc" /></span>
</div>
</FormikStepper>
);
};
export default SignupForm;
// export function FormikSteps({children, ...props}) {
// return <>{children}</>
// }
export function FormikStepper({children, ...props}) {
const childrenArr = React.Children.toArray(children);
const [steps, setSteps] = useState(0);
const currentChild = childrenArr[steps];
function checkLastStep() {
return steps === childrenArr.length -1;
}
console.log(currentChild);
return (
<Formik {...props}
validationSchema = {currentChild.props.validationschema}
onSubmit={async (values, helper) =>{
console.log(steps, '---------------------------------------------> on submit')
if(checkLastStep()) {
await props.onSubmit(values, helper)
} else {
setSteps((steps) => steps+1)
}
}}>
<Form autoComplete="off">
{currentChild}
{steps > 0 ? <button type="button" onClick={() => setSteps((s) => s-1)}>Back</button> : null}
<button type="submit">{checkLastStep() ? 'Submit' : 'next'}</button>
</Form>
</Formik>
)
} <file_sep>
import { put, takeEvery, call, takeLatest, all } from 'redux-saga/effects';
//const delay = (ms) => new Promise(res => setTimeout(res, ms))
// ...
// Our worker Saga: will perform the async increment task
export function* incrementAsync(data) {
// yield delay(1000)
yield put({ type: 'Increment_async', payload: data.payload })
}
export function* decrementAsync() {
//yield delay(1000);
let data = yield call(function() {
let data = fetch('https://jsonplaceholder.typicode.com/users').then(response => response.json())
let adata = data.then(json => {
return json;
});
return adata;
});
console.log(data, 'dldljd');
yield put({ type: 'Decrement_async', payload: data[0].name})
}
export function* loggedStatusAsync(data) {
yield put({ type: 'loggedStatus_async', payload: data.payload})
}
// Our watcher Saga: spawn a new incrementAsync task on each INCREMENT_ASYNC
export function* watch() {
yield takeEvery('Increment', incrementAsync);
yield takeLatest('Decrement', decrementAsync);
}
export function* noWatch() {
yield takeEvery('loggedStatus', loggedStatusAsync)
}
export function* rootSaga() {
yield all([
watch(),
noWatch()
])
}<file_sep>const initialState = {
loggedStatus : false,
loggeddata: {
username: '',
password: ''
}
};
function loggedReducer (state=initialState, action) {
switch(action.type) {
case 'loggedStatus_async':
return {
loggedStatus: !state.loggedStatus,
loggeddata: action.payload
};
default:
return state
}
}
export default loggedReducer; | f09e389e47467eb37f977ba06cc5081b2310cccb | [
"JavaScript"
]
| 5 | JavaScript | Gauravuidev/ReactReduxSaga | 8a44b4243402f4a7e4bb452b4e1608d972e5ae24 | 96990a6cc4796dcb3a6cc81b00787887abd8363f |
refs/heads/master | <file_sep>/**
* 加密解密参数模块
* @type {[type]}
*/
const enc = require('./encrypt.js');
/* 加密参数方法 第一个参数传变量名,第二个参数传变量值 */
function aesEncryptData(...args) { // 接收变量名
const varName = args[0];
// 接收变量值
const varValue = args[1];
// 调用方法获得公共参数
const data = enc.commonData();
// 引入加密算法
const Encrypt = enc.encrypt;
// 创建一个加密的对象(先清空)
let aesArr = { ...data[5] };
// 循环传入的所有参数
for (let i = 0, len = varValue.length; i < len; i += 1) {
varValue[i] = new Encrypt(data[0], data[1], data[2], data[3], data[4], varValue[i]);
aesArr[varName[i]] = varValue[i].aesEncrypt();
}
const resultArr = [
aesArr, varValue[0],
];
return resultArr;
}
/* 解密参数方法 第一个参数传变量名,第二个参数传变量值 */
function aesDecryptData(aes, data) {
return aes.aesDecrypt(data);
}
module.exports = {
aesEncrypt: aesEncryptData,
aesDecrypt: aesDecryptData,
};
<file_sep>/* global React */
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
import { navData } from '../navs/youwen';
require('../polyfill'); // 兼容性垫片
class App extends React.Component {
render() {
return (
<Switch>
{
navData.map(value =>
(
<Route
key={value.title}
exact={value.exact}
component={value.component}
path={value.path}
/>
)
)
}
{/* 404页面 */}
{/* <Route component={Component404} path='/404' />
<Redirect from='*' to='/404' /> */}
</Switch>
);
}
}
// 使用默认的确认函数
const getConfirmation = (message, callback) => {
console.log(message);
const allowTransition = window.confirm(message);
callback(allowTransition);
};
ReactDOM.render(
<Router getUserConfirmation={getConfirmation} basename="/youwen">
<App />
</Router>
, document.getElementById('youwen'));
<file_sep>const sha = require('./sha256.min.js');
const CryptoJS = require('./crypto.min.js');
function encrypt(openid, Timestamp, t, alias, seq, data) {
this.openid = openid;
this.Timestamp = Timestamp;
this.t = t;
this.alias = alias;
this.seq = seq;
this.parameter = '';
this.key = '';
this.keyMake = '';
this.data = data;
this.encrypted = '';
this.encrypt = '';
this.decrypt = '';
}
encrypt.prototype.getKey = () => {
for (let i = 0; i < 4; i += 1) {
if (this.seq.substring(i, i + 1) === '1') {
this.key += this.openid;
} else if (this.seq.substring(i, i + 1) === '2') {
this.key += this.Timestamp;
} else if (this.seq.substring(i, i + 1) === '3') {
this.key += this.t;
} else if (this.seq.substring(i, i + 1) === '4') {
this.key += this.alias;
}
}
this.key = sha.hex_sha256(this.key).substring(0, 16);
this.keyMake = this.key;
this.key = CryptoJS.enc.Utf8.parse(this.key);
};
encrypt.prototype.aesEncrypt = () => {
this.getKey();
this.data = CryptoJS.enc.Utf8.parse(this.data);
this.encrypted = CryptoJS.AES.encrypt(this.data, this.key, {
iv: this.key,
mode: CryptoJS.mode.CBC,
});
this.encrypted = this.encrypted.ciphertext.toString();
return this.encrypted;
};
encrypt.prototype.aesDecrypt = (data) => {
this.encrypt = data;
this.encrypt = CryptoJS.enc.Hex.parse(this.encrypt);
this.encrypt = CryptoJS.enc.Base64.stringify(this.encrypt);
this.decrypt = CryptoJS.AES.decrypt(this.encrypt, this.key, {
iv: this.key,
mode: CryptoJS.mode.CBC,
});
this.decrypt = CryptoJS.enc.Utf8.stringify(this.decrypt).toString();
return this.decrypt;
};
// 生成三位1-3的随机数
function mathRandom4() {
let a = '';
for (let i = 0; i < 4; i += 1) {
a += parseInt((Math.random() * 4) + 1, 10);
}
return a;
}
// 传递公共参数
function commonEncryptData() {
let arrData = [];
// 调用方法
const newTime = new Date().getTime();
// 产生随机数
const randomNum = mathRandom4();
const t = localStorage.getItem('t') || '';
const alias = localStorage.getItem('alias') || '';
/* if(userMsg.v){
let v = userMsg.v;
}else{ */
const v = '';
/* } */
// 检测用户的token和alias是否存在 不存在就返回空值
/* if (userMsg.t) {
let t = userMsg.t;
let alias = userMsg.alias;
} else {
let t = '';
let alias = '';
} */
arrData = [
v,
newTime,
t,
alias,
randomNum, {
v,
tm: newTime,
t,
alias,
seq: randomNum,
},
];
return arrData;
}
module.exports = {
commonData: commonEncryptData,
encrypt,
};
<file_sep>import { Modal } from 'antd-mobile';
// const sha1 = require('sha1');
const { alert } = Modal;
// 判断访问终端和来源
export const getSystemInfo = () => {
const system = {
terminal: '',
};
// 终端
const u = navigator.userAgent;
const app = navigator.appVersion;
if (u.toLowerCase().indexOf('micromessenger') > -1) { // 微信端
system.terminal = 'WX';
} else if (!!u.match(/(iPhone|iPod|Android|ios)/i)) { //移动终端
if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) { // ios
system.terminal = 'IOS';
} else if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) { // Android
system.terminal = 'Android';
}
} else { // PC端
system.terminal = 'PC';
}
return system;
};
// 公共地址
const { origin } = window.location;
export const commonUrl = origin.indexOf('localhost') !== -1 ? 'http://localhost:8080/localhost' : origin;
/**
* 配置一个每一个页面刚进入都需要调用的方法
* @param {String} title [需要更改的标题内容]
* @return {[type]} [description]
*/
export const enterPageFn = (title) => {
// 获取系统信息
const system = system();
// 更改网页title
document.title = title;
// 微信环境下根据微信SDk设置一些微信专有的功能
if (system.terminal === 'WX') {
jssdk();
}
};
// 通过微信SDK设置微信功能
export const jssdk = () => {
const guid = () => {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
};
// 获取js-sdk票据
/*Tool.request(
{},
'/app/token',
(data,textStatus) => {
let timestamp = parseInt((new Date().getTime())/1000)+'';
let noncestr = guid();
let sdkurl = window.location.href.split('#');
let singna = 'jsapi_ticket='+data+'&noncestr='+noncestr+'×tamp='+timestamp+'&url='+sdkurl[0];
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: 'wx5ef54e044b7e4ce5', // 必填,公众号的唯一标识
timestamp:timestamp, // 必填,生成签名的时间戳
nonceStr: noncestr, // 必填,生成签名的随机串
signature: sha1(singna).toUpperCase(),// 必填,签名,见附录1
jsApiList: [
'onMenuShareTimeline',
'onMenuShareAppMessage'
]
});
wx.ready(function(res) {
// 分享给朋友
wx.onMenuShareAppMessage({
title: '必达卡',
desc: document.title,
link: window.location.href,
imgUrl: 'https://oe7f0jikj.qnssl.com/biqu/web/bidaCard/src/small.jpeg'
});
// 分享到朋友圈
wx.onMenuShareTimeline({
title: document.title,
link: window.location.href,
imgUrl: 'https://oe7f0jikj.qnssl.com/biqu/web/bidaCard/src/small.jpeg',
});
});
},
'GET',
'text'
);*/
};
/**
* input输入值替换掉某个对象当中的相应字段值
* @param {String} value [input的输入值]
* @param {String} key [要替换的字段名]
* @param {Object} obj [要替换其中的字段的对象]
* @return {[type]} [description]
*/
export const changeValue = (value, key, obj) => {
obj[key] = value;
return obj;
};
// 验证手机号
export const expPhone = (phone) => {
let telReg = false;
if (phone) {
telReg = !!phone.match(/^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$/);
}
return telReg;
};
// 验证旅客姓名
export const expName = (name) => {
let Reg = false;
if (name) {
Reg = !!name.match(/^([a-zA-Z]{1,20}|[\u4e00-\u9fa5]{1,10})$/g);
}
return Reg;
};
// 验证票号
export const expTicketNo = (ticketNo) => {
let Reg = false;
if (ticketNo) {
Reg = !!ticketNo.match(/^\d{13}$/);
}
return Reg;
};
/**
* 通用弹框
* @param {String} content [需要显示的内容]
* @param {Func} cd [点击确定以后的回调]
* @return {[type]} [description]
*/
export const showAlert = (content, cb) => {
alert('温馨提示', content, [
{
text: '确定',
onPress: () => {
if (cb) {
cb();
}
},
},
]);
};
/**
* 实现对对象的深拷贝
* @param {Object} obj1 [原对象]
* @param {Object} [obj2={}] [需要拷贝到哪个对象中去,这个对象中的值将被追加或者覆盖]
* @return {Object} [description]
*/
export const objDeepcopy = (obj1, obj2 = {}) => {
for (let name in obj1) {
// 先判断一下obj[name]是不是一个对象
if (typeof obj1[name] === 'object') {
// 我们让要复制的对象的name项=数组或者是json
obj2[name] = (obj1[name].constructor === Array) ? [] : {};
// 然后来无限调用函数自己 递归思想
objDeepcopy(obj1[name], obj2[name]);
} else {
// 如果不是对象,直接等于即可,不会发生引用。
obj2[name] = obj1[name];
}
}
return obj2; // 然后在把复制好的对象给return出去
};
// 获取屏幕高度和宽度
export const getWindowHeight = () => {
const page = {
width: window.innerWidth,
height: window.innerHeight,
};
if (typeof page.width !== 'number') {
if (document.compatMode === 'number') {
page.width = document.documentElement.clientWidth;
page.height = document.documentElement.clientHeight;
} else {
page.width = document.body.clientWidth;
page.height = document.body.clientHeight;
}
}
return page;
};
<file_sep>const autoprefixer = require('autoprefixer');
const pxtorem = require('postcss-pxtorem');
module.exports = {
plugins: [
autoprefixer({
browsers: [
'> 1%',
'last 2 versions',
'Android >= 3.2',
'Firefox >= 20',
'iOS 7',
],
}),
pxtorem({
rootValue: 37.5,
// 忽略border相关属性
propList: ['*', '!border*', '!font-size*'],
}),
],
};
<file_sep>const path = require('path');
const webpack = require('webpack');
// css、less的共有loader
const commonCssUse = [
{
loader: 'style-loader',
}, {
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]',
},
}, {
loader: 'postcss-loader',
},
];
module.exports = {
context: path.join(__dirname, '/src'),
entry: {
youwen: './entries/youwen.js',
},
module: {
loaders: [
{
test: /\.js[x]?$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.css$/,
use: [...commonCssUse],
},
{
test: /\.less$/,
use: [
...commonCssUse,
{
loader: 'less-loader',
},
],
},
// svg-sprite for [email protected]
{
test: /\.(svg)$/i,
loader: 'svg-sprite-loader',
include: [require.resolve('antd-mobile').replace(/warn\.js$/, ''), // 1. 属于 antd-mobile 内置 svg 文件
// path.resolve(__dirname, 'src/my-project-svg-foler'), // 自己私人的 svg 存放目录
],
},
{
test: /\.(jpg|png)$/,
loader: 'url-loader',
},
],
},
output: {
path: path.join(__dirname, '/src/'),
filename: '[name].js',
},
resolve: {
modules: ['node_modules', path.join(__dirname, '../node_modules')],
extensions: ['.web.js', '.jsx', '.js', '.json'],
},
devServer: {
quiet: false, // 热更新不打印日志
historyApiFallback: { // 支持H5的history属性
rewrites: [
{ from: /^\/youwen/, to: 'src/pages/youwen.html' }, // 囿文
],
},
proxy: {
'/localhost': {
// target: "http://localhost:8950/",
target: 'http://dev.panatrip.cn:18950/',
pathRewrite: {
'^/localhost': '',
},
},
},
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
// 每个文件检测如果没有引入下列模块则自动require,路径就是每个文件的路径
new webpack.ProvidePlugin({
React: 'react',
PropTypes: 'prop-types',
// Tool: ['../../tools/tool', 'Tool'],
// Header: ['../common/header', 'default'],
is: ['immutable', 'is'],
fromJS: ['immutable', 'fromJS'],
// _data: ['../data/document', 'default'] // 所有项目中可变的文案
}),
],
};
<file_sep>function hex_sha256(a) {
return rstr2hex(rstr_sha256(str2rstr_utf8(a))) }
function b64_sha256(a) {
return rstr2b64(rstr_sha256(str2rstr_utf8(a))) }
function any_sha256(a, b) {
return rstr2any(rstr_sha256(str2rstr_utf8(a)), b) }
function hex_hmac_sha256(a, b) {
return rstr2hex(rstr_hmac_sha256(str2rstr_utf8(a), str2rstr_utf8(b))) }
function b64_hmac_sha256(a, b) {
return rstr2b64(rstr_hmac_sha256(str2rstr_utf8(a), str2rstr_utf8(b))) }
function any_hmac_sha256(a, b, c) {
return rstr2any(rstr_hmac_sha256(str2rstr_utf8(a), str2rstr_utf8(b)), c) }
function sha256_vm_test() {
return "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" == hex_sha256("abc").toLowerCase() }
function rstr_sha256(a) {
return binb2rstr(binb_sha256(rstr2binb(a), 8 * a.length)) }
function rstr_hmac_sha256(a, b) {
var d, e, f, g, c = rstr2binb(a);
for (c.length > 16 && (c = binb_sha256(c, 8 * a.length)), d = Array(16), e = Array(16), f = 0; 16 > f; f++) d[f] = 909522486 ^ c[f], e[f] = 1549556828 ^ c[f];
return g = binb_sha256(d.concat(rstr2binb(b)), 512 + 8 * b.length), binb2rstr(binb_sha256(e.concat(g), 768)) }
function rstr2hex(a) {
var c, d, e, f;
try {} catch (b) { hexcase = 0 }
for (c = hexcase ? "0123456789ABCDEF" : "0123456789abcdef", d = "", f = 0; f < a.length; f++) e = a.charCodeAt(f), d += c.charAt(15 & e >>> 4) + c.charAt(15 & e);
return d }
function rstr2b64(a) {
var c, d, e, f, g, h;
try {} catch (b) { b64pad = "" }
for (c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", d = "", e = a.length, f = 0; e > f; f += 3)
for (g = a.charCodeAt(f) << 16 | (e > f + 1 ? a.charCodeAt(f + 1) << 8 : 0) | (e > f + 2 ? a.charCodeAt(f + 2) : 0), h = 0; 4 > h; h++) d += 8 * f + 6 * h > 8 * a.length ? b64pad : c.charAt(63 & g >>> 6 * (3 - h));
return d }
function rstr2any(a, b) {
var e, f, g, h, j, k, c = b.length,
d = Array(),
i = Array(Math.ceil(a.length / 2));
for (e = 0; e < i.length; e++) i[e] = a.charCodeAt(2 * e) << 8 | a.charCodeAt(2 * e + 1);
for (; i.length > 0;) {
for (h = Array(), g = 0, e = 0; e < i.length; e++) g = (g << 16) + i[e], f = Math.floor(g / c), g -= f * c, (h.length > 0 || f > 0) && (h[h.length] = f);
d[d.length] = g, i = h }
for (j = "", e = d.length - 1; e >= 0; e--) j += b.charAt(d[e]);
for (k = Math.ceil(8 * a.length / (Math.log(b.length) / Math.log(2))), e = j.length; k > e; e++) j = b[0] + j;
return j }
function str2rstr_utf8(a) {
for (var d, e, b = "", c = -1; ++c < a.length;) d = a.charCodeAt(c), e = c + 1 < a.length ? a.charCodeAt(c + 1) : 0, d >= 55296 && 56319 >= d && e >= 56320 && 57343 >= e && (d = 65536 + ((1023 & d) << 10) + (1023 & e), c++), 127 >= d ? b += String.fromCharCode(d) : 2047 >= d ? b += String.fromCharCode(192 | 31 & d >>> 6, 128 | 63 & d) : 65535 >= d ? b += String.fromCharCode(224 | 15 & d >>> 12, 128 | 63 & d >>> 6, 128 | 63 & d) : 2097151 >= d && (b += String.fromCharCode(240 | 7 & d >>> 18, 128 | 63 & d >>> 12, 128 | 63 & d >>> 6, 128 | 63 & d));
return b }
function str2rstr_utf16le(a) {
var c, b = "";
for (c = 0; c < a.length; c++) b += String.fromCharCode(255 & a.charCodeAt(c), 255 & a.charCodeAt(c) >>> 8);
return b }
function str2rstr_utf16be(a) {
var c, b = "";
for (c = 0; c < a.length; c++) b += String.fromCharCode(255 & a.charCodeAt(c) >>> 8, 255 & a.charCodeAt(c));
return b }
function rstr2binb(a) {
var c, b = Array(a.length >> 2);
for (c = 0; c < b.length; c++) b[c] = 0;
for (c = 0; c < 8 * a.length; c += 8) b[c >> 5] |= (255 & a.charCodeAt(c / 8)) << 24 - c % 32;
return b }
function binb2rstr(a) {
var c, b = "";
for (c = 0; c < 32 * a.length; c += 8) b += String.fromCharCode(255 & a[c >> 5] >>> 24 - c % 32);
return b }
function sha256_S(a, b) {
return a >>> b | a << 32 - b }
function sha256_R(a, b) {
return a >>> b }
function sha256_Ch(a, b, c) {
return a & b ^ ~a & c }
function sha256_Maj(a, b, c) {
return a & b ^ a & c ^ b & c }
function sha256_Sigma0256(a) {
return sha256_S(a, 2) ^ sha256_S(a, 13) ^ sha256_S(a, 22) }
function sha256_Sigma1256(a) {
return sha256_S(a, 6) ^ sha256_S(a, 11) ^ sha256_S(a, 25) }
function sha256_Gamma0256(a) {
return sha256_S(a, 7) ^ sha256_S(a, 18) ^ sha256_R(a, 3) }
function sha256_Gamma1256(a) {
return sha256_S(a, 17) ^ sha256_S(a, 19) ^ sha256_R(a, 10) }
function sha256_Sigma0512(a) {
return sha256_S(a, 28) ^ sha256_S(a, 34) ^ sha256_S(a, 39) }
function sha256_Sigma1512(a) {
return sha256_S(a, 14) ^ sha256_S(a, 18) ^ sha256_S(a, 41) }
function sha256_Gamma0512(a) {
return sha256_S(a, 1) ^ sha256_S(a, 8) ^ sha256_R(a, 7) }
function sha256_Gamma1512(a) {
return sha256_S(a, 19) ^ sha256_S(a, 61) ^ sha256_R(a, 6) }
function binb_sha256(a, b) {
var e, f, g, h, i, j, k, l, m, n, o, p, c = new Array(1779033703, -1150833019, 1013904242, -1521486534, 1359893119, -1694144372, 528734635, 1541459225),
d = new Array(64);
for (a[b >> 5] |= 128 << 24 - b % 32, a[(b + 64 >> 9 << 4) + 15] = b, m = 0; m < a.length; m += 16) {
for (e = c[0], f = c[1], g = c[2], h = c[3], i = c[4], j = c[5], k = c[6], l = c[7], n = 0; 64 > n; n++) d[n] = 16 > n ? a[n + m] : safe_add(safe_add(safe_add(sha256_Gamma1256(d[n - 2]), d[n - 7]), sha256_Gamma0256(d[n - 15])), d[n - 16]), o = safe_add(safe_add(safe_add(safe_add(l, sha256_Sigma1256(i)), sha256_Ch(i, j, k)), sha256_K[n]), d[n]), p = safe_add(sha256_Sigma0256(e), sha256_Maj(e, f, g)), l = k, k = j, j = i, i = safe_add(h, o), h = g, g = f, f = e, e = safe_add(o, p);
c[0] = safe_add(e, c[0]), c[1] = safe_add(f, c[1]), c[2] = safe_add(g, c[2]), c[3] = safe_add(h, c[3]), c[4] = safe_add(i, c[4]), c[5] = safe_add(j, c[5]), c[6] = safe_add(k, c[6]), c[7] = safe_add(l, c[7]) }
return c }
function safe_add(a, b) {
var c = (65535 & a) + (65535 & b),
d = (a >> 16) + (b >> 16) + (c >> 16);
return d << 16 | 65535 & c }
var hexcase = 0,
b64pad = "",
sha256_K = new Array(1116352408, 1899447441, -1245643825, -373957723, 961987163, 1508970993, -1841331548, -1424204075, -670586216, 310598401, 607225278, 1426881987, 1925078388, -2132889090, -1680079193, -1046744716, -459576895, -272742522, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, -1740746414, -1473132947, -1341970488, -1084653625, -958395405, -710438585, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, -2117940946, -1838011259, -1564481375, -1474664885, -1035236496, -949202525, -778901479, -694614492, -200395387, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, -2067236844, -1933114872, -1866530822, -1538233109, -1090935817, -965641998);
module.exports = {
hex_sha256 : hex_sha256
};
<file_sep>const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const pxtorem = require('postcss-pxtorem');
const ExtractTextPlugin = require('extract-text-webpack-plugin'); // CSS提取插件
// 代码结构可视化工具
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
context: path.join(__dirname, '/src'),
entry: {
'bidacard/js/bundle': './bidacard/scripts/root.js',
'flight/js/bundle': './flight/scripts/root.js',
'lib/react': ['react', 'react-dom', 'react-router'],
'lib/redux': ['redux', 'redux-immutablejs', 'redux-thunk'],
},
module: {
loaders: [
{
test: /\.js[x]?$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
minimize: true, // css压缩
},
},
{
loader: 'postcss-loader',
options: {
plugins: () => [
autoprefixer({
browsers: [
'> 1%',
'last 2 versions',
'Android >= 3.2',
'Firefox >= 20',
'iOS 7',
],
}),
pxtorem({
rootValue: 100,
// 忽略border相关属性
propList: ['*', '!border*'],
}),
],
},
},
],
}),
},
// svg-sprite for [email protected]
{
test: /\.(svg)$/i,
loader: 'svg-sprite-loader',
include: [require.resolve('antd-mobile').replace(/warn\.js$/, ''), // 1. 属于 antd-mobile 内置 svg 文件
// path.resolve(__dirname, 'src/my-project-svg-foler'), // 自己私人的 svg 存放目录
],
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
minimize: true, // css压缩
},
},
{
loader: 'postcss-loader',
options: {
plugins: () => [
autoprefixer({
browsers: [
'> 1%',
'last 2 versions',
'Android >= 3.2',
'Firefox >= 20',
'iOS 7',
],
}),
pxtorem({
rootValue: 100,
// 忽略border相关属性
propList: ['*', '!border*'],
}),
],
},
},
{
loader: 'less-loader',
},
],
}),
},
{
test: /\.(jpg|png)$/,
loader: 'url-loader',
},
{
test: /\.html$/,
loader: 'html-loader',
},
],
},
resolve: {
modules: ['node_modules', path.join(__dirname, '../node_modules')],
extensions: ['.web.js', '.jsx', '.js', '.json'],
},
plugins: [
// new BundleAnalyzerPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
},
}),
new webpack.optimize.UglifyJsPlugin({ // 压缩代码
output: {
comments: false, // remove all comments(去掉所有注释)
},
compress: {
warnings: false,
drop_debugger: true,
drop_console: true,
},
mangle: {
except: ['$super', '$', 'exports', 'require', 'module', '_'], // 排除关键字
},
}),
new webpack.optimize.CommonsChunkPlugin({ // 提取公共代码
name: ['lib/react', 'lib/redux'],
minChunks: Infinity,
}),
// 每个文件检测如果没有引入下列模块则自动require,路径就是每个文件的路径
new webpack.ProvidePlugin({
React: 'react',
PropTypes: 'prop-types',
Tool: ['../../tools/tool', 'Tool'],
Header: ['../common/header', 'default'],
is: ['immutable', 'is'],
fromJS: ['immutable', 'fromJS'],
_data: ['../data/document', 'default'], // 所有项目中可变的文案
}),
],
};
<file_sep>import Login from '../routes/User/Login';
export const navData = [
{
title: '用户登录',
exact: true,
component: Login,
path: '/',
},
];
| 51ba7fb9bed64b90966b48c801147521d54b5ad6 | [
"JavaScript"
]
| 9 | JavaScript | troubleMakerrr/hreact-cli | 1a5de8e7f95da556b23ce60d5ceece719467aef6 | 70ebc987c87272c78a0dca0337d0b1de9eb10e60 |
refs/heads/master | <file_sep># Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = '<KEY>'
auth_token = '<PASSWORD>'
client = Client(account_sid, auth_token)
message = client.messages \
.create(
body="Company's twitter Account has reach threshold negative sentiment. Please check twitter ASAP!",
from_='+18572801622',
to='+17819990216'
)
print(message.sid)<file_sep>## Technical Report - Twitter Sentiment Dashboard
### Directory:
1. README.md
2. TweepyAdvanced (https://git.generalassemb.ly/ericpmwong/Capstone/blob/master/tweepyAdvanced.py)
3. TweepyAdvanced Jupyter Notebook (https://git.generalassemb.ly/ericpmwong/Capstone/blob/master/jupytertweepyAdvanced.ipynb)
4. plotly credentials (Hidden Files)
5. alert_sms (https://git.generalassemb.ly/ericpmwong/Capstone/blob/master/alert_sms.py)
6. twitter_cred (https://git.generalassemb.ly/ericpmwong/Capstone/blob/master/twittercred.py)
7. Slides (https://docs.google.com/presentation/d/1LoNRcWFnUxrF0klorwzVhAoHN7lDDOGhClo3VRLpEAs/edit?usp=sharing)
8. Link to Dashboard (https://plot.ly/dashboard/ericpmwong:80/present#/)
## Executive Problem
Our evolving social climate has added complexities to brand sentiment. Incidients involving high profile companies have recieved negative backlash for attempt at "positive" marketing campaigns or media messages. Traditional market testing methodologies are rendered less capable of encaspualting the social media's psychological diversity. Despite the large amount of investment in market testing, social platforms such as twitter are proving increasingly impactful and indicative of true underlying seniment.
## Twitter Sentiment Dashboard
"Twitter Sentiment Dashboard" is a realtime comprhensive and KPI indicator with emphasis on Public Relations damage control features. Underlying is an API streaming realtime twitter tweets and classifiying general "sentiment" (positive, negative or neutral). It will return the classified number of tweets as well as relative percentages. In the case of a misleading sentiment detction it includes most common key words which can reveal underlying sentiment negativity. In adddition, text messaging alerts of a potential PR issue. Tweets rolling means, convey a lagged indicator feedback to detect trend reversals of marketing actions.
<img src = "Dashboardex.gif">
###### Includes:
* General sentiment compiler
* Realtime list of commonly associated words (In case sentiment analyzer is deceptive)
* Instant Text messaging if negative tweets exceed set tolerance (Notifies 24/7)
* Moving average of average tweet to detect trend reversals (Can reveal success of damage control)
* Absolute number of tweets (Spikes in tweet numbers)
* Normalized percentages
###### Potential Updates:
* Pulls greater than 600 (Plotly unsported)
* Reintialization and re-looping
* Data export to XLS/CSV
* General Sentiment guage
## Citations and Resources:
- [vprusso github](https://github.com/vprusso/youtube_tutorials/tree/master/twitter_python/part_1_streaming_tweets)
- [the-javapocalypse github](https://github.com/the-javapocalypse/Twitter-Sentiment-Analysis)
- [shreyans29 github](https://github.com/shreyans29/thesemicolon)
- [sentdex video tutorial](https://www.youtube.com/watch?v=bz2zqXFjOrE&t=524s) (FYI. some Plotly Stream functions are deprecated)
- [Tweepy](http://www.tweepy.org/)
- [Twilio](https://www.twilio.com/)
- [Plotly Stream](https://plot.ly/python/streaming-tutorial/)
- [Twitter Developer](https://developer.twitter.com/content/developer-twitter/en.html)
- [TextBlob](https://textblob.readthedocs.io/en/dev/)
- [NLTK](https://www.nltk.org/)
- [Dash](https://dash.plot.ly/)
## Directory Outline:
1. README.md : Current File
2. tweepyAdvanced.py: (https://git.generalassemb.ly/ericpmwong/Capstone/blob/master/tweepyAdvanced.py)
* Exectuable which enables real time streaming
* Cannot be executed without main user Plotly Stream credentials (<NAME>)
* Several depencies needed: (twittercred, alert_sms, tls.getcredentialsfile (from Plotly Folder))
* Imports:
- numpy
- pandas
- time
- datetime
- tweepy
- json
- textblob
- re
- nltk stopwords
- Counter from collections
- dash
- plotly
- ProtocolError from urllib3.exceptions
3. tweepyAdvanced.IPYNP (https://git.generalassemb.ly/ericpmwong/Capstone/blob/master/jupytertweepyAdvanced.ipynb)
* Jupyter Notebook version of tweepyAdvanced
4. Plotly Credentials
* The following file is required to run the tweepyAdvanced.py
* Due to security reasons, I cannot release my personal stream APIs
* You may create your own plotly account and use your own plotly API stream IDs as the tls should import it
5. alert_sms.py (https://git.generalassemb.ly/ericpmwong/Capstone/blob/master/alert_sms.py)
* File is imported by tweepyAdvanced.py
* Connects to Twilio API to send text message.
* Code holds credentials for text messaging notification
* Appreciate if you do not use my Twilio credentials as they are limtied. Thank you.
6. twitter_cred (https://git.generalassemb.ly/ericpmwong/Capstone/blob/master/twittercred.py)
* Now embded in tweepyAdvanced.py and tweepAdvanced.IPYNP
* Twitter API developer keys listed in tweepyAdvanced.py
* Left for future to keep credentials seperate from main tweepy_Advanced.py
7. Slides (https://docs.google.com/presentation/d/1LoNRcWFnUxrF0klorwzVhAoHN7lDDOGhClo3VRLpEAs/edit?usp=sharing)
* Slides entailing executive summary and details of dashboard and methodology
8. Dashboard(https://plot.ly/dashboard/ericpmwong:80/present#/)
* Link to Dashboard
* Dashboard is inactive until tweepyAdvanced.py is exectued
* If tweepyAdvanced is not executing, Dashboard will display last fetched data (Not realtime)<file_sep> if t == timex[-1]:
print('PENIS')<file_sep>API = ''
APIKEY = ''
ACC = ''
ACCKEY = ''<file_sep># NOTE: If the stream is faster than graphing it will break
#Statitstics and Visuals
import numpy as np
import pandas as pd
import time
import datetime
#import matplotlib.pyplot as plt
#import matplotlib.animation as animation
#Tweepy and Twitter Imports
from tweepy import Stream, OAuthHandler, StreamListener
from tweepy.streaming import StreamListener
import json
#tokenizer
from nltk.corpus import stopwords
#from sklearn.feature_extraction.text import CountVectorizer
from collections import Counter
#Sentiment Analysis
from textblob import TextBlob #More Acccurate
#import nltk
import re
#Dashboard
import plotly
import plotly.plotly as py
#import plotlywrapper as pw
#import dash
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import plotly.tools as tls
#from statsmodels.tsa.arima_model import ARIMA
from urllib3.exceptions import ProtocolError
###########################################################
#Input brand of interest here
brand = 'gucci'
##########################################################
## SET MESSAGE NEGATIVE TWEET TOLERANCE. Graphs will not change without resets
tolerance = 10
##########################################################
# Tokens for Twitter (removed)
API = ''
APIKEY = ''
ACC = ''
ACCKEY = ''
#Plotly Credentials
stream_ids = tls.get_credentials_file()['stream_ids']
print (stream_ids)
#Global Variables predefined
#Changing Vars
positive=0
negative=0
neutral=0
positive_var = 0
negative_var = 0
neutral_var = 0
#Persistent Vars
count = 0
timex = []
timeypos = []
timeyneg = []
timeyneu = []
timeysent = []
tokens=[]
tokenstop =[]
Tx=[]
Ty=[]
posvar = []
negvar = []
neuvar = []
arimap = []
ariman = []
#Text messaging condition
sms = 0
#Creating Plotly Streams
# Absolute Senitment
stream1 = plotly.graph_objs.scatter.Stream(token =stream_ids[0])
stream2 = plotly.graph_objs.scatter.Stream(token =stream_ids[1])
stream3 = plotly.graph_objs.scatter.Stream(token =stream_ids[2])
# Percent Sentiment
stream4 = plotly.graph_objs.scatter.Stream(token =stream_ids[3])
stream5 = plotly.graph_objs.scatter.Stream(token =stream_ids[4])
stream6 = plotly.graph_objs.scatter.Stream(token =stream_ids[5])
# Live tweet
#stream7 = plotly.graph_objs.bar.Stream(token =stream_ids[6])
#Word Count
stream8 = plotly.graph_objs.bar.Stream(token =stream_ids[7])
#Heatmap
#stream9 = plotly.graph_objs.heatmap.Stream(token =stream_ids[8])
#Positive/Negative Rolling Mean 3
stream10 = plotly.graph_objs.scatter.Stream(token =stream_ids[9])
#stream11 = plotly.graph_objs.scatter.Stream(token =stream_ids[10])
stream12 = plotly.graph_objs.scatter.Stream(token =stream_ids[11])
stream13 = plotly.graph_objs.scatter.Stream(token =stream_ids[12])
stream14 = plotly.graph_objs.scatter.Stream(token =stream_ids[13])
# Stream objects
s1 = py.Stream(stream_ids[0])
s2 = py.Stream(stream_ids[1])
s3 = py.Stream(stream_ids[2])
s4 = py.Stream(stream_ids[3])
s5 = py.Stream(stream_ids[4])
s6 = py.Stream(stream_ids[5])
#s7 = py.Stream(stream_ids[6])
s8 = py.Stream(stream_ids[7])
#s9 = py.Stream(stream_ids[8])
s10 = py.Stream(stream_ids[9])
#s11 = py.Stream(stream_ids[10])
s12 = py.Stream(stream_ids[11])
s13 = py.Stream(stream_ids[12])
s14 = py.Stream(stream_ids[13])
#Plotly Line Graph
trace1 = go.Scatter(name = 'Negative', x=timex, y=timeyneg, mode='lines+markers', stream = stream1, fill = 'tozeroy', stackgroup='one', text="Negative",)
trace2 = go.Scatter(name = 'Neutral', x=timex, y=timeyneu, mode='lines+markers', stream = stream2, fill = 'tonexty', stackgroup='one', text="Neutral",)
trace3 = go.Scatter(name = 'Positive',x=timex, y=timeypos, mode='lines+markers', stream = stream3, fill = 'tonexty', stackgroup='one', text="Positive",)
data = [trace1, trace2, trace3]
layout = {'title':(str(brand)+" Sentiment Analysis"),
'shapes': [
{'type': 'line',
'xref': 'paper',
'x0': 0,
'y0': tolerance,
'x1': 1, #datetime.datetime.now().strftime('%M:%S'),
'y1': tolerance,
'line': {
'color': 'red',
'width': 4,
'dash': 'dashdot'}}
],
'annotations' : [
dict(
x=.05,
y=tolerance - 1,
xref='paper',
yref='y',
text='Text Warning Enabled',
showarrow=False,
font=dict(
family='Courier New, monospace',
size=16,
color='#ffffff'
),
align='center',
arrowhead=2,
arrowsize=1,
arrowwidth=2,
arrowcolor='#636363',
ax=20,
ay=-30,
bordercolor='#c7c7c7',
borderwidth=2,
borderpad=4,
bgcolor='red',
opacity=1
)
]
}
fig = dict(data=data, layout=layout)
#Line Graph Percentage
trace4 = go.Scatter(name = 'Negative percent', x=timex, y=timeyneg, mode='lines+markers', stream = stream4, fill = 'tozeroy', stackgroup='one', text="Negative", groupnorm='percent', )
trace5 = go.Scatter(name = 'Neutral percent', x=timex, y=timeyneu, mode='lines+markers', stream = stream5, fill = 'tonexty', stackgroup='one', text="Neutral",)
trace6 = go.Scatter(name = 'Positive percent',x=timex, y=timeypos, mode='lines+markers', stream = stream6, fill = 'tonexty', stackgroup='one', text="Positive",)
datap = [trace4, trace5, trace6]
layoutp = go.Layout(title=(str(brand)+" Sentiment Analysis Normalized"))
figpercent = dict(data=datap, layout=layoutp)
#Tweet Display Disabled
#trace7 = go.Table(stream=stream7, header = dict(values=['Tweets']),
#cells = dict(values=[texty]))
#dataf = [trace7]
#layoutt = go.Layout(title=(str(brand)+" Live Tweets"))
#figtable = dict(data=dataf, layout=layoutt)
#Toenized Word Count
trace8 = go.Bar(x= Tx, y=Ty, stream = stream8, orientation='h')
datat = [trace8]
layoutt = go.Layout(title=(str(brand)+" Common words"))
fighist = dict(data=datat, layout=layoutt)
#Heatmap
#trace9 = go.Heatmap(x=timex, y=timeysent)
#datah = [trace9]
#layouth = go.Layout(title=(str(brand)+" Average Sentiment Indicator"))
#figheat = dict(data=datah, layout=layouth)
#Positive Tweet Moving Average
trace10 = go.Scatter(name = 'Negative', x=timex, y=negvar, mode='lines+markers', stream = stream10, text="Negative", line =dict(color ='blue', ))
trace13 = go.Scatter(name = 'Rolling Mean 3', x=timex, y=ariman, mode='lines+markers', stream = stream13, text="Predicted", line =dict(color = ('red'),
width = 4,
dash = 'dot'))
layout1 = go.Layout(title = (str(brand)+" Negative Tweets per minute"))
figminneg = dict(data=[trace10, trace13], layout=layout1)
#Negative Tweet Moving Average
trace12 = go.Scatter(name = 'Positive',x=timex, y=posvar, mode='lines+markers', stream = stream12, text="Positive", line =dict(color='green'))
trace14 = go.Scatter(name = 'Rolling Mean 3', x=timex, y=arimap, mode='lines+markers', stream = stream14, text="Predicted", line =dict(color = ('red'),
width = 4,
dash = 'dot'))
layout2 = go.Layout(title = (str(brand)+" Positive Tweets per minute"))
figminpos = dict(data=[trace12, trace14], layout=layout2)
#########################################################################################
#Creates a class of filters, data modificaitons, etc to create twitter data
class stdOUTlistener(StreamListener):
#Grabbing data if not error.
def on_data(self,data):
#Sends a text message at negativity tolerance rate. See alert_sms documentation.
global sms
for x in timeyneg:
if x >= tolerance and sms == 0:
import alert_sms
sms += 1
#Try used in case of Key error
try:
#Set globals
global positive
global negative
global neutral
#global combined
global count
#global total
global text
global positive_var
global negative_var
global neutral_var
global posvar
global negvar
global neuvar
global arimap
global ariman
global Tx
global Ty
#Count 1 per tweet pull, 1 pull can contain 2-3 tweets
count += 1
print("TWEET PULL", count)
#Data Loading from json
all_data=json.loads(data)
tweet=all_data["text"]
#Tweet Cleaning
tweet=' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t]) |(\w+:\/\/\S+',’)", " ", tweet).split())
blob=TextBlob(tweet.strip())
#Conducts Sentiment Analysis per tweet
for sen in blob.sentences:
#Create time stamps for X variables
global initime
t= datetime.datetime.now().strftime('%M:%S')
print(t)
print(sen)
# Positive Tweet Threshold is higher. Due to many false positives
sentiment = sen.sentiment.polarity
print(sentiment)
if sentiment > 0.3:
positive += 1
positive_var += 1
print("pos")
#Negative tweets have a higher threshold.
#Vernacular causes noises and positive tweets were False positives.(of Negatives
elif sentiment < -.01:
negative += 1
negative_var += 1
print("neg")
else:
neutral +=1
neutral_var += 1
print("neutral")
#Tokenizes words for graph
tokens.extend([word for word in blob.words if word not in stopwords.words('english') and word not in "RT" and word not in "’" and word not in "," and word not in "https" and word not in str(brand) and word not in "I" and word not in "Gucci"])
tokenstop = Counter(tokens)
Tx = [x[1] for x in tokenstop.most_common(30)]
Ty = [x[0] for x in tokenstop.most_common(30)]
#print(Tx, Ty)
s8.write(dict(x=Tx, y=Ty))
# If TIME is not repeated, execute drawing to plotly
if t not in timex:
#Adds the time to X var
timex.append(t)
#Appending info to array for graphing
posvar.append(positive_var)
negvar.append(negative_var)
neuvar.append(neutral_var)
#Variables for ABS. and Percentage Graph
timeypos.append(positive)
timeyneg.append(negative)
timeyneu.append(neutral)
#totalpnn.append(total)
#total += (positive+negative+neutral)
# #text.append(sen)
#combined += sen.sentiment.polarity
#ARIMA
#Changed in favor of rolling mean manually calculated due to CPU overhead
#3 day Rolling Mean calculations
try:
#Calculating moving average instead
arimap.append(np.mean([posvar[-3],posvar[-2], posvar[-1]]))
ariman.append(np.mean([negvar[-3],negvar[-2], negvar[-1]]))
#pos
#modelp = ARIMA(posvar,order=(0,0,2))
#modelp_fit = modelp.fit(disp=0)
#predpos = modelp_fit.predict().astype(float)
#predposap = predpos[-1]
#arimap.append(predposap)
#print("Positve Arima",arimap)
#neg
#modeln = ARIMA(negvar ,order=(0,0,2))
##modeln_fit = modeln.fit(disp=0)
#predneg = modeln_fit.predict().astype(float)
#prednegap = predneg[-1]
#ariman.append(prednegap)
#print("Negative Arima",ariman)
except:
arimap.append(0.00)
ariman.append(0.00)
#Required Plotly channels to update graph
s1.write(dict(x=timex, y=timeyneg))
s2.write(dict(x=timex, y=timeyneu))
s3.write(dict(x=timex, y=timeypos))
#Nomralized Percentages
s4.write(dict(x=timex, y=timeyneg))
s5.write(dict(x=timex, y=timeyneu))
s6.write(dict(x=timex, y=timeypos))
#Commons Words Tokenizer
#Negative Posts w/Arima
s10.write(dict(x=timex, y=negvar))
s13.write(dict(x=timex, y=ariman))
#Positive Posts w/Arima
s12.write(dict(x=timex, y=posvar))
s14.write(dict(x=timex, y=arimap))
#Unused Streams
#s11.open()
#s11.write(dict(x=timex, y=neuvar))
#s9.open()
#s9.write(dict(x=timex, y=timeysent))
#s7.open()
#s7.write(dict(x=, y)))
#Print Indicators for testing
#print("time", t)
#print(blob)
#print("LABELED AS ", sen.sentiment.polarity)
#print("pos", positive)
#print("negs", negative)
#print("neutral", neutral)
#print("combined sent", compound)
#print(sentiment)
#print(total)
#print(totalpnn)
#Resets vars
#Reset Sentiment to 0 for each pull
sentiment = 0
#Resets for next time interval to replot
positive_var = 0
neutral_var = 0
negative_var = 0
print()
#Executes same code if time stamp is same
else:
for sen in blob.sentences:
print(sen)
#Low threshold most often tweets with pictures or mentions of product are
#positive from a marketing perspective. Gains more traction.
sentiment = sen.sentiment.polarity
print(sentiment)
if sentiment > 0.01:
positive += 1
positive_var += 1
print("pos")
#Negative tweets have a higher threshold.
#Vernacular causes noises and positive tweets were False positives.(of Negatives
elif sentiment < -.01:
negative += 1
negative_var += 1
print("neg")
else:
neutral +=1
neutral_var += 1
print("neutral")
except:
pass
print('error in loop')
def on_error(self, status):
print(status)
pass
######################################################################################
#Loads twitter credentials
listener = stdOUTlistener()
auth = OAuthHandler(API, APIKEY)
auth.set_access_token(ACC, ACCKEY)
#Uncomment to make layout changes in plots
#py.plot(fig, filename="Twit Sent Abs")
#py.plot(figtable, filename="Live Twit Feed")
#py.plot(fighist, filename="Word Count Hist")
#py.plot(figpercent, filename="Twit Sent Percent")
#py.plot(figminneg, filename="Tweet per min neg")
#py.plot(figminpos, filename="Tweet per min pos")
#Uncomment to test Matplotlib
#plt.style.use('ggplot')
#plt.show(block=False)
s1.open()
s2.open()
s3.open()
#Nomralized Percentages
s4.open()
s5.open()
s6.open()
#Commons Words Tokenizer
s8.open()
#Negative Posts w/Arima
s10.open()
s13.open()
#Positive Posts w/Arima
s12.open()
s14.open()
#Creating Streamer, pairs authentication and listerner class
stream = Stream(auth, listener)
#Engages the stream
while True:
try:
stream.filter(track=[brand], languages=["en"]);
except (ProtocolError, AttributeError):
continue
| 2a9d8be1f9100133d6afdb95993af5e488e57752 | [
"Markdown",
"Python"
]
| 5 | Python | EricPmWong/TwitterSentimentDASH | 77ecbde5b19816898d790c26a8c03f27fd7b3e01 | 53c532aa3547be47f8eacf1c0f1b16c7d02e1ecc |
refs/heads/main | <file_sep>import { createStore, applyMiddleware } from "redux";
import reducer from "./Reducers/reducer";
import thunk from "redux-thunk";
const logger = (storeAPI) => (next) => (action) => {
console.log("Store before action dispatch: ", storeAPI.getState());
console.log("Action dispatch: ", action);
const result = next(action);
console.log("Store after action dispatch: ", storeAPI.getState());
return result;
};
const middleWare = applyMiddleware(logger, thunk);
const store = createStore(reducer, middleWare);
export default store;
<file_sep>import { connect } from "react-redux";
import { loadBasketItems } from "../../actions/action";
import React, { useState } from "react";
function Basket(props) {
const { basket } = props;
const { items } = basket;
const [openBasket, setOpenBasket] = useState(false);
const handleBasketClick = () => {
setOpenBasket(!openBasket);
console.log(openBasket);
};
return (
<div className="basket">
<div id="basket" className="basket-button" onClick={handleBasketClick}>
<img src={`${process.env.PUBLIC_URL}/images/bag.svg`} alt="" />
<span className="count"></span>
</div>
{openBasket && (
<div className="basket-dropdown">
<h5 className="title">Your Cart</h5>
<ul>
{items &&
items.map((basketitem) => {
console.log("single basketitem", basketitem);
return (
<li key={basketitem.id}>
<a href="/">
<div className="icon">
<img src={basketitem.item[2]} alt="" />
</div>
<p className="prod-count mt-3">x1</p>
<div className="content">
<div className="description">
<p>{basketitem.item[1]}</p>
<p>Size: {basketitem.item[4]}</p>
</div>
<p className="price">
{basketitem.item[3]}
<sup>$</sup>
</p>
</div>
</a>
</li>
);
})}
</ul>
<div className="total">
<p className="subtotal">
Subtotal <span>(0 Items)</span>
</p>
<p className="price">
0<sup>$</sup>
</p>
</div>
<a href="/" className="btn-orange">
Checkout
</a>
</div>
)}
</div>
);
}
function mapStateToProps(state) {
return {
basket: state.basket,
};
}
function mapDispatchToProps(dispatch) {
return {
loadItems: (items) => dispatch(loadBasketItems(items)),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Basket);
<file_sep>export default function Intro() {
return (
<section id="intro">
<div className="pattern-icon vegetable">
<img src={`${process.env.PUBLIC_URL}/images/vegitable.png`} alt="" />
</div>
<div className="pattern-icon bg">
<img src={`${process.env.PUBLIC_URL}/images/intro-bg.png`} alt="" />
</div>
<div className="container">
<div className="row justify-content-center">
<div className="col-lg-7">
<h1 className="section-title">Food delivery in Kovel</h1>
<p className="section-subtitle">
If you decide to relax or have unexpected guests, call us. We make
sure that your vacation is comfortable, enjoyable and delicious
</p>
</div>
</div>
<div className="row justify-content-end">
<div className="col-lg-9">
<div className="photo">
<img src={`${process.env.PUBLIC_URL}/images/piza.png`} alt="" />
</div>
</div>
</div>
</div>
</section>
);
}
<file_sep>export default function Footer() {
return (
<footer>
<div className="container">
<p>© Classic Family Restaurant</p>
<div className="logo">
<img src="/assets/images/logos.svg" alt="" />
</div>
<p>
Made with delight by <span>harmuder</span>
</p>
</div>
</footer>
);
}
<file_sep>// import Axios from "axios";
import * as ActionTypes from "./action-types";
export function loadAsyncAction() {
return function (dispatch) {
fetch("https://isko88.github.io/apipizza.json")
.then((resp) => resp.json())
.then((products) => {
dispatch({
type: ActionTypes.FETCH_PRODUCTS,
payload: products,
});
});
};
}
export function loadBasketItems(items){
return{
type: ActionTypes.LOAD_BASKET_ITEM,
payload: items,
}
}
export function addBasketItems(item){
return{
type: ActionTypes.ADD_BASKET_ITEM,
payload: item,
}
}<file_sep>export default function Navbar(){
return(
<header>
<div className="container">
<div className="header-wrapper">
<nav>
<a href="/" className="nav-link">Payment</a>
<a href="/" className="nav-link">About Us</a>
<a href="/" className="nav-link">Contacts</a>
</nav>
<a href="/" className="logo">
<img src="assets/images/logos.svg" alt="" />
</a>
<div className="contact">
<p className="opening-hours">Daily 11am - 9pm</p>
<div className="phone">
<div className="icon">
<img src="/assets/images/phone.svg" alt="" />
</div>
<p>0 800 33 08 98</p>
</div>
</div>
<div className="ham-menu"><i className="fa fa-bars"></i></div>
</div>
</div>
</header>
)
}<file_sep>export const FETCH_PRODUCTS = "FETCH_PRODUCTS";
export const ADD_BASKET_ITEM = "ADD_BASKET_ITEM";
export const LOAD_BASKET_ITEM = "LOAD_BASKET_ITEM"; | df6ad9c2e2a9170619226914ef25006c284955c2 | [
"JavaScript"
]
| 7 | JavaScript | codeacademyprogramming/25-05-2021-zumrud7 | 9a0af452120be878840f629df530234ce0d4bded | 3a6b75b1ba8d28be078a5b192e783fa178a5ba3d |
refs/heads/master | <file_sep># ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Conceptive Engineering nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ============================================================================
from camelot.admin.entity_admin import EntityAdmin
from camelot.admin import table
from camelot.core.utils import ugettext_lazy as _
class VisitorsPerDirector(object):
class Admin(EntityAdmin):
verbose_name = _('Visitors per director')
list_display = table.Table( [ table.ColumnGroup( _('Name and Visitors'), ['first_name', 'last_name', 'visitors'] ),
table.ColumnGroup( _('Official'), ['birthdate', 'social_security_number', 'passport_number'] ) ]
)
# end column group
def setup_views():
from sqlalchemy.sql import select, func, and_
from sqlalchemy.orm import mapper, class_mapper, exc
from camelot.model.party import Person
from camelot_example.model import Movie, VisitorReport
try:
class_mapper(VisitorsPerDirector)
return
except exc.UnmappedClassError:
pass
s = select([Person.party_id,
Person.first_name.label('first_name'),
Person.last_name.label('last_name'),
Person.birthdate.label('birthdate'),
Person.social_security_number.label('social_security_number'),
Person.passport_number.label('passport_number'),
func.sum( VisitorReport.visitors ).label('visitors'),],
whereclause = and_( Person.party_id == Movie.director_party_id,
Movie.id == VisitorReport.movie_id),
group_by = [ Person.party_id,
Person.first_name,
Person.last_name,
Person.birthdate,
Person.social_security_number,
Person.passport_number, ] )
s=s.alias('visitors_per_director')
mapper( VisitorsPerDirector, s, always_refresh=True )
<file_sep>SQLAlchemy==1.0.8
Jinja2==2.7.2
chardet==2.2.1
xlwt-future==0.8.0
xlrd==0.9.3
six==1.10.0
pycrypto==2.6.1
<file_sep># ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Conceptive Engineering nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ============================================================================
"""Example code for attaching actions to camelot views
"""
from camelot.admin.action import Action
from camelot.admin.object_admin import ObjectAdmin
from camelot.view.action_steps import ChangeObject, FlushSession, UpdateProgress
from camelot.view.controls import delegates
from camelot.core.utils import ugettext_lazy as _
class Options(object):
"""A python object in which we store the change in rating
"""
def __init__(self):
self.only_selected = True
self.change = 1
# Since Options is a plain old python object, we cannot
# use an EntityAdmin, and should use the ObjectAdmin
class Admin( ObjectAdmin ):
verbose_name = _('Change rating options')
form_display = ['change', 'only_selected']
form_size = (100, 100)
# Since there is no introspection, the delegate should
# be specified explicitely, and set to editable
field_attributes = {'only_selected':{'delegate':delegates.BoolDelegate,
'editable':True},
'change':{'delegate':delegates.IntegerDelegate,
'editable':True},
}
# begin change rating action definition
class ChangeRatingAction( Action ):
"""Action to print a list of movies"""
verbose_name = _('Change Rating')
def model_run( self, model_context ):
#
# the model_run generator method yields various ActionSteps
#
options = Options()
yield ChangeObject( options )
if options.only_selected:
iterator = model_context.get_selection()
else:
iterator = model_context.get_collection()
for movie in iterator:
yield UpdateProgress( text = u'Change %s'%unicode( movie ) )
movie.rating = min( 5, max( 0, (movie.rating or 0 ) + options.change ) )
#
# FlushSession will write the changes to the database and inform
# the GUI
#
yield FlushSession( model_context.session )
# end change rating action definition
<file_sep># ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Conceptive Engineering nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ============================================================================
import six
from camelot.admin.action import Action
from camelot.core.utils import ugettext_lazy as _
from camelot.view.art import Icon
class ImportCovers( Action ):
verbose_name = _('Import cover images')
icon = Icon('tango/22x22/mimetypes/image-x-generic.png')
# begin select files
def model_run( self, model_context ):
from camelot.view.action_steps import ( SelectFile,
UpdateProgress,
Refresh,
FlushSession )
select_image_files = SelectFile( 'Image Files (*.png *.jpg);;All Files (*)' )
select_image_files.single = False
file_names = yield select_image_files
file_count = len( file_names )
# end select files
# begin create movies
import os
from sqlalchemy import orm
from camelot.core.orm import Session
from camelot_example.model import Movie
movie_mapper = orm.class_mapper( Movie )
cover_property = movie_mapper.get_property( 'cover' )
storage = cover_property.columns[0].type.storage
session = Session()
for i, file_name in enumerate(file_names):
yield UpdateProgress( i, file_count )
title = os.path.splitext( os.path.basename( file_name ) )[0]
stored_file = storage.checkin( six.text_type( file_name ) )
movie = Movie( title = six.text_type( title ) )
movie.cover = stored_file
yield FlushSession( session )
# end create movies
# begin refresh
yield Refresh()
# end refresh
<file_sep>#!/usr/bin/env python
import os
import sys
import camelot
from setuptools import setup, find_packages
src_dir = os.path.dirname(__file__)
README = os.path.join(src_dir, 'readme.txt')
long_description = open(README).read() + '\n\n'
dependencies = os.path.join(src_dir, 'requirements.txt')
install_requires = open( dependencies ).read().splitlines()
if sys.platform.startswith('win'):
install_requires.append('winpaths')
setup(
name = 'Camelot',
version = camelot.__version__,
description = 'A python GUI framework on top of Sqlalchemy and Qt, inspired by the Django admin interface. Start building desktop applications at warp speed, simply by adding some additional information to you model definition.',
long_description = long_description,
keywords = 'qt pyqt sqlalchemy elixir desktop gui framework',
author = 'Conceptive Engineering',
author_email = '<EMAIL>',
maintainer = 'Conceptive Engineering',
maintainer_email = '<EMAIL>',
url = 'http://www.python-camelot.com',
include_package_data = True,
package_data = {
# If any package contains *.txt files, include them:
'':['*.txt', '*.rst', '*.html', '*.js', '*.png', '*.doc', '*.GPL'],
'doc':['*.rst', '*.html', '*.png'],
},
options = {
'extract_messages':{'input_dirs':('camelot',),
'output_file':'camelot/art/translations/camelot.pot',
'keywords':'ugettext tr _ ugettext_lazy'},
'init_catalog':{'domain':'camelot',
'input_file':'camelot/art/translations/camelot.pot',
'output_dir':'camelot/art/translations'},
'update_catalog':{'domain':'camelot',
'input_file':'camelot/art/translations/camelot.pot',
'output_dir':'camelot/art/translations'},
},
license = 'GPL, Commercial',
platforms = 'Linux, Windows, OS X',
install_requires = install_requires,
entry_points = {'console_scripts':[
'camelot_admin = camelot.bin.camelot_admin:main',
'camelot_example = camelot_example.main:main',
'camelot_mini_example = camelot_example.mini_main:main',
],
'setuptools.installation':[
'eggsecutable = camelot_example.main:main',
],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Win32 (MS Windows)',
'Environment :: X11 Applications',
'Environment :: X11 Applications :: Gnome',
'Environment :: X11 Applications :: GTK',
'Environment :: X11 Applications :: KDE',
'Environment :: X11 Applications :: Qt',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'License :: Other/Proprietary License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: Database :: Front-Ends',
'Topic :: Office/Business',
'Topic :: Software Development :: Libraries :: Application Frameworks',
],
packages = find_packages() + ['doc',] )
<file_sep># ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Conceptive Engineering nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ============================================================================
import time
import datetime
# begin basic imports
from camelot.core.orm import Entity
from camelot.admin.entity_admin import EntityAdmin
from sqlalchemy import sql
from sqlalchemy.schema import Column
import sqlalchemy.types
# end basic imports
import camelot.types
from camelot.core.orm import (ManyToOne, OneToMany,
ManyToMany, ColumnProperty)
from camelot.admin.action import Action
from camelot.admin.action import list_filter
from camelot.core.utils import ugettext_lazy as _
from camelot.model.party import Person
from camelot.view import action_steps
from camelot.view.forms import Form, TabForm, WidgetOnlyForm, HBoxForm, Stretch
from camelot.view.controls import delegates
from camelot.view.art import ColorScheme
from camelot_example.change_rating import ChangeRatingAction
from camelot_example.drag_and_drop import DropAction
#
# Some helper functions that will be used later on
#
def genre_choices( entity_instance ):
"""Choices for the possible movie genres"""
return [
((None),('')),
(('action'),('Action')),
(('animation'),('Animation')),
(('comedy'),('Comedy')),
(('drama'),('Drama')),
(('sci-fi'),('Sci-Fi')),
(('war'),('War')),
(('thriller'),('Thriller')),
(('family'),('Family')) ]
# begin simple action definition
class BurnToDisk( Action ):
verbose_name = _('Burn to disk')
def model_run( self, model_context ):
yield action_steps.UpdateProgress( 0, 3, _('Formatting disk') )
time.sleep( 0.7 )
yield action_steps.UpdateProgress( 1, 3, _('Burning movie') )
time.sleep( 0.7 )
yield action_steps.UpdateProgress( 2, 3, _('Finishing') )
time.sleep( 0.5 )
# end simple action definition
def get_state( self, model_context ):
"""Turn the burn to disk button on, only if the title of the
movie is entered"""
state = super( BurnToDisk, self ).get_state( model_context )
obj = model_context.get_object()
if obj and obj.title:
state.enabled = True
else:
state.enabled = False
return state
# begin short movie definition
class Movie( Entity ):
__tablename__ = 'movies'
title = Column( sqlalchemy.types.Unicode(60), nullable = False )
short_description = Column( sqlalchemy.types.Unicode(512) )
releasedate = Column( sqlalchemy.types.Date )
genre = Column( sqlalchemy.types.Unicode(15) )
rating = Column( camelot.types.Rating() )
#
# All relation types are covered with their own editor
#
director = ManyToOne('Person')
cast = OneToMany('Cast')
visitor_reports = OneToMany('VisitorReport', cascade='delete')
tags = ManyToMany('Tag',
tablename = 'tags_movies__movies_tags',
local_colname = 'tags_id',
remote_colname = 'movies_id' )
# end short movie definition
#
# Camelot includes custom sqlalchemy types, like Image, which stores an
# image on disk and keeps the reference to it in the database.
#
# begin image definition
cover = Column( camelot.types.Image( upload_to = 'covers' ) )
# end image definition
#
# Or File, which stores a file in the upload_to directory and stores a
# reference to it in the database
#
script = Column( camelot.types.File( upload_to = 'script' ) )
description = Column( camelot.types.RichText )
#
# Normal python properties can be used as well, but then the
# delegate needs be specified in the Admin.field_attributes
#
@property
def visitors_chart(self):
#
# Container classes are used to transport chunks of data between
# the model the gui, in this case a chart
#
from camelot.container.chartcontainer import BarContainer
return BarContainer( range(len(self.visitor_reports)),
[vr.visitors for vr in self.visitor_reports] )
# begin column_property
@ColumnProperty
def total_visitors( self ):
return sql.select( [sql.func.sum( VisitorReport.visitors) ],
VisitorReport.movie_id == self.id )
# end column_property
#
# Each Entity subclass can have a subclass of EntityAdmin as
# its inner class. The EntityAdmin class defines how the Entity
# class will be displayed in the GUI. Its behavior can be steered
# by specifying some class attributes
#
# To fully customize the way the entity is visualized, the EntityAdmin
# subclass should overrule some of the EntityAdmin's methods
#
bar = 3
class Admin(EntityAdmin):
# the list_display attribute specifies which entity attributes should
# be visible in the table view
list_display = ['cover', 'title', 'releasedate', 'rating',]
lines_per_row = 5
# define filters to be available in the table view
list_filter = ['genre', list_filter.ComboBoxFilter('director.full_name')]
# if the search function needs to look in related object attributes,
# those should be specified within list_search
list_search = ['director.full_name']
# begin list_actions
#
# the action buttons that should be available in the list view
#
list_actions = [ChangeRatingAction()]
# end list_actions
drop_action = DropAction()
# the form_display attribute specifies which entity attributes should be
# visible in the form view
form_display = TabForm([
('Movie', Form([
HBoxForm([WidgetOnlyForm('cover'), ['title', 'rating', Stretch()]]),
'short_description',
'releasedate',
'director',
'script',
'genre',
'description',], columns = 2)),
('Cast', WidgetOnlyForm('cast')),
('Visitors', WidgetOnlyForm('visitors_chart')),
('Tags', WidgetOnlyForm('tags'))
])
# begin form_actions
#
# create a list of actions available for the user on the form view
#
form_actions = [BurnToDisk()]
# end form_actions
#
# additional attributes for a field can be specified in the
# field_attributes dictionary
#
field_attributes = dict(cast=dict(create_inline=True),
genre=dict(choices=genre_choices, editable=lambda o:bool(o.title and len(o.title))),
releasedate=dict(background_color=lambda o:ColorScheme.orange_1 if o.releasedate and o.releasedate < datetime.date(1920,1,1) else None),
visitors_chart=dict(delegate=delegates.ChartDelegate),
rating=dict(tooltip='''<table>
<tr><td>1 star</td><td>Not that good</td></tr>
<tr><td>2 stars</td><td>Almost good</td></tr>
<tr><td>3 stars</td><td>Good</td></tr>
<tr><td>4 stars</td><td>Very good</td></tr>
<tr><td>5 stars</td><td>Awesome !</td></tr>
</table>'''),
smiley=dict(delegate=delegates.SmileyDelegate),
script=dict(remove_original=True))
def __unicode__(self):
return self.title or ''
class Cast( Entity ):
__tablename__ = 'cast'
role = Column( sqlalchemy.types.Unicode(60) )
movie = ManyToOne( 'Movie', required = True, backref = 'cast' )
actor = ManyToOne( Person, required = True )
class Admin( EntityAdmin ):
verbose_name = 'Actor'
list_display = ['actor', 'role']
def __unicode__(self):
if self.actor:
return self.actor.name
return ''
class Tag(Entity):
__tablename__ = 'tags'
name = Column( sqlalchemy.types.Unicode(60), nullable = False )
movies = ManyToMany( 'Movie',
tablename = 'tags_movies__movies_tags',
local_colname = 'movies_id',
remote_colname = 'tags_id' )
def __unicode__( self ):
return self.name
class Admin( EntityAdmin ):
form_size = (400,200)
list_display = ['name']
# begin visitor report definition
class VisitorReport(Entity):
__tablename__ = 'visitor_report'
date = Column( sqlalchemy.types.Date,
nullable = False,
default = datetime.date.today )
visitors = Column( sqlalchemy.types.Integer,
nullable = False,
default = 0 )
movie = ManyToOne( 'Movie', required = True )
# end visitor report definition
class Admin(EntityAdmin):
verbose_name = _('Visitor Report')
list_display = ['movie', 'date', 'visitors']
field_attributes = {'visitors':{'minimum':0}}
<file_sep># ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Conceptive Engineering nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ============================================================================
from camelot.view.art import Icon
from camelot.admin.application_admin import ApplicationAdmin
from camelot.admin.section import Section
from camelot.core.utils import ugettext_lazy as _
# begin application admin
class MyApplicationAdmin(ApplicationAdmin):
name = 'Camelot Video Store'
# begin sections
def get_sections(self):
from camelot.model.memento import Memento
from camelot.model.party import ( Person, Organization,
PartyCategory )
from camelot.model.i18n import Translation
from camelot.model.batch_job import BatchJob, BatchJobType
from camelot_example.model import Movie, Tag, VisitorReport
from camelot_example.view import VisitorsPerDirector
# begin import action
from camelot_example.importer import ImportCovers
# end import action
return [
# begin section with action
Section( _('Movies'),
self,
Icon('tango/22x22/mimetypes/x-office-presentation.png'),
items = [ Movie,
Tag,
VisitorReport,
VisitorsPerDirector,
ImportCovers() ]),
# end section with action
Section( _('Relation'),
self,
Icon('tango/22x22/apps/system-users.png'),
items = [ Person,
Organization,
PartyCategory ]),
Section( _('Configuration'),
self,
Icon('tango/22x22/categories/preferences-system.png'),
items = [ Memento,
Translation,
BatchJobType,
BatchJob
])
]
# end sections
# begin actions
def get_actions(self):
from camelot.admin.action import OpenNewView
from camelot.model.party import Party
from camelot_example.model import Movie
new_movie_action = OpenNewView( self.get_related_admin(Movie) )
new_movie_action.icon = Icon('tango/22x22/mimetypes/x-office-presentation.png')
return [new_movie_action, OpenNewView(self.get_related_admin(Party))]
# end actions
# end application admin
class MiniApplicationAdmin( MyApplicationAdmin ):
"""An application admin for an application with a reduced number of
widgets on the main window.
"""
# begin mini admin
def get_toolbar_actions( self, toolbar_area ):
from PyQt4.QtCore import Qt
from camelot.model.party import Person
from camelot.admin.action import application_action, list_action
from model import Movie
movies_action = application_action.OpenTableView( self.get_related_admin( Movie ) )
movies_action.icon = Icon('tango/22x22/mimetypes/x-office-presentation.png')
persons_action = application_action.OpenTableView( self.get_related_admin( Person ) )
persons_action.icon = Icon('tango/22x22/apps/system-users.png')
if toolbar_area == Qt.LeftToolBarArea:
return [ movies_action,
persons_action,
list_action.AddNewObject(),
list_action.OpenFormView(),
list_action.DeleteSelection(),
application_action.Exit(),]
def get_actions( self ):
return []
def get_sections( self ):
return None
def get_main_menu( self ):
return None
def get_stylesheet(self):
from camelot.view import art
return art.read('stylesheet/black.qss').decode('utf-8')
# end mini admin
<file_sep># ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Conceptive Engineering nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ============================================================================
import datetime
import os
def load_movie_fixtures():
from camelot.model.fixture import Fixture
from camelot.model.party import Person
from camelot_example.model import Movie, VisitorReport
from camelot.core.files.storage import Storage, StoredImage
from camelot.core.resources import resource_filename
storage = Storage(upload_to='covers',
stored_file_implementation = StoredImage)
movies = [
[
u'The Shining',
u'The tide of terror that swept America is here.',
datetime.date(1980, 5, 23),
(u'Stanley', u'Kubrick',),
[
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>'
],
[u'Horror',u'Mystery',u'Thriller'],
u'thriller',
4,
u'shining.png',
u'A family heads to an isolated hotel for the winter where an evil'
' and spiritual presence influences the father into violence,'
' while his psychic son sees horrific forebodings from the past'
' and of the future.'
],
[
u'The Bourne Identity',
u'<NAME> is Jason Bourne.',
datetime.date(2002, 6, 14),
(u'Doug', u'Liman'),
[
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>'
],
[u'Action',u'Adventure'],
u'action',
4,
u'bourne.png',
u'A man is picked up by a fishing boat, bullet-riddled and without'
' memory, then races to elude assassins and recover from amnesia.'
],
[
u'Casino Royale',
u'Discover how James became Bond.',
datetime.date(2006, 11, 17),
(u'Martin', u'Campbell'),
[
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'Jeffrey',
u'Wright'
],
[u'Action',u'Adventure'],
u'action',
5,
u'casino.png',
u"In his first mission, <NAME> must stop Le Chiffre, a banker"
" to the world's terrorist organizations, from winning a"
" high-stakes poker tournament at Casino Royale in Montenegro."
],
[
u'Toy Story',
u'Oooh...3-D.',
datetime.date(1995, 11, 22),
(u'John', u'Lasseter'),
[
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>'
],
[u'Animation',u'Adventure'],
u'animation',
4,
u'toystory.png',
u"a cowboy toy is profoundly threatened and jealous when a fancy"
" spaceman toy supplants him as top toy in a boy's room."
],
[
u"<NAME> and the Sorcerer's Stone",
u'Let The Magic Begin.',
datetime.date(2001, 11, 16),
(u'Chris', u'Columbus'),
[
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>'
],
[u'Family',u'Adventure'],
u'family',
3,
u'potter.png',
u'Rescued from the outrageous neglect of his aunt and uncle, a'
' young boy with a great destiny proves his worth while attending'
' Hogwarts School of Witchcraft and Wizardry.'
],
[
u'Iron Man 2',
u'The world now becomes aware of the dual life of the Iron Man.',
datetime.date(2010, 5, 17),
(u'Jon', 'Favreau'),
[
u'<NAME> Jr.',
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>'
],
[u'Action',u'Adventure',u'Sci-fi'],
u'sci-fi',
3,
u'ironman.png',
u'billionaire <NAME> must contend with deadly issues involving'
' the government, his own friends, as well as new enemies due to'
' his superhero alter ego Iron Man.'
],
[
u'The Lion King',
u"Life's greatest adventure is finding your place in the Circle of"
" Life.",
datetime.date(1994, 6, 24),
(u'Roger', u'Allers'),
[
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>'
],
[u'Animation',u'Adventure'],
u'animation',
5,
u'lionking.png',
u'Tricked into thinking he killed his father, a guilt ridden lion'
' cub flees into exile and abandons his identity as the future'
' King.'
],
[
u'Avatar',
u'Enter the World.',
datetime.date(2009, 12, 18),
(u'James', u'Cameron'),
[
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>'
],
[u'Action',u'Adventure',u'Sci-fi'],
u'sci-fi',
5,
u'avatar.png',
u'A paraplegic marine dispatched to the moon Pandora on a unique'
' mission becomes torn between following his orders and'
' protecting the world he feels is his home.'
],
[
u'Pirates of the Caribbean: The Curse of the Black Pearl',
u'Prepare to be blown out of the water.',
datetime.date(2003, 7, 9),
(u'Gore', u'Verbinski'),
[
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>port'
],
[u'Action',u'Adventure'],
u'action',
5,
u'pirates.png',
u"<NAME> teams up with eccentric pirate \"Captain\""
" <NAME> to save his love, the governor's daughter, from"
" Jack's former pirate allies, who are now undead."
],
[
u'The Dark Knight',
u'Why so serious?',
datetime.date(2008, 7, 18),
(u'Christopher', u'Nolan'),
[
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>',
u'<NAME>'
],
[u'Action',u'Drama'],
u'action',
5,
u'darkknight.png',
u'<NAME> and <NAME> are forced to deal with the chaos'
' unleashed by an anarchist mastermind known only as the Joker, as'
' it drives each of them to their limits.'
]
]
visits = {
u'The Shining': [
(u'Washington D.C.', 10000, datetime.date(1980, 5, 23)),
(u'Buesnos Aires', 4000,datetime.date(1980, 6, 12)),
(u'California', 13000,datetime.date(1980, 5, 23)),
],
u'The Dark Knight': [
(u'New York', 20000, datetime.date(2008, 7, 18)),
(u'London', 15000, datetime.date(2008, 7, 20)),
(u'Tokyo', 3000, datetime.date(2008, 7, 24)),
],
u'Avatar': [
(u'Shangai', 6000, datetime.date(2010, 1, 5)),
(u'Atlanta', 3000, datetime.date(2009, 12, 18)),
(u'Boston', 5000, datetime.date(2009, 12, 18)),
],
}
for title, short_description, releasedate, (director_first_name, director_last_name), cast, tags, genre, rating, cover, description in movies:
director = Fixture.insert_or_update_fixture(
Person,
fixture_key = u'%s_%s'%(director_first_name, director_last_name),
values = {'first_name':director_first_name,
'last_name':director_last_name}
)
movie = Fixture.find_fixture( Movie, title )
if not movie:
# use resource_filename, since resource_string seems to mess either with encoding
# or with line endings, when on windows
image = resource_filename( 'camelot_example', os.path.join( 'media', 'covers', cover ) )
stored_image = storage.checkin( image )
movie = Fixture.insert_or_update_fixture(
Movie,
fixture_key = title,
values = {
'title': title,
'director':director,
'short_description':short_description,
'releasedate':releasedate,
'rating':rating,
'genre':genre,
'description':description,
'cover':stored_image,
},
)
rep = visits.get(title, None)
if rep:
for city, visitors, date in rep:
Fixture.insert_or_update_fixture(
VisitorReport,
fixture_key = '%s_%s' % (title, city),
values = {
'movie': movie,
'date': date,
'visitors': visitors,
}
)
<file_sep># ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Conceptive Engineering nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ============================================================================
import logging
FORMAT = '[%(levelname)-7s] [%(name)-35s] - %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger('videostore.main')
#logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)
try:
import matplotlib
logger.info('matplotlib %s is used'%(matplotlib.__version__))
except:
logger.error('Charts will not work because of missing matplotlib')
from camelot.core.conf import settings, SimpleSettings
class ExampleSettings( SimpleSettings ):
"""Special settings class for the example application, this is done to
'survive' various packaging regimes, such as windows, debian, ...
"""
@staticmethod
def setup_model():
from sqlalchemy.orm import configure_mappers
from camelot.core.sql import metadata
metadata.bind = settings.ENGINE()
#
# import all the needed model files to make sure the mappers and tables
# are defined before creating them in the database
#
from camelot.model import (party, authentication, i18n, fixture,
memento, batch_job)
from . import model
logger.debug('loaded datamodel for %s'%party.__name__)
logger.debug('loaded datamodel for %s'%authentication.__name__)
logger.debug('loaded datamodel for %s'%i18n.__name__)
logger.debug('loaded datamodel for %s'%fixture.__name__)
logger.debug('loaded datamodel for %s'%memento.__name__)
logger.debug('loaded datamodel for %s'%batch_job.__name__)
logger.debug('loaded datamodel for %s'%model.__name__)
#
# create the tables for all models, configure mappers first, to make
# sure all deferred properties have been handled, as those could
# create tables or columns
#
configure_mappers()
metadata.create_all()
#
# Load sample data with the fixure mechanism
#
from camelot_example.fixtures import load_movie_fixtures
load_movie_fixtures()
#
# setup the views
#
from camelot_example.view import setup_views
setup_views()
example_settings = ExampleSettings('camelot',
'videostore',
data = 'videostore_3.sqlite')
def main():
from camelot.admin.action.application import Application
from camelot.view.main import main_action
from camelot_example.application_admin import MyApplicationAdmin
settings.append(example_settings)
videostore = Application(MyApplicationAdmin())
main_action(videostore)
if __name__ == '__main__':
main()
| 6eadf075e3a2c89557813be7ff56d5706caea583 | [
"Python",
"Text"
]
| 9 | Python | ag-python-qt/camelot | 56aa93f774edbb0c31a21109e187cf81f49a68d8 | 0f9ef50f9a3774c87e638c7d4c9cffc837a7becb |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace StudentRegistration.Models
{
public class Student
{
[Display(Name = "Student ID Number")]
public int ID { get; set; }
[Display(Name = "Student Name")]
public string Name { get; set; }
[Display(Name = "Mobile Phone Number")]
[DataType(DataType.PhoneNumber)]
public double CellPh { get; set; }
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
public int Age { get; set; }
}
}
<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
namespace StudentRegistration.Data.Migrations
{
public partial class testing1 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<double>(
name: "CellPh",
table: "Student",
nullable: false,
oldClrType: typeof(int));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "CellPh",
table: "Student",
nullable: false,
oldClrType: typeof(double));
}
}
}
| b493e88f0b9115b0b7b8f5f676398c503a1efa3b | [
"C#"
]
| 2 | C# | gmullins925/StudentRegistration | 173de6ddc34cde714f2150f15d805f6614a3739e | 28d05f105bcbbd035ae7fc7929f72ba19f269f87 |
refs/heads/master | <file_sep>/*****************************************************************************
* Copyright (C) <NAME> <EMAIL>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include <stdio.h>
#include <curses.h>
#include <menu.h>
#include <stdlib.h>
#include <errno.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
#define CTRLD 4
#define prate 200
#define grate 150
#define srate 100
#define trate 2
#define pf 10
typedef struct node {
int seat;
char type;
struct node *next;
}node;
typedef struct matrix {
node **a;
int n;
}matrix;
float billing(int n, char ch);
int booking(MENU *, int *n, char *ch, matrix *m);
void reciept(char type,int psn, float price,int n, char ch);
void init(matrix *m, int n);
void insertseat(matrix *m, int from, int to, char type);
void insertseat(matrix *m, int from, int to, char type);
void printmatrix(matrix *m, int n);
char *choices[] = {
"ENGLISH MOVIES",
"HINDI MOVIES",
"MARATHI MOVIES",
"EXIT",
};
char *english[] = {
"THE MARTIAN",
"INTERSTELLAR",
"STAR WARS",
"MISSION IMPOSSIBLE V",
"BACK"
};
char *hindi[] = {
"TALWAR",
"PK",
"SHAANDAR",
"<NAME>",
"BACK",
};
char *marathi[] ={
"<NAME>",
"<NAME>",
"ZENDA",
"<NAME>",
"BACK",
};
void func(char *name);
int main(int argc, char *argv[]) {
ITEM **my_items, **e_items, **h_items, **m_items;
int n, k, c;
char ch;
float prize;
FILE *fp;
int i1, j1, j;
matrix m;
fp = fopen("seats.txt", "r");
if(fp == NULL) {
perror("fopen failed:");
return errno;
}
fscanf(fp, "%d", &n);
init(&m, n);
/*Code to read seat matrix from file */
for(i1 = 0; i1 < n; i1++)
for(j1 = 0; j1 < n;) {
fscanf(fp, "%c", &ch);
if(ch == 'p' || ch == 'g' || ch == 's' || ch == 'B'){
insertseat(&m, i1, j1, ch);
j1++;
}
}
fclose(fp);
/*Initialise Curses*/
static int pos = 0, pos1 = 0, pos2 = 0, pos3 = 0;
MENU *my_menu,*e_menu,*h_menu,*m_menu ;
int n_choices,m_choices,h_choices,e_choices, i;
initscr();
start_color();
cbreak();
noecho();
keypad(stdscr, TRUE);
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_MAGENTA, COLOR_BLACK);
n_choices = ARRAY_SIZE(choices);
e_choices = ARRAY_SIZE(english);
h_choices = ARRAY_SIZE(hindi);
m_choices = ARRAY_SIZE(marathi);
my_items = (ITEM**)calloc(n_choices +1, sizeof(ITEM *));
e_items = (ITEM**)calloc(e_choices +1, sizeof(ITEM *));
h_items = (ITEM**)calloc(h_choices +1, sizeof(ITEM *));
m_items = (ITEM**)calloc(m_choices +1, sizeof(ITEM *));
/*Initialise Menu*/
for(i = 0;i < n_choices; ++i) {
my_items[i] = new_item(choices[i], NULL);
set_item_userptr(my_items[i], func);
}
for(i = 0;i < e_choices; ++i) {
e_items[i] =new_item(english[i], NULL);
set_item_userptr(e_items[i], func);
}
for(i = 0;i < h_choices; ++i) {
h_items[i] = new_item(hindi[i], NULL);
set_item_userptr(h_items[i], func);
}
for(i = 0;i < m_choices; ++i) {
m_items[i] =new_item(marathi[i], NULL);
set_item_userptr(m_items[i], func);
}
my_items[n_choices] = (ITEM *)NULL;
e_items[e_choices] = (ITEM *)NULL;
h_items[h_choices] = (ITEM *)NULL;
m_items[m_choices] = (ITEM *)NULL;
my_menu = new_menu((ITEM**)my_items);
e_menu = new_menu((ITEM**)e_items);
h_menu = new_menu((ITEM**)h_items);
m_menu = new_menu((ITEM**)m_items);
/*Control will reach here when you exit from any language Section*/
read:
mvprintw(LINES - 3,0,"Press <Enter> to see the option selected");
mvprintw(LINES - 2,0,"EXIT to exit and up and down arrow keys to navigate");
attron(A_BOLD);
mvprintw(LINES / 2, COLS / 2 - 16, "!!!TICKET BOOKING PORTAL!!!");
attroff(A_BOLD);
post_menu(my_menu);
refresh();
/*Menu Operations Begin Here*/
while((c = getch()) != KEY_F(2)) {
switch(c) {
case KEY_DOWN:
menu_driver(my_menu,REQ_DOWN_ITEM);
if(pos != 3)
pos++;
mvprintw(LINES - 4,0, "the key is at %d", pos + 1);
break;
case KEY_UP:
menu_driver(my_menu, REQ_UP_ITEM);
if(pos != 0)
pos--;
mvprintw(LINES - 4,0, "the key is at %d", pos + 1);
break;
case 10 : {
ITEM *cur;
void (*p) (char *);
cur = current_item(my_menu);
p = item_userptr(cur);
p((char *)item_name(cur));
pos_menu_cursor(my_menu);
if(pos == 0) {
unpost_menu(my_menu);
/*Control will reach here if booking is cancelled*/
read1:
post_menu(e_menu);
refresh();
pos_menu_cursor(e_menu);
while((c = getch()) != KEY_F(2)) {
switch(c) {
case KEY_DOWN:
menu_driver(e_menu,REQ_DOWN_ITEM);
if(pos1 != 4)
pos1++;
mvprintw(LINES - 4,0, "the key is at %d", pos1 + 1);
break;
case KEY_UP:
menu_driver(e_menu, REQ_UP_ITEM);
if(pos1 != 0)
pos1--;
mvprintw(LINES - 4, 0, "the key is at %d", pos1 + 1);
break;
case 10:
if(pos1 == 4) {
unpost_menu(e_menu);
goto read;
}
else {
k = booking(e_menu, &n, &ch, &m);
if(k == 1) {
prize = billing(n, ch);
reciept('e', pos1, prize, n, ch);
getch();
goto read4;
}
else/*In case booking is cancelled*/
goto read1;
}
break;
}
}
}
else if(pos == 1) {
unpost_menu(my_menu);
read2:
post_menu(h_menu);
refresh();
pos_menu_cursor(h_menu);
while((c = getch()) != KEY_F(2)) {
switch(c) {
case KEY_DOWN:
menu_driver(h_menu,REQ_DOWN_ITEM);
if(pos2 != 4)
pos2++;
mvprintw(LINES - 4,0, "the key is at %d", pos2 + 1);
break;
case KEY_UP:
menu_driver(h_menu, REQ_UP_ITEM);
if(pos2 != 0)
pos2--;
mvprintw(LINES - 4, 0, "the key is at %d", pos2 + 1);
break;
case 10:
if(pos2 == 4) {
unpost_menu(h_menu);
goto read;
}
else {
k = booking(h_menu, &n, &ch, &m);
if(k == 1) {
prize = billing(n, ch);
reciept('h', pos2, prize, n, ch);
getch();
goto read4;
}
else
goto read2;
}
break;
}
}
}
else if(pos == 2) {
unpost_menu(my_menu);
read3:
post_menu(m_menu);
refresh();
pos_menu_cursor(m_menu);
while((c = getch()) != KEY_F(2)) {
switch(c) {
case KEY_DOWN:
menu_driver(m_menu,REQ_DOWN_ITEM);
if(pos3 != 4)
pos3++;
mvprintw(LINES - 4,0, "the key is at %d", pos3 + 1);
break;
case KEY_UP:
menu_driver(m_menu, REQ_UP_ITEM);
if(pos3 != 0)
pos3--;
mvprintw(LINES - 4, 0, "the key is at %d", pos3 + 1);
break;
case 10:
if(pos3 == 4) {
unpost_menu(m_menu);
goto read;
}
else {
k = booking(m_menu, &n, &ch, &m);
if(k == 1) {
prize = billing(n, ch);
reciept('m', pos3, prize, n, ch);
getch();
goto read4;
}
else
goto read3;
}
break;
}
}
}
else if(pos == 3) {
unpost_menu(my_menu);
read4:
for(i = 0;i < n_choices; ++i)
free_item(my_items[i]);
free_menu(my_menu);
for(i = 0;i < e_choices; ++i)
free_item(e_items[i]);
free_menu(e_menu);
for(i = 0;i < h_choices; ++i)
free_item(h_items[i]);
free_menu(h_menu);
for(i = 0;i < m_choices; ++i)
free_item(m_items[i]);
node *tmp;
fp = fopen("seats.txt","w");
matrix *o = &m;
fprintf(fp,"%d\n", o->n);
for(i = 0; i < o->n; i++) {
tmp = o->a[i];
for(j = 0; j < o->n; j++) {
fprintf(fp, "%c", tmp->type);
tmp = tmp->next;
}
fprintf(fp, "\n");
}
fclose(fp);
free_menu(m_menu);
endwin();
clear();
exit(0);
}
break;
}
break;
}
}
fclose(fp);
return 0;
}
void func(char *name) {
move(20, 0);
clrtoeol();
mvprintw(20, 0, "Item selected is: %s", name);
}
/*Reciept Printing Function*/
void reciept(char type, int pos, float prize, int n,char ch) {
int j;
printw("RECIEPT :\n");
if(type == 'e') {
printw("TYPE: %s\n", choices[0]);
for(j = 0;j < 5; j++)
if(pos == j)
printw("MOVIE: %s\n",english[pos]);
}
if(type == 'h') {
printw("LANGUAGE: %s\n", choices[1]);
for(j = 0;j < 5; j++)
if(pos == j)
printw("MOVIE: %s\n", hindi[pos]);
}
if(type == 'm') {
printw("LANGUAGE: %s\n", choices[2]);
for(j = 0;j < 5; j++)
if(pos == j)
printw("MOVIE: %s\n", marathi[pos]);
}
printw("TICKETS BOOKED = %d\n", n);
if(ch == 'p')
printw("TICKET CLASS : PLATINUM\n");
else if(ch =='g')
printw("TICKET CLASS : GOLD\n");
else if(ch == 's')
printw("TICKET CLASS: SILVER\n");
printw("BILL: Rs %f[Inclusive all Taxes and processing fee = 10 Rupees]\n", prize);
mvprintw(LINES / 2, COLS / 2, "THANK YOU");
return;
}
/*Booking is done Here*/
int booking(MENU *s_menu,int *n, char *ch, matrix *m) {
char c;
unpost_menu(s_menu);
initscr();
echo();
mvprintw(0, 0, "Type no.of tickets and <enter> and then press\n p - PLATINUM(Rate : 200Rs/head)\n g- GOLD(Rate : 150Rs/head)\n s - SILVER(Rate : 100Rs/head)\n");
move(LINES/2, COLS/2 - 18);
printw("How Many Tickets Do You Want??");
mvscanw(LINES / 2 + 1, COLS / 2 - 18,"%d", n);
mvprintw(LINES / 2 + 2,COLS / 2 - 18, "what type of seats do you want ??");
mvscanw(LINES / 2 +3, COLS / 2 -18, "%c", ch);
clear();
printmatrix(m, *n);
mvprintw(0, 0,"Do You Wish To Continue??");
mvprintw(LINES - 3,0,"Press \n <y> to continue");
mvprintw(LINES -1 , 0," Any key to go back");
mvscanw(1,0,"%c", &c);
refresh();
clear();
if(c == 'y')
return 1;
else
return 0;
}
/*billing is done here*/
float billing(int n, char ch) {
int val;
if (n == 0)
return 0;
float total, tax;
if(ch == 'p')
val = n * prate;
else if(ch == 'g')
val = n * grate;
else if(ch == 's')
val = n * srate;
tax = val * trate /100 + pf;
total = val + tax;
return total;
}
/*Code below will do the seat matrix operations using array of linked lists*/
void init(matrix *m, int n) {
int i, j;
node *k, *tmp, *l;
m->a = (node **)malloc(n * sizeof(node *));
m->n = n;
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
k = (node *)malloc(sizeof(node));
if(j > 0)
l->next = k;
k->type = 'O';
k->seat = j;
if(j == 0)
tmp = k;
if(j == n - 1)
k->next = NULL;
l = k;
}
m->a[i] = tmp;
}
}
void insertseat(matrix *m, int from, int to, char type) {
node *tmp;
tmp = m->a[from];
while(tmp->seat != to)
tmp = tmp->next;
tmp->type = type;
}
void printmatrix(matrix *m, int n) {
int i, j, k;
node *tmp;
mvprintw(LINES -6, 10,"Choose seat numbers by entering row(space)Column and enter");
mvprintw(LINES -5, 0,"P-> Platinum\nG-> Gold\nS->Silver\nB->Booked");
move(LINES / 2 - 1, COLS / 2);
printw(" ");
for(i = 0; i < m->n; i++)
printw("%d ", i + 1);
printf("\n");
for(i = 0; i < m->n; i++) {
tmp = m->a[i];
move(LINES / 2 + i, COLS / 2);
printw("%d ", i+1);
for(j = 0; j < m->n; j++) {
printw("%c ", tmp->type);
tmp = tmp->next;
}
printw("\n");
}
mvprintw(0, 10, "Choose %d seats\n", n);
echo();
for(k = 0; k < n; k++) {
scanw("%d %d", &i, &j);
insertseat(m, i -1, j - 1, 'B');
}
clear();
}
<file_sep>project : main.c
cc main.c -Wall -lncurses -lmenu -o project
clean :
rm -f *.o project
<file_sep>Name of project :MOVIE TICKET BOOKING PORTAL
Name: <NAME>
MIS:111403079
Description:
This project is used to book tickets for movie.You can book tickets for movies of three different languages.After selecting languages you can choose movie of your choice or return back to languages menu.After chosing a movie you will have to enter the number of seats and type of seats
after this a seat matrix will open and you can choose seats from available seats.After this a reciept will be shown on the screen.Linked list is used for seat matrix and 2-d arrays are used for menu operations.
| 0436d8938b5023fcf69f00af95e10d115eab8212 | [
"Markdown",
"C",
"Makefile"
]
| 3 | C | ranjansarwade/project | 9836993744874e27dbcfbfd4d1759c36231febf6 | e47c7e7f4fd8014aea7370d58106e0edf76b185b |
refs/heads/master | <file_sep>#include <stdio.h>
int fun(char *s)
{
char t[80];
int i, j;
for (i = 0; s[i]; i++) /*将串s拷贝至串t*/
t[i] = s[i];
t[i] = '\0';
for (i = 0, j = 0; t[i]; i++)
/*对于数字字符先写一个$符号,再写该数字字符*/
if (t[i] >= '0' && t[i] <= '9')
{
s[j++] = '$';
s[j++] = t[i];
}
/*对于非数字字符原样写入串s*/
else
s[j++] = t[i];
s[j] = '\0'; /*在串s结尾加结束标志*/
return 0;
}
int main()
{
char s[80];
printf("Enter a string:");
scanf("%s", s); /*输入字符串*/
fun(s);
printf("The result: %s\n", s); /*输出结果*/
return 0;
}
//24点游戏
#include<stdio.h>
char op[5] = { '#', '+', '-', '*', '/', };
float cal(float x, float y, int op)
{
switch (op)
{
case 1: return x + y;
case 2: return x - y;
case 3: return x*y;
case 4: return x / y;
default: return 0.0;
}
}
float calculate_model1(float i, float j, float k, float t, int op1, int op2, int op3)
{
float r1, r2, r3;
r1 = cal(i, j, op1);
r2 = cal(r1, k, op2);
r3 = cal(r2, t, op3);
return r3;
}
float calculate_model2(float i, float j, float k, float t, int op1, int op2, int op3)
{
float r1, r2, r3;
r1 = cal(j, k, op2);
r2 = cal(i, r1, op1);
r3 = cal(r2, t, op3);
return r3;
}
float calculate_model3(float i, float j, float k, float t, int op1, int op2, int op3)
{
float r1, r2, r3;
r1 = cal(k, t, op3);
r2 = cal(j, r1, op2);
r3 = cal(i, r2, op1);
return r3;
}
float calculate_model4(float i, float j, float k, float t, int op1, int op2, int op3)
{
float r1, r2, r3;
r1 = cal(j, k, op2);
r2 = cal(r1, t, op3);
r3 = cal(i, r2, op1);
return r3;
}
float calculate_model5(float i, float j, float k, float t, int op1, int op2, int op3)
{
float r1, r2, r3;
r1 = cal(i, j, op1);
r2 = cal(k, t, op3);
r3 = cal(r1, r2, op2);
return r3;
}
int get24(int i, int j, int k, int t)
{
int op1, op2, op3;
int flag = 0;
for (op1 = 1; op1 <= 4; op1++)
for (op2 = 1; op2 <= 4; op2++)
for (op3 = 1; op3 <= 4; op3++)
{
if (calculate_model1(i, j, k, t, op1, op2, op3) == 24)
{
printf("((%d%c%d)%c%d)%c%d=24\n", i, op[op1], j, op[op2], k, op[op3], t);
flag = 1;
}
if (calculate_model2(i, j, k, t, op1, op2, op3) == 24)
{
printf("(%d%c(%d%c%d))%c%d=24\n", i, op[op1], j, op[op2], k, op[op3], t);
flag = 1;
}
if (calculate_model3(i, j, k, t, op1, op2, op3) == 24)
{
printf("%d%c(%d%c(%d%c%d))=24\n", i, op[op1], j, op[op2], k, op[op3], t);
flag = 1;
}
if (calculate_model4(i, j, k, t, op1, op2, op3) == 24)
{
printf("%d%c((%d%c%d)%c%d)=24\n", i, op[op1], j, op[op2], k, op[op3], t);
flag = 1;
}
if (calculate_model5(i, j, k, t, op1, op2, op3) == 24)
{
printf("(%d%c%d)%c(%d%c%d)=24\n", i, op[op1], j, op[op2], k, op[op3], t);
flag = 1;
}
}
return flag;
}
int main()
{
int i, j, k, t;
printf("Please input four integer (1~10)\n");
loop: scanf("%d %d %d %d", &i, &j, &k, &t);
if (i<1 || i>10 || j<1 || j>10 || k<1 || k>10 || t<1 || t>10)
{
printf("Input illege, Please input again\n");
goto loop;
}
if (get24(i, j, k, t));
else
printf("Sorry, the four integer cannot be calculated to get 24\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
char gamer; // 玩家出拳
int computer; // 电脑出拳
int result; // 比赛结果
// 为了避免玩一次游戏就退出程序,可以将代码放在循环中
while (1){
printf("这是一个猜拳的小游戏,请输入你要出的拳头:\n");
printf("A:剪刀\nB:石头\nC:布\nD:不玩了\n");
scanf("%c%*c", &gamer);
switch (gamer){
case 65: //A
case 97: //a
gamer = 4;
break;
case 66: //B
case 98: //b
gamer = 7;
break;
case 67: //C
case 99: //c
gamer = 10;
break;
case 68: //D
case 100: //d
return 0;
default:
printf("你的选择为 %c 选择错误,退出...\n", gamer);
getchar();
system("cls"); // 清屏
return 0;
break;
}
srand((unsigned)time(NULL)); // 随机数种子
computer = rand() % 3; // 产生随机数并取余,得到电脑出拳
result = (int)gamer + computer; // gamer 为 char 类型,数学运算时要强制转换类型
printf("电脑出了");
switch (computer)
{
case 0:printf("剪刀\n"); break; //4 1
case 1:printf("石头\n"); break; //7 2
case 2:printf("布\n"); break; //10 3
}
printf("你出了");
switch (gamer)
{
case 4:printf("剪刀\n"); break;
case 7:printf("石头\n"); break;
case 10:printf("布\n"); break;
}
if (result == 6 || result == 7 || result == 11) printf("你赢了!");
else if (result == 5 || result == 9 || result == 10) printf("电脑赢了!");
else printf("平手");
system("pause>nul&&cls"); // 暂停并清屏
}
return 0;
} | ab4b797b4eef8ccf67218d71fd2cae04fea73fb7 | [
"C"
]
| 1 | C | wanyu990124/18_1114 | e68a336bf280891226a3d827074b44de71dfc76f | 70f59d341462491619b5d119fa4b2ab1791b08c2 |
refs/heads/main | <file_sep># NBA-Web-Scraper
A JSoup Web scraper app that returns 3 point average of searched player per game.
The application is implemented as a command line interface which accepts inputs until the player quits by typing "q".
Example output:

I have also implemented a few JUnit tests in the MainTest.java file to properly test the application.
<file_sep>import java.io.IOException;
import java.util.Scanner;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Main {
public static void main(String[] args) {
while (true){
Scanner playerInput = new Scanner(System.in);
System.out.println("Enter player name:");
String playerName = playerInput.nextLine().toLowerCase().trim();
String output = searchPlayer(playerName);
if(output.equals("q")){
break;
}
printResult(output);
}
}
public static String searchPlayer(String playerName){ //search for player
String searchURL = "https://www.basketball-reference.com/search/search.fcgi?search=" + playerName;
//quit the program
if (playerName.equals("q")){
return "q";
}
try {
Document doc = Jsoup.connect(searchURL).get();
Elements searchResults = doc.getElementsByClass("search-item-name");
try {
//get first result from search
Element result = searchResults.get(0);
String playerPageURL = "https://www.basketball-reference.com" + result.siblingElements().get(0).text();
return result.text() + "\n" + getStats(playerPageURL);
}catch (IndexOutOfBoundsException e){
return "No match found.";
}
} catch (IOException e) {
e.printStackTrace();
return "IO Error.";
}
}
public static String getStats(String URL){ //get stats from player page
try {
Document doc = Jsoup.connect(URL).get();
Element table = doc.getElementById("per_game");
Elements rows = table.getElementsByClass("full_table");
StringBuilder playerData = new StringBuilder();
for (Element row : rows){
String season = row.select("th[data-stat=season] a").text();
String threePointAverage = row.select("td[data-stat=fg3a_per_g]").text();
playerData.append(season).append(" ").append(threePointAverage).append("\n");
}
return String.valueOf(playerData);
} catch (IOException e) {
e.printStackTrace();
return "IO Error.";
}
}
public static void printResult(String result){
System.out.println(result);
}
}
<file_sep>import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class MainTest {
@Test
public void hasQuit(){
assertEquals("q", Main.searchPlayer("q"));
}
@Test
public void playerNotFound(){
assertEquals("No match found.",Main.searchPlayer("sdgsvshgdgsh"));
}
@Test
public void getStats(){
assertEquals("<NAME> (2014-2015)\n" +
"2013-14 3.4\n" +
"2014-15 2.7\n", Main.searchPlayer("pero antic"));
}
} | 39fea46467ccbc50bc7107769ae891d1c4459ee8 | [
"Markdown",
"Java"
]
| 3 | Markdown | kiriltofiloski/NBA-Web-Scraper | 9f748e15e11c45c1df5f337dd92e12b55b515045 | c146c80417c749450ce9aa80f5a9fb835eaddda9 |
refs/heads/master | <file_sep>package duke.dukeexception;
public class DukeToDoIllegalArgumentException extends DukeException {
public DukeToDoIllegalArgumentException() {
super("☹ OOPS!!! The description of a todo cannot be empty.");
}
}<file_sep>package duke.dukeexception;
public class DukeFindIllegalArgumentException extends DukeException {
public DukeFindIllegalArgumentException(String message) {
super("You have entered " + message + " keywords in your search");
}
}<file_sep>package duke.parser;
import java.util.ArrayList;
import duke.datetime.DateTime;
import duke.task.Task;
import duke.task.Deadline;
import duke.task.Event;
import duke.task.ToDo;
import duke.command.Command;
import duke.command.AddCommand;
import duke.command.DeleteCommand;
import duke.command.DoneCommand;
import duke.command.ExitCommand;
import duke.command.ListCommand;
import duke.command.FindCommand;
import duke.dukeexception.DukeException;
import duke.dukeexception.DukeIllegalArgumentException;
import duke.dukeexception.DukeToDoIllegalArgumentException;
import duke.dukeexception.DukeEventIllegalArgumentException;
import duke.dukeexception.DukeDeadlineIllegalArgumentException;
import duke.dukeexception.DukeDeleteIllegalArgumentException;
import duke.dukeexception.DukeSaveFileCorruptedError;
import duke.dukeexception.DukeFindIllegalArgumentException;
public class Parser {
public Parser() {
}
public static Command parse(String userInput) throws DukeException {
String[] newTaskSplit = userInput.split(" ");
String taskType = newTaskSplit[0];
switch(taskType) {
case "list":
return new ListCommand();
case "bye":
return new ExitCommand();
case "done":
int completedTaskNum = parseDoneCommand(newTaskSplit);
return new DoneCommand(completedTaskNum);
case "delete":
int deletionNum = parseDeleteCommand(newTaskSplit);
return new DeleteCommand(deletionNum);
case "event":
Task newEvent = parseAddEventCommand(newTaskSplit);
return new AddCommand(newEvent);
case "deadline":
Task newDeadline = parseAddDeadlineCommand(newTaskSplit);
return new AddCommand(newDeadline);
case "todo":
Task newToDo = parseAddToDoCommand(newTaskSplit);
return new AddCommand(newToDo);
case "find":
String keyword = parseFindCommand(newTaskSplit);
return new FindCommand(keyword);
default:
throw new DukeIllegalArgumentException();
}
}
public static int parseDoneCommand(String[] newTaskSplit) {
int completedTaskNum = Integer.parseInt(newTaskSplit[1]) - 1;
assert completedTaskNum > 0;
return completedTaskNum;
}
private static int parseDeleteCommand(String[] newTaskSplit) throws DukeDeleteIllegalArgumentException {
int newTaskLen = newTaskSplit.length;
if (newTaskLen < 2) {
throw new DukeDeleteIllegalArgumentException("You have not entered a number for deletion");
} else if (newTaskLen > 2) {
throw new DukeDeleteIllegalArgumentException("You have entered too many arguments for deletion");
} else {
try {
return Integer.parseInt(newTaskSplit[1]) - 1;
} catch (NumberFormatException e) {
throw new DukeDeleteIllegalArgumentException("Please enter a valid number for deletion");
} catch (IndexOutOfBoundsException e) {
throw new DukeDeleteIllegalArgumentException("Please enter a valid number within the range");
}
}
}
private static ToDo parseAddToDoCommand(String[] newTaskSplit) throws DukeToDoIllegalArgumentException {
try {
int newTaskLen = newTaskSplit.length;
String description = newTaskSplit[1];
for (int i = 2; i < newTaskLen; i++) {
description += " " + newTaskSplit[i];
}
ToDo newToDo = new ToDo(description);
return newToDo;
} catch (ArrayIndexOutOfBoundsException e) {
throw new DukeToDoIllegalArgumentException();
}
}
private static Deadline parseAddDeadlineCommand(String[] newTaskSplit) throws DukeDeadlineIllegalArgumentException {
try {
int newTaskLen = newTaskSplit.length;
boolean foundDeadline = false;
String description = newTaskSplit[1];
String deadlineTimeString = "";
for (int i = 2; i < newTaskLen; i++) {
if (foundDeadline) {
if (i == newTaskLen - 1) {
deadlineTimeString += newTaskSplit[i];
} else {
deadlineTimeString += newTaskSplit[i] + " ";
}
} else {
if (newTaskSplit[i].equals("/by")) {
foundDeadline = true;
} else {
description += " " + newTaskSplit[i];
}
}
}
if (foundDeadline) {
DateTime deadlineTime = convertDateTime(deadlineTimeString);
Deadline newDeadline = new Deadline(description, deadlineTime);
return newDeadline;
} else {
throw new DukeDeadlineIllegalArgumentException("deadline");
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new DukeDeadlineIllegalArgumentException("description");
}
}
private static Event parseAddEventCommand(String[] newTaskSplit) throws DukeEventIllegalArgumentException {
try {
int newTaskLen = newTaskSplit.length;
boolean foundEvent = false;
String description = newTaskSplit[1];
String eventTimeString = "";
for (int i = 2; i < newTaskLen; i++) {
if (foundEvent) {
if (i == newTaskLen - 1) {
eventTimeString += newTaskSplit[i];
} else {
eventTimeString += newTaskSplit[i] + " ";
}
} else {
if (newTaskSplit[i].equals("/at")) {
foundEvent = true;
} else {
description += " " + newTaskSplit[i];
}
}
}
if (foundEvent) {
DateTime eventTime = convertDateTime(eventTimeString);
return new Event(description, eventTime);
} else {
throw new DukeEventIllegalArgumentException("event timing");
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new DukeEventIllegalArgumentException("description");
}
}
private static String parseFindCommand(String[] newTaskSplit) throws DukeFindIllegalArgumentException {
int newTaskLen = newTaskSplit.length;
if (newTaskLen == 2) {
return newTaskSplit[1];
} else if (newTaskLen > 2) {
throw new DukeFindIllegalArgumentException("too many");
} else {
throw new DukeFindIllegalArgumentException("too few");
}
}
public static ArrayList<Task> findTasksByKeyword(String keyword, ArrayList<Task> taskArrayList) {
assert keyword.length() > 0;
ArrayList<Task> searchResultArrayList = new ArrayList<Task>();
for (Task task : taskArrayList) {
String[] descriptionSplit = task.getDescription().split(" ");
boolean keyWordFound = false;
for (String word : descriptionSplit) {
if (word.equals(keyword)) {
keyWordFound = true;
break;
}
}
if (keyWordFound) {
searchResultArrayList.add(task);
}
}
return searchResultArrayList;
}
private static DateTime convertDateTime(String dateTimeString) {
assert dateTimeString.length() > 0;
String[] dateTimeStringSplit = dateTimeString.split(" ");
String[] dateStringSplit = dateTimeStringSplit[0].split("/");
int day = Integer.parseInt(dateStringSplit[0]);
int month = Integer.parseInt(dateStringSplit[1]);
int year = Integer.parseInt(dateStringSplit[2]);
int time = Integer.parseInt(dateTimeStringSplit[1]);
return new DateTime(day, month, year, time, dateTimeString);
}
public static Task parseSaveData(String newTaskString) throws DukeSaveFileCorruptedError {
String[] newTaskSplit = newTaskString.split(" \\| ");
String taskType = newTaskSplit[0];
boolean taskIsDone = Integer.parseInt(newTaskSplit[1]) == 1;
String description = newTaskSplit[2];
Task newTask;
switch(taskType) {
case "T":
newTask = new ToDo(description);
break;
case "D":
DateTime deadlineTime = convertDateTime(newTaskSplit[3]);
newTask = new Deadline(description, deadlineTime);
break;
case "E":
DateTime eventTime = convertDateTime(newTaskSplit[3]);
newTask = new Event(description, eventTime);
break;
default:
throw new DukeSaveFileCorruptedError();
}
if (taskIsDone) {
newTask.taskComplete();
}
return newTask;
}
}
<file_sep>package duke.dukeexception;
public class DukeSaveFileCorruptedError extends DukeException {
public DukeSaveFileCorruptedError() {
super("The save file is corrupted. Creating new save file...");
}
}<file_sep>package duke.command;
import java.util.ArrayList;
import duke.tasklist.TaskList;
import duke.ui.Ui;
import duke.storage.Storage;
import duke.task.Task;
import duke.parser.Parser;
public class FindCommand extends Command {
private String keyword;
public FindCommand(String keyword) {
this.keyword = keyword;
}
@Override
public void execute(TaskList taskList, Ui ui, Storage storage) {
ArrayList<Task> searchResultTaskList = Parser.findTasksByKeyword(keyword, taskList.getTaskList());
int searchResultTaskListLen = searchResultTaskList.size();
String[] taskDescriptionArray = new String[searchResultTaskListLen];
for (int i = 0; i < searchResultTaskListLen; i++) {
taskDescriptionArray[i] = searchResultTaskList.get(i).toString();
}
ui.showSearchResult(taskDescriptionArray);
}
@Override
public boolean isExit() {
return false;
}
}
<file_sep>package duke.ui;
import java.util.Scanner;
public class Ui {
private Scanner sc;
private String output;
public Ui() {
sc = new Scanner(System.in);
}
public String readCommand() {
return sc.nextLine();
}
public void showAddTaskMessage(String taskDescription, int listSize) {
output = "Got it. I've added this task:\n"
+ taskDescription
+ "\nNow you have " + listSize + " tasks in the list.";
}
public void showDeleteTaskMessage(String taskDescription, int listSize) {
output = "Noted. I've removed this task: \n"
+ taskDescription
+ "\nNow you have " + listSize + " tasks in the list.";
}
public void showDoneMessage(String taskDescription) {
output = "Nice! I've marked this task as done: \n" + taskDescription;
}
public void showList(String[] taskDescriptionArray) {
int taskLen = taskDescriptionArray.length;
if (taskLen == 0) {
System.out.println("You do not have any tasks in your list");
} else {
output = "Here are the tasks in your list: ";
for (int i = 0; i < taskLen; i ++) {
String taskDescription = taskDescriptionArray[i];
output += "\n" + (i + 1) + "." + taskDescription;
}
}
}
public void showSearchResult(String[] taskDescriptionArray) {
int taskLen = taskDescriptionArray.length;
if (taskLen == 0) {
output = "There are no matching tasks in your list";
} else {
output = "Here are the matching tasks in your list: ";
for (int i = 0; i < taskLen; i ++) {
String taskDescription = taskDescriptionArray[i];
output += "\n" + (i + 1) + "." + taskDescription;
}
}
}
public void showWelcome() {
String logo = " ____ _ \n"
+ "| _ \\ _ _| | _____ \n"
+ "| | | | | | | |/ / _ \\\n"
+ "| |_| | |_| | < __/\n"
+ "|____/ \\__,_|_|\\_\\___|\n";
String welcomeMessage = "Hello! I'm Duke\n" + "What can I do for you?";
output = "Hello from\n" + logo;
output += getLine();
output += welcomeMessage;
output += getLine();
}
private String getLine() {
return "____________________________________________________________";
}
public void showLoadingError() {
output = "No save file found... creating new save file";
}
public void showError(String errorMessage) {
output = errorMessage;
}
public void showExit() {
output = "Bye. Hope to see you again soon!";
}
public String getOutput() {
return output;
}
}<file_sep>package duke.command;
import duke.tasklist.TaskList;
import duke.task.Task;
import duke.ui.Ui;
import duke.storage.Storage;
import java.util.ArrayList;
public class ListCommand extends Command {
@Override
public void execute(TaskList taskList, Ui ui, Storage storage) {
ArrayList<Task> taskListArray = taskList.getTaskList();
int taskListSize = taskListArray.size();
String[] taskDescriptionArray = new String[taskListSize];
for (int i = 0; i < taskListSize; i++) {
taskDescriptionArray[i] = taskListArray.get(i).toString();
}
ui.showList(taskDescriptionArray);
}
@Override
public boolean isExit() {
return false;
}
}<file_sep>package duke.dukeexception;
public class DukeDeadlineIllegalArgumentException extends DukeException {
public DukeDeadlineIllegalArgumentException(String fieldName) {
super("☹ OOPS!!! The " + fieldName + " of a deadline cannot be empty.");
}
}
<file_sep>package duke.dukeexception;
public class DukeDeleteIllegalArgumentException extends DukeException {
public DukeDeleteIllegalArgumentException(String message) {
super(message);
}
}<file_sep># User Guide
Welcome to Duke, a simple and easy-to-use chat bot that will help manage your tasks.
## Features
### Add new tasks
Duke allows you to add new Events, Deadlines or To Do tasks to your list of tasks.
### Mark a task as completed
Once a task is added, you can then update Duke once you have completed the task.
### Find tasks by keyword
You can also filter tasks according to the keyword you input.
### List all tasks
You may also enter a command and Duke will list your current tasks.
### Delete a task
Duke also allows you to delete a task when you no longer need it.
## Usage
### `help` - Display user commands
The help command brings up a list of tasks the user can use in Duke.
Expected outcome:
Welcome to Duke. The following are a list of possible commands:
todo <description> --- Creates a ToDo task
deadline <description> /by <dd/mm/yy hhmm> --- Creates a Deadline task
event <description> /at <dd/mm/yy hhmm> --- Creates an Event task
list --- Lists all tasks
done <task number> --- Mark a task as completed
delete <task number> --- Delete a task
help --- Display the help menu
bye --- Exit Duke
### `todo` - Add a To Do task
Example of usage:
`todo CS2100 Tutorial`
Expected outcome:
```
Got it. I have added this task:
[T][✗] CS2100 Tutorial
Now you have 1 tasks in the list.
```
### `event` - Add an Event task
Example of usage:
`event Sister's Birthday /at 20/10/19 1900`
Expected outcome:
```
Got it. I have added this task:
[E][✗] Sister's Birthday (at: 20th of October 2019, 7pm)
Now you have 1 tasks in the list.
```
### `deadline` - Add a Deadline task
Example of usage:
`deadline CS2103T Post Lecture Quiz /by 30/9/19 2359`
Expected outcome:
```
Got it. I have added this task:
[D][✗] CS2103T Post Lecture Quiz (by: 30th of September 2019, 11.59pm)
Now you have 1 tasks in the list.
```
### `done` - Mark a task as complete
The user also inputs the number of the task he completed.
Example of usage:
`done 2`
Expected outcome:
```
Nice! I've marked this task as done:
[D][✓] CS2103T Post Lecture Quiz (by: 30th of September 2019, 11.59pm)
```
### `find` - Find tasks containing a keyword
The user also inputs the keyword that he is searching for.
Example of usage:
`find CS2100`
Expected outcome:
```
Here are the matching tasks in your list:
1.[T][✗] CS2100 Tutorial
```
### `list` - List all tasks in Duke
Expected outcome:
```
Here are the matching tasks in your list:
1.[T][✗] CS2100 Tutorial
2.[E][✗] Sister's Birthday (at: 20th of October 2019, 7pm)
3.[D][✓] CS2103T Post Lecture Quiz (by: 30th of September 2019, 11.59pm)
```
### `delete` - Delete a task in Duke
The user also inputs the number of the task to delete.
Example of usage:
`delete 1`
Expected outcome:
```
Noted. I've removed this task:
[E][✗] Sister's Birthday (at: 20th of October 2019, 7pm)
Now you have 2 tasks in the list.
```
### `bye` - Close Duke
Exits the Duke application.
<file_sep>package duke.tasklist;
import java.util.ArrayList;
import duke.task.Task;
public class TaskList {
private ArrayList<Task> taskList;
public TaskList(ArrayList<Task> taskList) {
this.taskList = taskList;
}
public TaskList() {
this.taskList = new ArrayList<Task>();
}
public void addTask(Task newTask) {
taskList.add(newTask);
}
public Task deleteTask(int index) throws IndexOutOfBoundsException{
return taskList.remove(index);
}
public Task completeTask(int completedTaskIndex) {
Task completedTask = taskList.get(completedTaskIndex);
completedTask.taskComplete();
return completedTask;
}
public ArrayList<Task> getTaskList() {
return taskList;
}
public int getListSize() {
return taskList.size();
}
} | b9dd54108bfcfdf367e0f13f3d658c19ac90f7a8 | [
"Markdown",
"Java"
]
| 11 | Java | gabrielseow/duke | 01ae30674cd4c5fde292ed0ea1390020cc222cad | 2cfd0f46e7a030edec475a8f4b54653732d8d052 |
refs/heads/master | <repo_name>Vasyl-Zakharuk/IWillRead<file_sep>/App.js
import React, {useState} from 'react'
import { StyleSheet, Text, View, FlatList } from 'react-native'
import { Navbar } from './src/components/Navbar'
import { MainScreen } from './src/screens/MainScreen'
import { TodoScreen } from './src/screens/TodoScreen'
export default function App() {
const [todoId, setTodoId] = useState(null)
const [todos, setTodos] = useState([
{ id: '1', title: 'test' },
{id: '2', title: 'test2'}
])
const addTodo = (title) => {
setTodos(prev => [
...prev,
{
id: Date.now().toString(),
title
}
])
}
const removeTodo = id => {
setTodos(prev => prev.filter(todo => todo.id !== id))
}
let content = (
<MainScreen
todos={todos}
addTodo={addTodo}
removeTodo={removeTodo}
openTodo={setTodoId}
/>
)
if (todoId) {
const selectedTogo= todos.find(todo => todo.id === todoId)
content = <TodoScreen goBack={() => setTodoId(null)} todo={selectedTogo} />
}
return (
<View>
<Navbar title='I wiil read' />
<View style={styles.container}>{content}</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
paddingHorizontal: 30,
paddingVertical: 20
}
})
<file_sep>/src/screens/TodoScreen.js
import React from 'react'
import { StyleSheet, View, Text, Button } from 'react-native'
export const TodoScreen = ({goBack, todo}) => {
return (
<View>
<Text>{ todo.title}</Text>
<Button title='Back' onPress={goBack} />
</View>
)
}
const styles = StyleSheet.create({}) | e0bc45e7e010c9a659f7cdb4d3c950ca246f28e0 | [
"JavaScript"
]
| 2 | JavaScript | Vasyl-Zakharuk/IWillRead | d8acdbd4667559ac529d6b1f93fc4ddd6c0538a4 | 3ff5cbe4e18bb81f973dcbba2fa05704e1edc97a |
refs/heads/master | <repo_name>azmifauzan/LenKTPelKiosLibUsb<file_sep>/main.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <Windows.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <direct.h>
int portnumber = 999;
char isiBuffer[102400];
char isiInfo[100];
char isiClose[25];
char isiPoll[100];
char isiPut[100];
char isiReset[25];
char isiPut[100];
char isiFinger[50];
char isiLog[102400];
char isiDemog[18096];
char isiSwitch[50];
char isiDisplay[50];
char isiSetpow[50];
char isiRespow[50];
char isiUpdateInit[50];
char isiUpdateFile[50];
char isiUpdateFinish[50];
int tid = 1;
int nunggurespon = 0, resput = 0, resinfo = 0, resclose = 0, respoll = 0, resreset = 0, resfinger = 0;
int reslog = 0, resdemog = 0, resswitch = 0, resdisplay = 0, ressetpow = 0, resrespow = 0;
int resupdateinit = 0, resupdatefile = 0, resupdatefinish = 0;
int openstatus = 0;
HANDLE hComm;
BOOL br = FALSE;
char hasil2[1024];
int kirimcmd = 0;
int lastReaderStatus = 0, lastPutKtpStatus = 0, lastVerifyFingerStatus = 0, lastDeviceStatus = 0, portInUse = 0;
char* sendCommandOP(char* port, char* command)
{
char ComPortName[] = "\\\\.\\";
strcat(ComPortName,port);
BOOL Status;
DWORD dwEventMask;
char TempChar;
DWORD NoBytesRead;
char SerialBuffer[1024];
int i = 0;
char hasil3[100];
char mylog[102400];
sprintf(mylog,"===SendCommand===Begin process");
tulisLog(mylog);
sprintf(mylog,"Trying to established connection in %s",port);
tulisLog(mylog);
hComm = CreateFile( ComPortName, // Name of the Port to be Opened
GENERIC_READ | GENERIC_WRITE, // Read/Write Access
0, // No Sharing, ports cant be shared
NULL, // No Security
OPEN_EXISTING, // Open existing port only
0, // Non Overlapped I/O
NULL); // Null for Comm Devices
if (hComm == INVALID_HANDLE_VALUE){
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to established connection in COM%d, error number:%d",portnumber,GetLastError());
tulisLog(mylog);
}
DCB dcbSerialParams = { 0 };
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
sprintf(mylog,"Trying to GetCommState");
tulisLog(mylog);
Status = GetCommState(hComm, &dcbSerialParams);
if (Status == FALSE){
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to GetCommState, error number:%d",GetLastError());
tulisLog(mylog);
}
dcbSerialParams.BaudRate = CBR_115200; // Setting BaudRate = 9600
dcbSerialParams.ByteSize = 8; // Setting ByteSize = 8
dcbSerialParams.StopBits = ONESTOPBIT; // Setting StopBits = 1
dcbSerialParams.Parity = NOPARITY; // Setting Parity = None
sprintf(mylog,"Trying to SetCommState");
tulisLog(mylog);
Status = SetCommState(hComm, &dcbSerialParams);
if (Status == FALSE)
{
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to SetCommState, error number:%d",GetLastError());
tulisLog(mylog);
}
COMMTIMEOUTS timeouts = { 0 };
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutMultiplier = 0;
sprintf(mylog,"Trying to SetCommTimeouts");
tulisLog(mylog);
if (SetCommTimeouts(hComm, &timeouts) == FALSE){
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to SetCommTimeouts, error number:%d",GetLastError());
tulisLog(mylog);
}
int pjg = strlen(command);
char lpBuffer[pjg+1];
strcpy(lpBuffer,command);
DWORD dNoOFBytestoWrite;
DWORD dNoOfBytesWritten = 0;
dNoOFBytestoWrite = sizeof(lpBuffer);
sprintf(mylog,"Trying to send command:%s",command);
tulisLog(mylog);
Status = WriteFile(hComm, // Handle to the Serialport
lpBuffer, // Data to be written to the port
dNoOFBytestoWrite, // No of bytes to write into the port
&dNoOfBytesWritten, // No of bytes written to the port
NULL);
free(lpBuffer);
if (Status == FALSE){
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to send command, error number:%d",GetLastError());
tulisLog(mylog);
}
sprintf(mylog,"Trying to SetCommMask");
tulisLog(mylog);
Status = SetCommMask(hComm, EV_RXCHAR);
if (Status == FALSE){
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to SetCommMask, error number:%d",GetLastError());
tulisLog(mylog);
}
sprintf(mylog,"Trying to Set WaitCommEvent");
tulisLog(mylog);
Status = WaitCommEvent(hComm, &dwEventMask, NULL);
if (Status == FALSE)
{
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to Set WaitCommEvent, error number:%d",GetLastError());
tulisLog(mylog);
}
else
{
int err;
do
{
Status = ReadFile(hComm, &TempChar, sizeof(TempChar), &NoBytesRead, NULL);
err = GetLastError();
SerialBuffer[i] = TempChar;
i++;
}
while (NoBytesRead > 0 && err != ERROR_IO_PENDING);
sprintf(mylog,"Receive buffer:%s",SerialBuffer);
tulisLog(mylog);
int j =0;
for (j = 0; j < i-1; j++)
{
hasil3[j] = SerialBuffer[j];
}
}
//free(SerialBuffer);
memset(SerialBuffer,0,sizeof(SerialBuffer));
sprintf(mylog,"===SendCommand===End process");
tulisLog(mylog);
return hasil3;
}
char* OpenOnly(char* port)
{
// char mylog[1024];
// sprintf(mylog,"send command:%s",command);
// tulisLog(mylog);
char mylog[1024];
sprintf(mylog,"===Open COM===Begin process");
tulisLog(mylog);
char ComPortName[] = "\\\\.\\";
strcat(ComPortName,port);
BOOL Status;
char hasil3[100];
sprintf(hasil3,"success");
sprintf(mylog,"Trying to established connection in COM%d",port);
tulisLog(mylog);
hComm = CreateFile( ComPortName, // Name of the Port to be Opened
GENERIC_READ | GENERIC_WRITE, // Read/Write Access
0, // No Sharing, ports cant be shared
NULL, // No Security
OPEN_EXISTING, // Open existing port only
0, // Non Overlapped I/O
NULL); // Null for Comm Devices
if (hComm == INVALID_HANDLE_VALUE){
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to established connection in COM%d, error number:%d",portnumber,GetLastError());
tulisLog(mylog);
}
DCB dcbSerialParams = { 0 };
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
sprintf(mylog,"Trying to GetCommState");
tulisLog(mylog);
Status = GetCommState(hComm, &dcbSerialParams);
if (Status == FALSE){
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to GetCommState, error number:%d",GetLastError());
tulisLog(mylog);
}
dcbSerialParams.BaudRate = CBR_115200; // Setting BaudRate = 9600
dcbSerialParams.ByteSize = 8; // Setting ByteSize = 8
dcbSerialParams.StopBits = ONESTOPBIT; // Setting StopBits = 1
dcbSerialParams.Parity = NOPARITY; // Setting Parity = None
dcbSerialParams.fAbortOnError = TRUE;
sprintf(mylog,"Trying to SetCommState");
tulisLog(mylog);
Status = SetCommState(hComm, &dcbSerialParams);
if (Status == FALSE)
{
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to SetCommState, error number:%d",GetLastError());
tulisLog(mylog);
}
COMMTIMEOUTS timeouts = { 0 };
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutMultiplier = 0;
sprintf(mylog,"Trying to SetCommTimeouts");
tulisLog(mylog);
if (SetCommTimeouts(hComm, &timeouts) == FALSE){
sprintf(hasil3,"opendevicefailed#");
sprintf(mylog,"Failed to SetCommTimeouts, error number:%d",GetLastError());
tulisLog(mylog);
}
sprintf(mylog,"===Open COM===End process");
tulisLog(mylog);
return hasil3;
}
char* sendCommandSR(char* port, char* command, int timeout)
{
char mylog[1024];
sprintf(mylog,"send command:%s",command);
tulisLog(mylog);
HANDLE hComm2;
char ComPortName[] = "\\\\.\\";
strcat(ComPortName,port);
BOOL Status;
char TempChar;
DWORD NoBytesRead;
int i = 0;
hComm2 = CreateFile( ComPortName, // Name of the Port to be Opened
GENERIC_READ | GENERIC_WRITE, // Read/Write Access
0, // No Sharing, ports cant be shared
NULL, // No Security
OPEN_EXISTING, // Open existing port only
FILE_FLAG_OVERLAPPED, // Overlapped I/O
NULL); // Null for Comm Devices
if (hComm2 == INVALID_HANDLE_VALUE){
sprintf(hasil2,"opendevicefailed#");
CloseHandle(hComm2);
return hasil2;
}
DCB dcbSerialParams = { 0 };
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
Status = GetCommState(hComm2, &dcbSerialParams);
if (Status == FALSE){
sprintf(hasil2,"opendevicefailed#");
CloseHandle(hComm2);
return hasil2;
}
dcbSerialParams.BaudRate = CBR_115200; // Setting BaudRate = 9600
dcbSerialParams.ByteSize = 8; // Setting ByteSize = 8
dcbSerialParams.StopBits = ONESTOPBIT; // Setting StopBits = 1
dcbSerialParams.Parity = NOPARITY; // Setting Parity = None
//dcbSerialParams.fAbortOnError = TRUE;
Status = SetCommState(hComm2, &dcbSerialParams);
if (Status == FALSE)
{
sprintf(hasil2,"opendevicefailed#");
CloseHandle(hComm2);
return hasil2;
}
COMMTIMEOUTS timeouts = { 0 };
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutMultiplier = 0;
if (SetCommTimeouts(hComm2, &timeouts) == FALSE){
sprintf(hasil2,"opendevicefailed#");
CloseHandle(hComm2);
return hasil2;
}
int pjg = strlen(command);
char lpBuffer[pjg+1];
strcpy(lpBuffer,command);
DWORD dNoOFBytestoWrite,dwOvRes;
DWORD dNoOfBytesWritten = 0;
OVERLAPPED osWrite = { 0 };
osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osWrite.hEvent == NULL){
sprintf(hasil2,"opendevicefailed#");
CloseHandle(hComm2);
return hasil2;
}
dNoOFBytestoWrite = sizeof(lpBuffer);
BOOL okw = WriteFile(hComm2, lpBuffer, dNoOFBytestoWrite, &dNoOfBytesWritten, &osWrite);
if(!okw){
DWORD err = GetLastError();
if(err != ERROR_IO_PENDING)
{
sprintf(hasil2,"timeoutwrite#");
CloseHandle(hComm2);
return hasil2;
}
DWORD reason = WaitForSingleObject(osWrite.hEvent,INFINITE);
switch(reason){
case WAIT_OBJECT_0:
break;
case WAIT_OBJECT_0+1:
break;
}
}
CloseHandle(osWrite.hEvent);
Status = SetCommMask(hComm2, EV_RXCHAR);
if (Status == FALSE){
sprintf(hasil2,"opendevicefailed#");
CloseHandle(hComm2);
return hasil2;
}
OVERLAPPED osRead = { 0 };
osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osRead.hEvent == NULL){
sprintf(hasil2,"error#open device failed");
CloseHandle(hComm2);
return hasil2;
}
BOOL readstat = TRUE;
BOOL adaisi = FALSE;
int counter = 0;
while(readstat){
BOOL okr = ReadFile(hComm2,&TempChar, sizeof(TempChar), &NoBytesRead, &osRead);
if(!okr)
{
DWORD err = GetLastError();
if(err != ERROR_IO_PENDING)
{
readstat = FALSE;
continue;
}
DWORD result = WaitForSingleObject(osRead.hEvent,100);
switch(result){
case WAIT_OBJECT_0:
if(!GetOverlappedResult(hComm2,&osRead,&dwOvRes,FALSE)){
readstat = FALSE;
continue;
}
if(dwOvRes == 1){
hasil2[i] = TempChar;
i++;
adaisi = TRUE;
if(TempChar == ';'){
readstat = FALSE;
continue;
}
}
break;
case WAIT_OBJECT_0 + 1:
break;
case WAIT_TIMEOUT:{
readstat = FALSE;
}
break;
}
}
counter++;
if(counter > timeout*15 && adaisi == FALSE){
sprintf(hasil2,"timeoutread#");
CloseHandle(osRead.hEvent);
CloseHandle(hComm2);
return hasil2;
}
}
CloseHandle(osRead.hEvent);
CloseHandle(hComm2);
return hasil2;
}
void parsingIsi()
{
//printf("\nisi buffer:%s\n",isiBuffer);
char mylog[102400];
//sprintf(mylog,"receive buffer:%s",isiBuffer);
//tulisLog(mylog);
//PurgeComm(hComm,PURGE_RXCLEAR|PURGE_TXCLEAR);
//portInUse = 0;
if(isiBuffer[0] == '$'){
char *hdr = strtok(isiBuffer,"#");
char *isi = strtok(NULL,"#");
if(strcmp(hdr,"$demog") == 0){
sprintf(mylog,"receive buffer: data demografi");
}
else if(strcmp(hdr,"$machinelg") == 0){
sprintf(mylog,"receive buffer: data log");
}
else{
sprintf(mylog,"receive buffer:%s",isi);
}
if(strcmp(hdr,"$poll") == 0){
strcpy(isiPoll,isi);
respoll = 1;
}
else if(strcmp(hdr,"$info") == 0){
strcpy(isiInfo,isi);
resinfo = 1;
}
else if(strcmp(hdr,"$close") == 0){
strcpy(isiClose,isi);
resclose = 1;
}
else if(strcmp(hdr,"$putktp") == 0){
strcpy(isiPut,isi);
resput = 1;
}
else if(strcmp(hdr,"$reset") == 0){
strcpy(isiReset,isi);
resreset = 1;
}
else if(strcmp(hdr,"$finger") == 0){
strcpy(isiFinger,isi);
resfinger = 1;
}
else if(strcmp(hdr,"$demog") == 0){
strcpy(isiDemog,isi);
resdemog = 1;
}
else if(strcmp(hdr,"$machinelg") == 0){
strcpy(isiLog,isi);
reslog = 1;
}
else if(strcmp(hdr,"$switch") == 0){
strcpy(isiSwitch,isi);
resswitch = 1;
}
else if(strcmp(hdr,"$display") == 0){
strcpy(isiDisplay,isi);
resdisplay = 1;
}
else if(strcmp(hdr,"$setpow") == 0){
strcpy(isiSetpow,isi);
ressetpow = 1;
}
else if(strcmp(hdr,"$respow") == 0){
strcpy(isiRespow,isi);
resrespow = 1;
}
else if(strcmp(hdr,"$updateinit") == 0){
strcpy(isiUpdateInit,isi);
resupdateinit = 1;
}
else if(strcmp(hdr,"$updatefile") == 0){
strcpy(isiUpdateFile,isi);
resupdatefile = 1;
}
else if(strcmp(hdr,"$updatefinish") == 0){
strcpy(isiUpdateFinish,isi);
resupdatefinish = 1;
}
free(hdr);
free(isi);
//free(isiBuffer);
memset(isiBuffer,0,sizeof(isiBuffer));
tulisLog(mylog);
}
}
void *threadRespon(void *x)
{
char TempChar;
DWORD NoBytesRead;
int i = 0;
BOOL simpanData = FALSE;
char dataSebelum = '\0';
do
{
ReadFile(hComm, &TempChar, sizeof(TempChar), &NoBytesRead, NULL);
//printf("c:%c ,",TempChar);
while(br == TRUE){Sleep(10);}
//printf("temp:%c\n,",TempChar);
if(TempChar == '$'){
simpanData = TRUE;
}
if(simpanData){
isiBuffer[i] = TempChar;
//isiBuffer[i] = '0';
i++;
}
if(TempChar == ';'){
if(dataSebelum != ';'){
simpanData = FALSE;
parsingIsi();
}
i = 0;
}
dataSebelum = TempChar;
}
while (nunggurespon == 0);
//printf("\n thread selesai.\n");
}
int searchreader()
{
if(portnumber == 999)
{
char folde[FILENAME_MAX];
_getcwd(folde,FILENAME_MAX);
char pathfile[5000];
sprintf(pathfile,"%s\\LenKTPelKiosLibUsb.l",folde);
FILE *fp;
char buff[255];
int porttemp = 1;
fp = fopen(pathfile,"r");
if (fp != NULL){
fscanf(fp, "%s", buff);
porttemp = atoi(buff);
}
fclose(fp);
if(porttemp != 0){
char scport2[5];
sprintf(scport2,"COM%d",porttemp);
char* hasil2 = sendCommandSR(scport2,"ektpack#;",10);
char *split12 = strtok(hasil2,"#");
char *split22 = strtok(NULL,"#");
if(strcmp(split12,"$ack") == 0 && strcmp(split22,"len442ektpreader") == 0){
portnumber = porttemp;
}
free(hasil2);
free(split12);
free(split22);
}
if(portnumber == 999)
{
int i=0;
for(i=1; i<=50; i++){
char scport[5];
sprintf(scport,"COM%d",i);
char* hasil = sendCommandSR(scport,"ektpack#;",10);
//int c = 0;
//char **arr = NULL;
//c = split(hasil, '#', &arr);
char *split1 = strtok(hasil,"#");
char *split2 = strtok(NULL,"#");
if(strcmp(split1,"$ack") == 0 && strcmp(split2,"len442ektpreader") == 0){
portnumber = i;
break;
}
free(hasil);
free(split1);
free(split2);
//free(arr);
}
FILE *fp;
fp = fopen(pathfile, "w");
if (fp != NULL){
char myport[5];
sprintf(myport,"%d",portnumber);
fputs(myport, fp);
}
fclose(fp);
}
}
//free(hasil2);
memset(hasil2,0,sizeof(hasil2));
return portnumber;
}
int sendCommandOnly(char* command)
{
// if(kirimcmd >= 50){
// cAOReaderAgain();
// kirimcmd = 0;
// }
char mylog[1024];
sprintf(mylog,"$$$send command$$$Begin Process");
tulisLog(mylog);
portInUse = 1;
PurgeComm(hComm,PURGE_RXCLEAR|PURGE_TXCLEAR);
BOOL Status;
int pjg = strlen(command);
char lpBuffer[pjg+1];
strcpy(lpBuffer,command);
DWORD dNoOFBytestoWrite;
DWORD dNoOfBytesWritten = 0;
dNoOFBytestoWrite = sizeof(lpBuffer);
sprintf(mylog,"send command:%s",command);
tulisLog(mylog);
Status = WriteFile(hComm, // Handle to the Serialport
lpBuffer, // Data to be written to the port
dNoOFBytestoWrite, // No of bytes to write into the port
&dNoOfBytesWritten, // No of bytes written to the port
NULL);
free(lpBuffer);
kirimcmd++;
if (Status == FALSE){
//cAOReaderAgain();
sprintf(mylog,"send command failed, error number:%d",GetLastError());
tulisLog(mylog);
return 99;
}
sprintf(mylog,"$$$send command$$$End Process");
tulisLog(mylog);
return 0;
}
void cAOReaderAgain(){
char mylog[1024];
sprintf(mylog,"%%%Refresh Serial%%%Begin process");
tulisLog(mylog);
br = FALSE;
nunggurespon = 1;
FlushFileBuffers(hComm);
Sleep(200);
sprintf(mylog,"%%%Refresh Serial%%%Close serial");
tulisLog(mylog);
PurgeComm(hComm,PURGE_RXCLEAR|PURGE_TXCLEAR|PURGE_RXABORT|PURGE_TXABORT);
CloseHandle(hComm);
Sleep(200);
sprintf(mylog,"%%%Refresh Serial%%%Open serial");
tulisLog(mylog);
char port[6];
int scport = searchreader();
sprintf(port,"COM%d",scport);
char* result = OpenOnly(port);
if(strcmp(result,"success") == 0){
nunggurespon = 0;
pthread_t tid;
pthread_create(&tid,NULL,threadRespon,NULL);
Sleep(200);
char command[100];
openstatus = 1;
sprintf(mylog,"%%%Refresh Serial%%%Open Success");
tulisLog(mylog);
}
else{
DWORD dwerr;
COMSTAT commstat;
ClearCommError(hComm,&dwerr,&commstat);
sprintf(mylog,"%%%Refresh Serial%%%Open serial failed, error number:",GetLastError());
tulisLog(mylog);
}
sprintf(mylog,"%%%Refresh Serial%%%End process");
tulisLog(mylog);
Sleep(500);
}
char* sendAndRec(char* command)
{
// char mylog[1024];
// sprintf(mylog,"send command:%s",command);
// tulisLog(mylog);
BOOL Status;
int pjg = strlen(command);
char lpBuffer[pjg+1];
strcpy(lpBuffer,command);
DWORD dNoOFBytestoWrite;
DWORD dNoOfBytesWritten = 0;
dNoOFBytestoWrite = sizeof(lpBuffer);
Status = WriteFile(hComm, // Handle to the Serialport
lpBuffer, // Data to be written to the port
dNoOFBytestoWrite, // No of bytes to write into the port
&dNoOfBytesWritten, // No of bytes written to the port
NULL);
free(lpBuffer);
if (Status == FALSE)
return "error";
DWORD dwEventMask, NoBytesRead;
char TempChar;
char SerialBuffer[1024], hasil3[1024];
int i = 0;
Status = WaitCommEvent(hComm, &dwEventMask, NULL);
if (Status == FALSE)
{
sprintf(hasil3,"opendevicefailed#");
}
else
{
int err;
do
{
Status = ReadFile(hComm, &TempChar, sizeof(TempChar), &NoBytesRead, NULL);
err = GetLastError();
SerialBuffer[i] = TempChar;
i++;
}
while (NoBytesRead > 0 && err != ERROR_IO_PENDING);
int j =0;
for (j = 0; j < i-1; j++)
{
hasil3[j] = SerialBuffer[j];
}
}
//free(SerialBuffer);
return hasil3;
}
void tulisLog(char tulis[102400])
{
// char folde[FILENAME_MAX];
// _getcwd(folde,FILENAME_MAX);
// char pathfile[5000];
// sprintf(pathfile,"%s\\LenKTPelKiosLibUsb.log",folde);
//
// time_t t = time(NULL);
// struct tm tm = *localtime(&t);
// FILE *fp;
// fp = fopen(pathfile, "a+");
// if (fp != NULL){
// char mylog[102400];
// sprintf(mylog,"%d/%d/%d %d:%d:%d - %s\n",tm.tm_mday,tm.tm_mon+1,tm.tm_year+1900,tm.tm_hour,tm.tm_min,tm.tm_sec,tulis);
// fputs(mylog, fp);
// }
// fclose(fp);
}
void bacafile()
{
FILE *fp;
char buff[255];
fp = fopen("D:\\test.txt","r");
if (fp == NULL){
printf("Could not open file");
}
else{
printf("Hasil Read file: ");
fscanf(fp, "%s", buff);
printf("%s",buff);
}
fclose(fp);
}
//int split (const char *str, char c, char ***arr)
//{
// int count = 1;
// int token_len = 1;
// int i = 0;
// char *p;
// char *t;
//
// p = str;
// while (*p != '\0')
// {
// if (*p == c)
// count++;
// p++;
// }
//
// *arr = (char**) malloc(sizeof(char*) * count);
// if (*arr == NULL)
// exit(1);
//
// p = str;
// while (*p != '\0')
// {
// if (*p == c)
// {
// (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
// if ((*arr)[i] == NULL)
// exit(1);
//
// token_len = 0;
// i++;
// }
// p++;
// token_len++;
// }
// (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
// if ((*arr)[i] == NULL)
// exit(1);
//
// i = 0;
// p = str;
// t = ((*arr)[i]);
// while (*p != '\0')
// {
// if (*p != c && *p != '\0')
// {
// *t = *p;
// t++;
// }
// else
// {
// *t = '\0';
// i++;
// t = ((*arr)[i]);
// }
// p++;
// }
// //free(arr);
// return count;
//}
__declspec(dllexport) int ektp_getDLL(char error[100], char dllVersion[100])
{
strcpy(error,"ERR_OK");
strcpy(dllVersion,"172.16.17.32");
return 0;
}
__declspec(dllexport) int ektp_getAPI(char error[100], char dllVersion[100])
{
strcpy(error,"ERR_OK");
strcpy(dllVersion,"01.02.00");
return 0;
}
__declspec(dllexport) int ektp_open(char error[100])
{
char mylog[1024];
sprintf(mylog,"###ektp_open###Receive request call");
tulisLog(mylog);
int hasil = 0;
nunggurespon = 1;
CloseHandle(hComm);
openstatus = 0;
Sleep(1000);
int scport = searchreader();
if(scport > 50){
hasil = -1001;
strcpy(error,"No Device Found");
}
else{
char port[6];
sprintf(port,"COM%d",scport);
char* result = sendCommandOP(port,"ektpopen#;");
char *split1 = strtok(result,"#");
if(strcmp(split1,"timeoutwrite") == 0)
{
hasil = -1005;
strcpy(error,"Send Data Timeout");
}
else if(strcmp(split1,"timeoutread") == 0)
{
hasil = -1007;
strcpy(error,"Receive Data Timeout");
}
else if(strcmp(split1,"opendevicefailed") == 0)
{
hasil = -1004;
strcpy(error,"Setup Device Param Failed");
}
else if(strcmp(split1,"$open") == 0)
{
char *split2 = strtok(NULL,"#");
if(strcmp(split2,"0") == 0)
{
hasil = 0;
strcpy(error,"ERR_OK");
openstatus = 1;
nunggurespon = 0;
br = TRUE;
pthread_t tid;
pthread_create(&tid,NULL,threadRespon,NULL);
}
else {
hasil = -1003;
strcpy(error,"Open Device Failed");
}
//free(split2);
}
//free(split1);
//free(result);
}
sprintf(mylog,"###ektp_open###Return request call:%d,%s",hasil,error);
tulisLog(mylog);
return hasil;
}
__declspec(dllexport) int ektp_close(char error[100])
{
char mylog[1024];
sprintf(mylog,"###ektp_close###Receive request call");
tulisLog(mylog);
int hasil = 99;
if(openstatus == 1)
{
br = TRUE;
int result = sendCommandOnly("ektpclose#;");
int timeout = 2;
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(resclose == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resclose == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
}
else{
if(strcmp(isiClose,"0") == 0){
hasil = 0;
strcpy(error,"ERR_OK");
nunggurespon = 1;
CloseHandle(hComm);
openstatus = 0;
}
else{
hasil = -1;
strcpy(error,"ERR_ERROR");
}
resclose = 0;
}
}
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
sprintf(mylog,"###ektp_close###Return request call:%d,%s",hasil,error);
tulisLog(mylog);
return hasil;
}
__declspec(dllexport) int ektp_info(char error[100], char hid[50], char sn[50], char fw[50], char status[30])
{
char mylog[1024];
sprintf(mylog,"###ektp_info###Receive request call");
tulisLog(mylog);
int hasil = 0;
if(openstatus == 1)
{
while(portInUse == 1){
Sleep(500);
}
br = TRUE;
//fflush(stdin);
int result = sendCommandOnly("ektpinfo#;");
int timeout = 2;
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(resinfo == 0 && cnt < tt){
Sleep(100);
cnt++;
}
//br = TRUE;
if(resinfo == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
cAOReaderAgain();
}
else{
char *split1 = strtok(isiInfo,",");
if(strcmp(split1,"error") == 0){
hasil = -1006;
strcpy(error,"Send Data Failed");
}
else{
strcpy(error,"ERR_OK");
strcpy(hid,split1);
strcpy(sn,strtok(NULL,","));
strcpy(fw,strtok(NULL,","));
strcpy(status,"01");
}
//free(split1);
resinfo = 0;
//free(isiInfo);
memset(isiInfo,0,sizeof(isiInfo));
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
cAOReaderAgain();
}
portInUse = 0;
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
sprintf(mylog,"###ektp_info###Return request call:%d,%s",hasil,error);
tulisLog(mylog);
return hasil;
}
__declspec(dllexport) int ektp_putKTP(char error[100], char dm[80], int timeout, char ft[6])
{
char mylog[1024];
sprintf(mylog,"###ektp_putKTP###Receive request call");
tulisLog(mylog);
int hasil = 0;
//cAOReaderAgain();
if(openstatus == 1)
{
while(portInUse == 1){
Sleep(500);
}
lastPutKtpStatus = 18;
br = TRUE;
char command[100];
//fflush(stdin);
sprintf(command,"ektpput#%d#%s#;",timeout,dm);
int result = sendCommandOnly(command);
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = (timeout+1) * 10;
while(resput == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resput == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
lastPutKtpStatus = 3;
lastReaderStatus = 0;
cAOReaderAgain();
}
else{
char *split1 = strtok(isiPut,",");
char *split2 = strtok(NULL,",");
char *split3 = strtok(NULL,",");
if(strcmp(split1,"error") == 0){
hasil = -1;
strcpy(error,split2);
lastPutKtpStatus = 27;
lastReaderStatus = 24;
}
else{
strcpy(error,"ERR_OK");
char jari[10];
sprintf(jari,"%s,%s",split2,split3);
strcpy(ft,jari);
lastPutKtpStatus = 34;
lastReaderStatus = 0;
}
//free(split1);
//free(split2);
//free(split3);
memset(isiPut,0,sizeof(isiPut));
resput = 0;
//cAOReaderAgain();
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
cAOReaderAgain();
lastPutKtpStatus = 24;
lastReaderStatus = 0;
}
portInUse = 0;
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
sprintf(mylog,"###ektp_putKTP###Return request call:%d,%s,%s",hasil,error,ft);
tulisLog(mylog);
return hasil;
}
__declspec(dllexport) int ektp_poll(char error[100], unsigned char *readerStatus, unsigned char *putKTPStatus, unsigned char *verifyFingerStatus, unsigned char *deviceStatus)
{
char mylog[1024];
sprintf(mylog,"###ektp_poll###Receive request call");
tulisLog(mylog);
int hasil = 0;
if(openstatus == 1)
{
if(portInUse == 1)
{
*readerStatus = lastReaderStatus;
*putKTPStatus = lastPutKtpStatus;
*verifyFingerStatus = lastVerifyFingerStatus;
*deviceStatus = lastDeviceStatus;
Sleep(1000);
}
else
{
br = TRUE;
//fflush(stdin);
//free(isiBuffer);
//memset(isiBuffer,0,sizeof(isiBuffer));
//free(isiPoll);
//memset(isiPoll,0,sizeof(isiPoll));
//FlushFileBuffers(hComm);
int result = sendCommandOnly("ektppoll#;");
int timeout = 2;
*readerStatus = '\0';
*putKTPStatus = '\0';
*verifyFingerStatus = '\0';
*deviceStatus = '\0';
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(respoll == 0 && cnt < tt){
Sleep(100);
cnt++;
}
//br = TRUE;
if(respoll == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
cAOReaderAgain();
}
else{
strcpy(error,"ERR_OK");
char *split1 = strtok(isiPoll,",");
if(strcmp(split1,"error") == 0){
hasil = -1012;
strcpy(error,"Device Not Open");
}
else{
int rdst = atoi(split1);
int ptst = atoi(strtok(NULL,","));
int vrst = atoi(strtok(NULL,","));
int dvst = atoi(strtok(NULL,","));;
*readerStatus = rdst;
*putKTPStatus = ptst;
*verifyFingerStatus = vrst;
*deviceStatus = dvst;
lastReaderStatus = rdst;
lastPutKtpStatus = ptst;
lastVerifyFingerStatus = vrst;
lastDeviceStatus = dvst;
}
free(split1);
memset(isiPoll,0,sizeof(isiPoll));
respoll = 0;
//free(isiBuffer);
memset(isiBuffer,0,sizeof(isiBuffer));
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
cAOReaderAgain();
}
portInUse = 0;
}
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
sprintf(mylog,"###ektp_poll###Return request call:%d,%s",hasil,error);
tulisLog(mylog);
return hasil;
}
__declspec(dllexport) int ektp_reset(char error[100], char type)
{
char mylog[1024];
sprintf(mylog,"###ektp_reset###Receive request call");
tulisLog(mylog);
int hasil = 0;
if(openstatus == 1)
{
while(portInUse == 1){
Sleep(500);
}
br = TRUE;
char command[100];
//fflush(stdin);
sprintf(command,"ektpreset#%c#;",type);
int result = sendCommandOnly(command);
int timeout = 2;
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(resreset == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resreset == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
cAOReaderAgain();
}
else{
if(strcmp(isiReset,"0") == 0){
hasil = 0;
strcpy(error,"ERR_OK");
Sleep(1000);
// nunggurespon = 1;
// CloseHandle(hComm);
// openstatus = 0;
}
else{
hasil = -1;
strcpy(error,"ERR_ERROR");
}
resreset = 0;
//free(isiReset);
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
cAOReaderAgain();
}
portInUse = 0;
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
sprintf(mylog,"###ektp_poll###Return request call:%d,%s",hasil,error);
tulisLog(mylog);
return hasil;
}
__declspec(dllexport) int ektp_verifyFinger(char error[100], char dm[80], int timeout, char ft[6], char opid[20], char opnik[20])
{
char mylog[1024];
sprintf(mylog,"###ektp_verifyFinger###Receive request call");
tulisLog(mylog);
int hasil = 0;
//cAOReaderAgain();
if(openstatus == 1)
{
while(portInUse == 1){
Sleep(500);
}
lastVerifyFingerStatus = 19;
br = TRUE;
char command[100];
//fflush(stdin);
sprintf(command,"ektpfinger#%d#%s#%s#%s#%s#;",timeout,ft,opid,opnik,dm);
int result = sendCommandOnly(command);
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = (timeout+1) * 10;
while(resfinger == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resfinger == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
lastVerifyFingerStatus = 3;
lastReaderStatus = 0;
cAOReaderAgain();
}
else{
//int cc = 0;
//char **arrr = NULL;
//cc = split(isiFinger, ',', &arrr);
char *split1 = strtok(isiFinger,",");
if(strcmp(split1,"error") == 0){
hasil = -1;
strcpy(error,strtok(NULL,","));
lastVerifyFingerStatus = 0;
lastReaderStatus = 0;
}
else{
if(strcmp(isiFinger,"Y")==0){
strcpy(error,"Fingerprint match");
lastVerifyFingerStatus = 35;
lastReaderStatus = 0;
}
else{
hasil = -1;
strcpy(error,"Fingerprint not match");
lastVerifyFingerStatus = 30;
}
}
resfinger = 0;
//free(split1);
//free(isiFinger);
//cAOReaderAgain();
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
cAOReaderAgain();
lastVerifyFingerStatus = 24;
lastReaderStatus = 0;
}
portInUse = 0;
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
sprintf(mylog,"###ektp_verifyFinger###Return request call:%d,%s",hasil,error);
tulisLog(mylog);
return hasil;
}
__declspec(dllexport) int ektp_getDataDemography(char error[100], int timeout, char opid[20], char opnik[20], char auid[20], char aunik[20], char** ektpdata)
{
char mylog[102400];
sprintf(mylog,"###ektp_getDataDemography###Receive request call");
tulisLog(mylog);
int hasil = 0;
if(openstatus == 1)
{
while(portInUse == 1){
Sleep(500);
}
br = TRUE;
char command[100];
//fflush(stdin);
sprintf(command,"ektpdemog#%d#%s#%s#;",timeout,opid,opnik);
int result = sendCommandOnly(command);
*ektpdata = '\0';
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(resdemog == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resdemog == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
cAOReaderAgain();
}
else{
//int c = 0;
//char **arr = NULL;
//c = split(isiDemog, ',', &arr);
char *p = isiDemog;
int i=0;
char arr[3][1024];
int x=0;
char temp[1024];
char c = ',';
//char *t;
while (*p != '\0')
{
if (*p != c && *p != '\0')
{
temp[x] = *p;
x++;
}
else
{
temp[x] = '\0';
strcpy(arr[i],temp);
x=0;
i++;
if(i==2){
break;
}
}
p++;
}
// char isiDemog2[18096];
// printf("1");
// strcpy(isiDemog2,isiDemog);
// printf("2");
// char *split1 = strtok(isiDemog2,",");
// printf("3");
// if(strcmp(split1,"error") == 0){
// hasil = -1;
// //strcpy(error,arr[1]);
// strcpy(error,strtok(NULL,","));
// }
// else{
// printf("4");
// strcpy(error,"ERR_OK");
// printf("5");
// //*ektpdata = isiDemog;
// int i = 0;
// while(isiDemog[i] != '\0'){
// ektpdata[i] = isiDemog[i];
// i++;
// }
// ektpdata[i] = '\0';
// //ektpdata = isiDemog;
// //printf("isi Demog: %s",isiDemog);
// printf("6");
// }
// if(strcmp(arr[0],"error") == 0){
// hasil = -1;
// strcpy(error,arr[1]);
// }
// else{
// strcpy(error,"ERR_OK");
// //*ektpdata = isiDemog;
// strcpy(ektpdata,isiDemog);
// }
if(strcmp(arr[0],"error")== 0){
hasil = -1;
strcpy(error,arr[1]);
}
else{
strcpy(error,"ERR_OK");
//strcpy(*ektpdata,isiDemog);
*ektpdata = isiDemog;
}
resdemog = 0;
//free(isiDemog);
//free(isiDemog2);
//free(arr);
//free(p);
//free(t);
//free(temp);
//cAOReaderAgain();
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
cAOReaderAgain();
}
portInUse = 0;
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
sprintf(mylog,"###ektp_getDataDemography###Return request call:%d,%s,%s",hasil,error,isiDemog);
tulisLog(mylog);
return hasil;
}
__declspec(dllexport) int ektp_getMachineLog(char error[100], char date[10], char** map)
{
char mylog[102400];
sprintf(mylog,"###ektp_getMachineLog###Receive request call");
tulisLog(mylog);
int hasil = 0;
char isiLog2[102400];
if(openstatus == 1)
{
while(portInUse == 1){
Sleep(500);
}
br = TRUE;
char command[100];
//fflush(stdin);
sprintf(command,"ektplog#%s#;",date);
int result = sendCommandOnly(command);
int timeout = 30;
*map = '\0';
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(reslog == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(reslog == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
cAOReaderAgain();
}
else{
//int cc = 0;
//char **arrr = NULL;
//cc = split(isiLog, ',', &arrr);
strcpy(isiLog2,isiLog);
//printf("isi log:%s",isiLog);
//printf("isi log2:%s",isiLog2);
char *split1 = strtok(isiLog,",");
char *split2 = strtok(NULL,",");
if(strcmp(split1,"error") == 0){
hasil = -1;
strcpy(error,split2);
}
else if(strcmp(split1,"kosong") == 0){
strcpy(error,"ERR_OK");
}
else{
strcpy(error,"ERR_OK");
*map = isiLog2;
//strcpy(map,isiLog2);
}
reslog = 0;
//free(isiLog2);
//free(split1);
//free(split2);
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
cAOReaderAgain();
}
portInUse = 0;
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
sprintf(mylog,"###ektp_getMachineLog###Return request call:%d,%s",hasil,error);
tulisLog(mylog);
return hasil;
}
__declspec(dllexport) int ektp_dispMessage(char error[100], char dspMessage[50])
{
int hasil = 0;
if(openstatus == 1)
{
while(portInUse == 1){
Sleep(500);
}
br = TRUE;
//fflush(stdin);
int result = sendCommandOnly("ektpdisplay#;");
int timeout = 2;
dspMessage = '\0';
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(resdisplay == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resdisplay == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
}
else{
char *split1 = strtok(isiDisplay,",");
char *split2 = strtok(NULL,",");
if(strcmp(split1,"error") == 0){
hasil = -1;
strcpy(error,split2);
}
else{
strcpy(error,split1);
hasil = 1;
}
resdisplay = 0;
//free(split1);
//free(split2);
//free(isiDisplay);
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
}
portInUse = 0;
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
return hasil;
}
__declspec(dllexport) int ektp_switchMode(char error[100], int mode)
{
int hasil = 0;
if(openstatus == 1)
{
while(portInUse == 1){
Sleep(500);
}
br = TRUE;
//fflush(stdin);
int result = sendCommandOnly("ektpswitch#;");
int timeout = 2;
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(resswitch == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resswitch == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
}
else{
char *split1 = strtok(isiSwitch,",");
char *split2 = strtok(NULL,",");
if(strcmp(split1,"error") == 0){
hasil = -1;
strcpy(error,split2);
}
else{
strcpy(error,split1);
hasil = 1;
}
resswitch = 0;
//free(isiSwitch);
//free(split1);
//free(split2);
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
}
portInUse = 0;
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
return hasil;
}
__declspec(dllexport) int ektp_setPowText(char error[100], char powText[256])
{
int hasil = 0;
if(openstatus == 1)
{
while(portInUse == 1){
Sleep(500);
}
br = TRUE;
//fflush(stdin);
int result = sendCommandOnly("ektpsetpow#;");
int timeout = 2;
powText = '\0';
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(ressetpow == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(ressetpow == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
}
else{
char *split1 = strtok(isiSetpow,",");
char *split2 = strtok(NULL,",");
if(strcmp(split1,"error") == 0){
hasil = -1;
strcpy(error,split2);
}
else{
strcpy(error,split1);
hasil = 1;
}
ressetpow = 0;
//free(isiSetpow);
//free(split1);
//free(split2);
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
}
portInUse = 0;
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
return hasil;
}
__declspec(dllexport) int ektp_resPowText(char error[100])
{
int hasil = 0;
if(openstatus == 1)
{
while(portInUse == 1){
Sleep(500);
}
br = TRUE;
//fflush(stdin);
int result = sendCommandOnly("ektprespow#;");
int timeout = 2;
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(resrespow == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resrespow == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
}
else{
char *split1 = strtok(isiRespow,",");
char *split2 = strtok(NULL,",");
if(strcmp(split1,"error") == 0){
hasil = -1;
strcpy(error,split2);
}
else{
strcpy(error,split1);
hasil = 1;
}
resrespow = 0;
//free(isiRespow);
//free(split1);
//free(split2);
}
}
else{
hasil = -1006;
strcpy(error,"Send Data Failed");
}
portInUse = 0;
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
return hasil;
}
char* readFileBytes(const char *name)
{
FILE *fl = fopen(name, "r");
fseek(fl, 0, SEEK_END);
long len = ftell(fl);
char *ret = malloc(len);
fseek(fl, 0, SEEK_SET);
fread(ret, 1, len, fl);
fclose(fl);
return ret;
}
int updateFinish()
{
br = TRUE;
char command[100];
sprintf(command,"ektpupdatefinish#qwerty#;");
int result = sendCommandOnly(command);
int timeout = 2;
int x = -1;
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(resupdatefinish == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resupdatefinish == 0){
x = -1;
}
else{
if(strcmp(isiUpdateFinish,"error") == 0){
x = -1;
}
else if(strcmp(isiUpdateFinish,"0") == 0){
x = 0;
}
else{
x = atoi(isiUpdateFinish);
}
resupdatefinish = 0;
}
}
return x;
}
void kirimFile(int fileLen, char* buffer)
{
int x = -1;
br = TRUE;
//int arr = (fileLen*2)+100;
char command[20000];
sprintf(command,"ektpupdatefile#%d#%d#%d#%s#;",fileLen,0,fileLen,buffer);
int result = sendCommandOnly(command);
free(buffer);
int timeout = 2;
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(resupdatefile == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resupdatefile == 0){
x = -1;
}
else{
if(strcmp(isiUpdateFile,"error") == 0){
x = -1;
}
else if(strcmp(isiUpdateFile,"0") == 0){
x = updateFinish();
//printf("\nyyy:%d",x);
}
else{
x = -1;
}
resupdatefile = 0;
}
}
//nunggurespon = 1;
//Sleep(1000);
//printf("sebelum retrurn:%d",x);
//return x;
}
int kirimFile2(int fileLen, char* buffer)
{
//int x = -1;
br = TRUE;
char command[4100];
int jumdata = 2000;
int jum = jumdata;
int divlen = (fileLen*2) / jumdata;
int modlen = (fileLen*2) % jumdata;
char dt1[4100];
int lenbaru = jum/2;
int i,awal=0,z;
for(i=0; i<divlen; i++){
awal=i*jumdata;
//free(dt1);
for(z=0; z<jumdata; z++){
dt1[z] = buffer[awal+z];
}
dt1[jum] = '\0';
sprintf(command,"ektpupdatefile#%d#%d#%d#%s#;",lenbaru,awal/2,((awal/2)+lenbaru-1),dt1);
sendCommandOnly(command);
fflush(stdin);
fflush(stdout);
Sleep(15);
}
if(modlen > 0){
char dt2[modlen];
awal = awal + jumdata;
for(z=0; z<modlen; z++){
dt2[z] = buffer[awal+z];
}
dt2[modlen] = '\0';
sprintf(command,"ektpupdatefile#%d#%d#%d#%s#;",modlen/2,(awal/2),fileLen,dt2);
sendCommandOnly(command);
}
Sleep(100);
return updateFinish();
}
__declspec(dllexport) int ektp_update(char error[100], char *updateApp[256])
{
int hasil = -1;
FILE *file;
char *buffer;
unsigned long fileLen;
//Open file
file = fopen(updateApp, "rb");
if (!file)
{
hasil = -1;
strcpy(error,"Unable to open file");
return hasil;
}
//Get file length
fseek(file, 0, SEEK_END);
fileLen=ftell(file);
fseek(file, 0, SEEK_SET);
//printf("Panjang file:%d\n",fileLen);
//Allocate memory
buffer=(char *)malloc(fileLen+1);
if (!buffer)
{
//fprintf(stderr, "Memory error!");
fclose(file);
hasil = -1;
strcpy(error,"Cannot alocate memory to update");
return hasil;
}
//Read file contents into buffer
fread(buffer, fileLen, 1, file);
fclose(file);
//Rubah byte ke hexa string
int i;
char hasils[((fileLen-1) * 2)-1];
char hex_char[16] = "0123456<KEY>";
for (i = 0; i < fileLen; ++i)
{
// High nybble
hasils[i<<1] = hex_char[(buffer[i] >> 4) & 0x0f];
// Low nybble
hasils[(i<<1) + 1] = hex_char[buffer[i] & 0x0f];
}
//printf("setelah convert\nHasil convert:%s",hasils);
free(buffer);
int hasilkirim;
char dt[101];
int z;
for(z=0; z<100; z++){
//printf("%c,",buffer[awal+z]);
dt[z] = hasils[z];
}
dt[100]='\0';
if(openstatus == 1)
{
br = TRUE;
char command[100];
fflush(stdin);
sprintf(command,"ektpupdateinit#%d#%s#;",fileLen,dt);
int result = sendCommandOnly(command);
int timeout = 2;
if(result == 0){
br = FALSE;
Sleep(500);
int cnt = 0;
int tt = timeout * 10;
while(resupdateinit == 0 && cnt < tt){
Sleep(100);
cnt++;
}
if(resupdateinit == 0){
hasil = -1007;
strcpy(error,"Receive Data Timeout");
}
else{
if(strcmp(isiUpdateInit,"error") == 0){
hasil = -1;
strcpy(error,"ERR_ERROR");
}
else if(strcmp(isiUpdateInit,"0") == 0){
hasilkirim = kirimFile2(fileLen,hasils);
if(hasilkirim == 0){
hasil = hasilkirim;
strcpy(error,"ERR_OK");
nunggurespon = 1;
CloseHandle(hComm);
openstatus = 0;
}
else{
hasil = hasilkirim;
strcpy(error,"Cannot send update file");
}
}
else if(strcmp(isiUpdateInit,"2") == 0){
hasil = -1018;
strcpy(error,"Invalid file update version");
}
else if(strcmp(isiUpdateInit,"3") == 0){
hasil = -1017;
strcpy(error,"Invalid file update type");
}
else{
hasil = -1;
strcpy(error,"Cannot update reader");
//printf("isi:%s",isiUpdateInit);
}
resupdateinit = 0;
}
}
}
else{
hasil = -1012;
strcpy(error,"Device Not Open");
}
return hasil;
}
//__declspec(dllexport) int ektp_resetVar(char error[100])
//{
// free(isiBuffer);
// free(isiInfo);
// free(isiClose);
// free(isiPoll);
// free(isiPut);
// free(isiReset);
// free(isiPut);
// free(isiFinger);
// free(isiLog);
// free(isiDemog);
// free(isiSwitch);
// free(isiDisplay);
// free(isiSetpow);
// free(isiRespow);
// free(isiUpdateInit);
// free(isiUpdateFile);
// free(isiUpdateFinish);
//// int tid = 1;
//// int nunggurespon = 0, resput = 0, resinfo = 0, resclose = 0, respoll = 0, resreset = 0, resfinger = 0;
//// int reslog = 0, resdemog = 0, resswitch = 0, resdisplay = 0, ressetpow = 0, resrespow = 0;
//// int resupdateinit = 0, resupdatefile = 0, resupdatefinish = 0;
//// int openstatus = 0;
// CloseHandle(hComm);
// //BOOL br = FALSE;
// return 0;
//}
//__declspec(dllexport) int ektp_pollTanpaRespon()
//{
// if(openstatus == 1)
// {
// br = TRUE;
// int result = sendCommandOnly("ektppoll#;");
// //return 0;
// }
//}
<file_sep>/main.h
struct apiresult
{
int status;
char* error;
char* result;
};
__declspec(dllexport) struct apiresult ektp_getDLL();
__declspec(dllexport) struct apiresult ektp_getAPI();
__declspec(dllexport) struct apiresult ektp_open(char* port);
__declspec(dllexport) struct apiresult ektp_close(char* port);
__declspec(dllexport) struct apiresult ektp_info(char* port);
__declspec(dllexport) struct apiresult ektp_poll(char* port);
__declspec(dllexport) struct apiresult ektp_reset(char* port);
__declspec(dllexport) struct apiresult ektp_getMachineLog(char* port, char* tanggal);
__declspec(dllexport) struct apiresult ektp_dispMessage(char* port);
__declspec(dllexport) struct apiresult ektp_putKTP(char* port, char* text, int timeout);
__declspec(dllexport) struct apiresult ektp_verifyFinger(char* port, char* text, char* jari, char* idop, char* nikop, int timeout);
__declspec(dllexport) struct apiresult ektp_getDataDemography(char* port, char* idop, char* nikop, int timeout);
__declspec(dllexport) struct apiresult ektp_switchMode(char* port, int mode);
__declspec(dllexport) struct apiresult ektp_setPowText(char* port, char* gambar);
__declspec(dllexport) struct apiresult ektp_resPowText(char* port);
| cc408625df1cc7d4c5a427040239e0c94123e1f6 | [
"C"
]
| 2 | C | azmifauzan/LenKTPelKiosLibUsb | 28b9c16ae2d8f0267924fa85780504a6e4163599 | 1aa34cf9a20d743a27b4f170c59c31c6f0383ea5 |
refs/heads/main | <file_sep># Generated by Django 2.1.5 on 2020-12-30 06:44
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_blog_image'),
]
operations = [
migrations.AddField(
model_name='blog',
name='pub_date',
field=models.DateTimeField(blank=True, default=datetime.datetime(2020, 12, 30, 12, 14, 52, 949002)),
),
]
<file_sep>from django.contrib import admin
from . models import Blog
admin.site.register(Blog)<file_sep>Django==2.1.5
Pillow==8.0.1
psycopg2==2.8.6
pytz==2020.5
<file_sep># Generated by Django 2.1.5 on 2020-12-30 06:47
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_auto_20201230_1216'),
]
operations = [
migrations.AddField(
model_name='blog',
name='body',
field=models.TextField(default=''),
),
migrations.AddField(
model_name='blog',
name='image',
field=models.ImageField(default='', upload_to='images/'),
),
migrations.AddField(
model_name='blog',
name='pub_date',
field=models.DateTimeField(blank=True, default=datetime.datetime(2020, 12, 30, 12, 17, 29, 688497)),
),
]
<file_sep># Generated by Django 2.1.5 on 2020-12-30 06:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0005_auto_20201230_1215'),
]
operations = [
migrations.RemoveField(
model_name='blog',
name='body',
),
migrations.RemoveField(
model_name='blog',
name='image',
),
migrations.RemoveField(
model_name='blog',
name='pub_date',
),
migrations.AddField(
model_name='blog',
name='title',
field=models.CharField(default='', max_length=200),
),
]
<file_sep># Generated by Django 2.1.5 on 2020-12-30 06:45
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0004_auto_20201230_1215'),
]
operations = [
migrations.AlterField(
model_name='blog',
name='pub_date',
field=models.DateTimeField(blank=True, default=datetime.datetime(2020, 12, 30, 12, 15, 38, 543764)),
),
]
| 83e03cf5ee1467082a5962ec1391b4070b54b97d | [
"Python",
"Text"
]
| 6 | Python | sanojtomar/portfolio-project | 7d22c04f149f3184e64920537af15734b4845873 | ea4649bb0e11851e280b771c8330de986cffe54f |
refs/heads/master | <file_sep>using System;
namespace ControlerElevadores.Domain.Model
{
public class PesquisaModel
{
public int andar { get; set; }
public string elevador { get; set; }
public string turno { get; set; }
}
}
<file_sep># Teste para Controle de Elevadores
Teste para extração de informações de utilização de 5 elevadores em um prédio com 16 andares
# Linguagem
C# .Net
# Bibliotecas utilizadas
Newtonsoft.Json para desserializar o json com os dados da pesquisa do arquivo input.json
# Formato
Console Application
<file_sep>using ControleElevadores.Appplication.Interfaces;
using ControleElevadores.Appplication.Services;
using System;
namespace ControleElevadores
{
class Program
{
private static void Main(string[] args)
{
IElevadorService _elevadorService = new ElevadorService();
Console.WriteLine("LEGENDA: M: Matutino; V: Vespertino; N: Noturno");
//a.Qual é o andar menos utilizado pelos usuários;
Console.WriteLine($"\na) Qual é o andar menos utilizado pelos usuários: {string.Join(", ", _elevadorService.andarMenosUtilizado())}");
//b.Qual é o elevador mais frequentado e o período que se encontra maior fluxo;
Console.WriteLine(string.Format("\nb) Qual é o elevador mais frequentado e o período que se encontra MAIOR fluxo: O elevador MAIS frequentado é o {0} " +
"com maior fluxo no período {1}.", string.Join(", ", _elevadorService.elevadorMaisFrequentado()), string.Join(", ", _elevadorService.periodoMaiorFluxoElevadorMaisFrequentado())));
//c.Qual é o elevador menos frequentado e o período que se encontra menor fluxo;
Console.WriteLine(string.Format("\nc) Qual é o elevador menos frequentado e o período que se encontra MENOR fluxo: O(s) elevador(es) MENOS frequentado(s) é(são) {0} " +
"com menor fluxo no período {1}.", string.Join(", ", _elevadorService.elevadorMenosFrequentado()), string.Join(", ", _elevadorService.periodoMenorFluxoElevadorMenosFrequentado())));
//d.Qual o período de maior utilização do conjunto de elevadores;
Console.WriteLine($"\nd) Qual o período de maior utilização do conjunto de elevadores: {string.Join(", ", _elevadorService.periodoMaiorUtilizacaoConjuntoElevadores())}");
//e.Qual o percentual de uso de cada elevador com relação a todos os serviços prestados;
Console.WriteLine($"\ne) Qual o percentual de uso de cada elevador com relação a todos os serviços prestados: \n\n" +
$"Elevador A: { string.Join(", ", _elevadorService.percentualDeUsoElevadorA().ToString("#.##")) } %");
Console.WriteLine($"Elevador B: { string.Join(", ", _elevadorService.percentualDeUsoElevadorB().ToString("#.##")) } %");
Console.WriteLine($"Elevador C: { string.Join(", ", _elevadorService.percentualDeUsoElevadorC().ToString("#.##")) } %");
Console.WriteLine($"Elevador D: { string.Join(", ", _elevadorService.percentualDeUsoElevadorD().ToString("#.##")) } %");
Console.WriteLine($"Elevador E: { string.Join(", ", _elevadorService.percentualDeUsoElevadorE().ToString("#.##")) } %\n");
}
}
}
<file_sep>using System.Collections.Generic;
using System.IO;
using System.Linq;
using ControleElevadores.Appplication.Interfaces;
using ControlerElevadores.Domain.Model;
using Newtonsoft.Json;
namespace ControleElevadores.Appplication.Services
{
public class ElevadorService : IElevadorService
{
List<PesquisaModel> lstDadosPesquisa = getDadosPesquisa();
private const float _100Porcento = 100;
private const int _totalElevadores = 5;
public List<int> andarMenosUtilizado()
{
int[] arrAndaresPesquisa = lstDadosPesquisa.Select(x => x.andar).ToArray();
var andaresAgrupados = arrAndaresPesquisa
.GroupBy(x => x)
.Select(a => new
{
Andar = a.Key,
Quantidade = a.Count()
})
.ToArray();
List<int> lstAndaresMenosUtilizados = andaresAgrupados.Where(x => x.Quantidade <= 1).OrderBy(x => x.Andar).Select(x => x.Andar).ToList();
return lstAndaresMenosUtilizados;
}
public List<char> elevadorMaisFrequentado()
{
string[] arrElevadoresPesquisa = lstDadosPesquisa.Select(x => x.elevador).ToArray();
var elevadoresAgrupados = arrElevadoresPesquisa
.GroupBy(x => x)
.Select(e => new
{
Elevador = e.Key,
Quantidade = e.Count()
})
.ToArray();
List<char> lstElevadorMaisFrequentado = new List<char>();
lstElevadorMaisFrequentado.AddRange(elevadoresAgrupados.OrderBy(i => i.Quantidade).LastOrDefault().Elevador);
return lstElevadorMaisFrequentado;
}
public List<char> elevadorMenosFrequentado()
{
string[] arrElevadoresPesquisa = lstDadosPesquisa.Select(x => x.elevador).ToArray();
var elevadoresAgrupados = arrElevadoresPesquisa
.GroupBy(x => x)
.Select(e => new
{
Elevador = e.Key,
Quantidade = e.Count()
})
.ToArray();
List<char> lstElevadorMenosFrequentado = new List<char>();
int min = elevadoresAgrupados.Min(x => x.Quantidade);
foreach (var item in elevadoresAgrupados.Where(x => x.Quantidade == min).ToList())
{
lstElevadorMenosFrequentado.AddRange(item.Elevador);
}
return lstElevadorMenosFrequentado;
}
public float percentualDeUsoElevadorA()
{
int totalElevadoresA = lstDadosPesquisa.Where(x => x.elevador == "A").Select(y => y.elevador).ToList().Count();
return calculaPercentualUsoElevador(_totalElevadores, totalElevadoresA);
}
public float percentualDeUsoElevadorB()
{
int totalElevadoresB = lstDadosPesquisa.Where(x => x.elevador == "B").Select(y => y.elevador).ToList().Count();
return calculaPercentualUsoElevador(_totalElevadores, totalElevadoresB);
}
public float percentualDeUsoElevadorC()
{
int totalElevadoresC = lstDadosPesquisa.Where(x => x.elevador == "C").Select(y => y.elevador).ToList().Count();
return calculaPercentualUsoElevador(_totalElevadores, totalElevadoresC);
}
public float percentualDeUsoElevadorD()
{
int totalElevadoresD = lstDadosPesquisa.Where(x => x.elevador == "D").Select(y => y.elevador).ToList().Count();
return calculaPercentualUsoElevador(_totalElevadores, totalElevadoresD);
}
public float percentualDeUsoElevadorE()
{
int totalElevadoresE = lstDadosPesquisa.Where(x => x.elevador == "E").Select(y => y.elevador).ToList().Count();
return calculaPercentualUsoElevador(_totalElevadores, totalElevadoresE);
}
public List<char> periodoMaiorFluxoElevadorMaisFrequentado()
{
var lstElevadorMaisFrequentado = elevadorMaisFrequentado().Select(c => c.ToString()).ToList();
List<PesquisaModel> elevadoresFiltrados = new List<PesquisaModel>();
foreach (var elevador in lstElevadorMaisFrequentado)
{
elevadoresFiltrados.AddRange(lstDadosPesquisa.Where(x => x.elevador.Equals(elevador)).ToList());
}
string[] arrTurnosPesquisa = elevadoresFiltrados.Select(x => x.turno).ToArray();
var turnosAgrupados = arrTurnosPesquisa
.GroupBy(x => x)
.Select(e => new
{
Turno = e.Key,
Quantidade = e.Count()
})
.ToArray();
List<char> lstPeriodoMaiorFluxo = new List<char>();
lstPeriodoMaiorFluxo.AddRange(turnosAgrupados.FirstOrDefault().Turno);
return lstPeriodoMaiorFluxo;
}
public List<char> periodoMaiorUtilizacaoConjuntoElevadores()
{
var turnosAgrupados = lstDadosPesquisa.Select(x => x.turno).ToArray().GroupBy(x => x)
.Select(e => new
{
Turno = e.Key,
Quantidade = e.Count()
})
.ToArray();
List<char> lstTurnoMaiorUtilizacao = new List<char>();
lstTurnoMaiorUtilizacao.AddRange(turnosAgrupados.OrderBy(i => i.Quantidade).LastOrDefault().Turno);
return lstTurnoMaiorUtilizacao;
}
public List<char> periodoMenorFluxoElevadorMenosFrequentado()
{
List<PesquisaModel> elevadoresFiltrados = new List<PesquisaModel>();
List<string> lstElevadorMenosFrequentado = elevadorMenosFrequentado().Select(c => c.ToString()).ToList();
foreach (var elevador in lstElevadorMenosFrequentado)
elevadoresFiltrados.AddRange(lstDadosPesquisa.Where(x => x.elevador.Equals(elevador)).ToList());
string[] arrTurnosPesquisa = elevadoresFiltrados.Select(x => x.turno).ToArray();
List<char> lstPeriodoMenorFluxo = new List<char>();
foreach (var item in getPeriodoMenorFluxoElevadorMenosFrequentado(arrTurnosPesquisa).GroupBy(x => x)
.Select(e => new
{
Turno = e.Key,
Quantidade = e.Count()
})
.ToArray())
lstPeriodoMenorFluxo.AddRange(item.Turno);
return lstPeriodoMenorFluxo;
}
public List<string> getPeriodoMenorFluxoElevadorMenosFrequentado(string[] lstElevadores)
{
//M: Matutino; V: Vespertino; N: Noturno
string[] turnos = new string[] { "M", "V", "N" };
List<string> lstTurnosMenorFluxo = new List<string>();
IEnumerable<string> turnosMenorFluxo = turnos.Except(lstElevadores);
foreach (string turno in turnosMenorFluxo)
{
lstTurnosMenorFluxo.Add(turno);
}
return lstTurnosMenorFluxo;
}
private static List<PesquisaModel> getDadosPesquisa()
{
string json = File.ReadAllText("../../input.json");
return JsonConvert.DeserializeObject<List<PesquisaModel>>(json);
}
private float calculaPercentualUsoElevador(int totalElevadores, int totalElevadorCategoria)
{
float percentual = totalElevadores / _100Porcento;
float percentualUsoElevador = (percentual * totalElevadorCategoria) * _100Porcento;
return percentualUsoElevador;
}
}
}
| f965d6b88798846c2644dd70ca3eaf3acce474c9 | [
"Markdown",
"C#"
]
| 4 | C# | luanfmeller/TesteControleElevadores | 6926e205c2e3249adff261bc79ecb19595b3221f | 278537454bb9f64ec18fc51600e1963688056a82 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.ServiceBus;
using Newtonsoft.Json;
using V2.FunctionApp;
namespace V1.FunctionApp
{
public static class CosmosDbTrigger
{
[FunctionName("CosmosDbTrigger")]
public async static Task Run(
[CosmosDBTrigger(
databaseName: "%CosmosDbDdatabaseName%",
collectionName: "%CosmosDbCollectionName%",
LeaseDatabaseName = "%CosmosDbDdatabaseName%",
LeaseCollectionName = "%CosmosDbLeaseCollectionName%")] IReadOnlyList<Document> input,
[ServiceBus("%ServiceBusQueue%", EntityType = EntityType.Queue)] IAsyncCollector<Message> collector,
TraceWriter log)
{
if (input == null || !input.Any())
{
log.Info("No document found");
}
log.Info($"Count: {input.Count}");
foreach (var document in input)
{
log.Info(JsonConvert.SerializeObject(document));
log.Info(document.ToString());
Product product = (dynamic)document;
var serialised = JsonConvert.SerializeObject(product);
log.Info(serialised);
var message = new Message(Encoding.UTF8.GetBytes(serialised))
{
ContentType = "application/json",
UserProperties = { { "sample", "key" } }
};
await collector.AddAsync(message).ConfigureAwait(false);
}
}
}
}
<file_sep>//using System;
//using Microsoft.Azure.WebJobs;
//using Microsoft.Azure.WebJobs.Host;
//namespace V2.FunctionApp
//{
// public static class TestTimerTrigger
// {
// [FunctionName("TestTimerTrigger")]
// public static void Run([TimerTrigger("0/10 * * * * *")]TimerInfo myTimer, TraceWriter log)
// {
// log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
// }
// }
//}
<file_sep>using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using V1.Di.FunctionApp.Functions;
using V1.Di.FunctionApp.Functions.FunctionOptions;
using V1.Di.FunctionApp.Modules;
namespace V1.Di.FunctionApp
{
/// <summary>
/// This represents the HTTP trigger entity to list all repositories for a given user or organisation from GitHub.
/// </summary>
public static class AutofacGitHubRepositoriesHttpTrigger
{
public static IFunctionFactory Factory = new AutofacFunctionFactory(new AutofacAppModule());
/// <summary>
/// Invokes the HTTP trigger.
/// </summary>
/// <param name="req"></param>
/// <param name="log"></param>
/// <returns>Returns response.</returns>
[FunctionName("AutofacGitHubRepositoriesHttpTrigger")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/repositories")]HttpRequestMessage req, TraceWriter log)
{
var options = GetOptions(req);
var result = await Factory.Create<IGitHubRepositoriesFunction>(log).InvokeAsync<HttpRequestMessage, object>(req, options).ConfigureAwait(false);
return req.CreateResponse(HttpStatusCode.OK, result);
}
private static GitHubRepositoriesHttpTriggerOptions GetOptions(HttpRequestMessage req)
{
return new GitHubRepositoriesHttpTriggerOptions(req);
}
}
}<file_sep>using System.Net.Http;
using Autofac;
using V1.Di.FunctionApp.Configs;
using V1.Di.FunctionApp.Functions;
namespace V1.Di.FunctionApp.Modules
{
public class AutofacAppModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
var github = new GitHub();
builder.RegisterInstance(github).As<GitHub>().SingleInstance();
var httpClient = new HttpClient();
builder.RegisterInstance(httpClient).As<HttpClient>().SingleInstance();
builder.RegisterType<AutofacGitHubRepositoriesFunction>().As<IGitHubRepositoriesFunction>().InstancePerLifetimeScope();
}
}
}<file_sep>using System.IO;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using V2.Di.FunctionApp.Configs;
using V2.Di.FunctionApp.Extensions;
using V2.Di.FunctionApp.Functions;
namespace V2.Di.FunctionApp.Modules
{
/// <summary>
/// This represents the module entity for dependencies.
/// </summary>
public class CoreAppModule : Module
{
/// <inheritdoc />
public override void Load(IServiceCollection services)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json")
.Build();
var github = config.Get<GitHub>("github");
services.AddSingleton(github);
services.AddSingleton<HttpClient>();
services.AddTransient<IGitHubRepositoriesFunction, CoreGitHubRepositoriesFunction>();
}
}
}<file_sep>using Newtonsoft.Json;
namespace V2.FunctionApp
{
/// <summary>
/// This represents the entity for product.
/// </summary>
public class Product
{
/// <summary>
/// Gets or sets the product Id.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the product category.
/// </summary>
[JsonProperty("category")]
public string Category { get; set; }
/// <summary>
/// Gets or sets the product name.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the product price.
/// </summary>
[JsonProperty("price")]
public decimal Price { get; set; }
}
}<file_sep>
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
namespace V2.FunctionApp
{
/// <summary>
/// This represents the trigger entity for HTTP request.
/// </summary>
public static class TestCosmosDbBinding
{
/// <summary>
/// Invokes the trigger.
/// </summary>
/// <param name="req"><see cref="HttpRequest"/> instance.</param>
/// <param name="collector"><see cref="IAsyncCollector{Product}"/> instance.</param>
/// <param name="log"><see cref="TraceWriter"/> instance.</param>
/// <returns>Returns the <see cref="IActionResult"/> instance.</returns>
[FunctionName("TestCosmosDbBinding")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "v2/products")] HttpRequest req,
[CosmosDB(
databaseName: "%CosmosDbDdatabaseName%",
collectionName: "%CosmosDbCollectionName%")] IAsyncCollector<Product> collector,
TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
var data = JsonConvert.DeserializeObject<Product>(await req.ReadAsStringAsync().ConfigureAwait(false));
await collector.AddAsync(data).ConfigureAwait(false);
return new OkObjectResult(data);
}
}
}
<file_sep># Gets the nightly build of Azure Functions runtime
FROM microsoft/azure-functions-dotnet-core2.0:dev-jessie
ENV AzureWebJobsScriptRoot=/home/site/wwwroot
COPY ./bin/Debug/netstandard2.0 /home/site/wwwroot
<file_sep>using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
namespace V1.FunctionApp
{
/// <summary>
/// This represents the trigger entity for HTTP request.
/// </summary>
public static class TestCosmosDbBinding
{
/// <summary>
/// Invokes the trigger.
/// </summary>
/// <param name="req"><see cref="HttpRequestMessage"/> instance.</param>
/// <param name="collector"><see cref="IAsyncCollector{Product}"/> instance.</param>
/// <param name="log"><see cref="TraceWriter"/> instance.</param>
/// <returns>Returns the <see cref="HttpResponseMessage"/> instance.</returns>
[FunctionName("TestCosmosDbBinding")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "v1/products")] HttpRequestMessage req,
[DocumentDB(
databaseName: "%CosmosDbDdatabaseName%",
collectionName: "%CosmosDbCollectionName%")] IAsyncCollector<Product> collector,
TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
var data = await req.Content.ReadAsAsync<Product>().ConfigureAwait(false);
await collector.AddAsync(data).ConfigureAwait(false);
return req.CreateResponse(HttpStatusCode.OK, data);
}
}
}
| 73bb6a76b97005de8aa237315a7b8e63b41375f4 | [
"C#",
"Dockerfile"
]
| 9 | C# | rekha-balan/GAB2018-3 | e6a59319a54051d4f13b556a72ec9385f2746871 | 5b165ff41956bc99db9516416c8f35fb1728ac24 |
refs/heads/master | <file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "53295ce74684e3afac761cc696594d26",
"url": "/Contact-Manager-Redux/index.html"
},
{
"revision": "510558a2d23679f52632",
"url": "/Contact-Manager-Redux/static/css/main.5dd82d03.chunk.css"
},
{
"revision": "8e2cf3c4c3c28898e242",
"url": "/Contact-Manager-Redux/static/js/2.a86e6f86.chunk.js"
},
{
"revision": "6<PASSWORD>",
"url": "/Contact-Manager-Redux/static/js/2.a86e6f86.chunk.js.LICENSE.txt"
},
{
"revision": "510558a2d23679f52632",
"url": "/Contact-Manager-Redux/static/js/main.e7aedc1e.chunk.js"
},
{
"revision": "2a2d34d1390237b9b6e6",
"url": "/Contact-Manager-Redux/static/js/runtime-main.b5e6c87c.js"
}
]);<file_sep>import React from "react";
import "./about.css";
function About() {
return (
<div className = "about-parent">
<h1>About Contact Manager</h1>
<p>It is a simple app to manage your contacts!</p>
<p className = "about-suffix">Version 1.0.0</p>
</div>
);
}
export default About;
<file_sep>import React from "react";
import "./header.css";
import { Link } from "react-router-dom";
function Header(props) {
return (
<ul className="header-parent">
<div className="header-name">
<h3>{props.branding}</h3>
</div>
<div className="header-items">
<li>
<Link to="/">
<i className="fas fa-home" /> Home
</Link>
</li>
<li>
<Link to="/add">
<i className="fas fa-plus" /> Add
</Link>
</li>
<li>
<Link to="/about">
<i className="fas fa-question" /> About
</Link>
</li>
</div>
</ul>
);
}
export default Header;
<file_sep>import React, { Component } from "react";
import TextInputGroup from "../layout/TextInputGroup";
import "./editcontact.css";
import { updateContact } from "../../actions/actionCreator";
import { getContact } from "../../actions/actionCreator";
import { connect } from "react-redux";
import PropTypes from "prop-types";
class EditContact extends Component {
state = {
name: "",
email: "",
phone: "",
};
UNSAFE_componentWillReceiveProps(nextProps, nextState) {
if (nextState.contact !== this.props.contact) {
const { name, phone, email } = nextProps.contact;
this.setState({
name,
email,
phone,
});
}
}
componentDidMount() {
const { id } = this.props.match.params;
this.props.getContact(id);
}
onChange = (e) => this.setState({ [e.target.name]: e.target.value });
onSubmit = (e) => {
e.preventDefault();
const { name, email, phone } = this.state;
const { id } = this.props.match.params;
const updatedContact = {
id,
name,
email,
phone,
};
this.props.updateContact(updatedContact);
this.setState({
name: "",
email: "",
phone: "",
});
this.props.history.push("/");
};
render() {
const { name, email, phone } = this.state;
return (
<form className="editcontact-parent" onSubmit={this.onSubmit}>
<div className="editcontact-child1">
<h3>Edit Contact </h3>
</div>
<ul className="editcontact-child2">
<TextInputGroup
label="Name"
name="name"
placeholder="Enter name..."
value={name}
onChange={this.onChange}
/>
<TextInputGroup
label="Email"
name="email"
type="email"
placeholder="Enter email..."
value={email}
onChange={this.onChange}
/>
<TextInputGroup
label="Phone"
name="phone"
placeholder="Enter phone..."
value={phone}
onChange={this.onChange}
/>
<li>
<input type="submit" value="Update Contact" />
</li>
</ul>
</form>
);
}
}
EditContact.propTypes = {
updateContact: PropTypes.func.isRequired,
getContact: PropTypes.func.isRequired,
contact: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
contact: state.contact.contact,
});
export default connect(mapStateToProps, { updateContact, getContact })(
EditContact
);
| 18f491533a49f39084861a2e1eb91dde8ad31177 | [
"JavaScript"
]
| 4 | JavaScript | DaniyalMalik/Contact-Manager-Redux | 6197ed1a50368a8f7a0b6d552f86b05ad46cf1d1 | 4c020f65dc3853a89de0c183f31de16e7a0b944d |
refs/heads/master | <repo_name>minlingchao1/spring-boot-rocketmq-starter<file_sep>/src/main/java/com/wkx/annotation/MQConsumer.java
package com.wkx.annotation;
import com.alibaba.rocketmq.common.protocol.heartbeat.MessageModel;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MQConsumer {
String topic();
MessageModel messageModel() default MessageModel.CLUSTERING;
}
| 2442331029ad3cfbd0f7aa79584f5e88403a2163 | [
"Java"
]
| 1 | Java | minlingchao1/spring-boot-rocketmq-starter | 256a22c043a23d039659e67aa7a4a3ace1323f02 | bc584fcf39a04847eeeb4065d173b8a766f2a059 |
refs/heads/master | <file_sep>package main;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
/**
* Created by eddie on 9/19/16.
*/
public class TreeNodeTest {
private final TreeNode test = new TreeNode(4,
new TreeNode(2,
new TreeNode(1, TreeNode.empty, TreeNode.empty),
new TreeNode(3, TreeNode.empty, TreeNode.empty)),
new TreeNode(6,
new TreeNode(5, TreeNode.empty, TreeNode.empty),
new TreeNode(7, TreeNode.empty, TreeNode.empty)));
@Test
public void testkthSmallest() throws Exception {
TreeNode secondSmallest = test.kthSmallest(2);
assertEquals(2, secondSmallest.val);
}
@Test
public void testInOrder() throws Exception {
ArrayList<Integer> inOrder = test.inOrder();
System.out.println(Arrays.toString(inOrder.toArray()));
for (int i = 1; i < 8; i++) {
assertEquals(i, (int) inOrder.get(i - 1));
}
}
} | 649925f695a7ce846bbd85a3ff7e1b736cc9a1d2 | [
"Java"
]
| 1 | Java | eddiedugan/interview | bbfbc0bddddbf65265204ede66af5351b0d75c4e | 5561c51eb9c026fd713b8734016025b851f04a69 |
refs/heads/master | <file_sep>//http://logementetudiant.umontreal.ca/identification/#tab-1433182219425-2-8
//http://logementetudiant.umontreal.ca/inscription/?message=checkmail&uid=7751#tab-1433182219425-2-8
//http://logementetudiant.umontreal.ca/identification/?updated=account_active
//http://logementetudiant.umontreal.ca/ajouter-une-propriete/
//http://logementetudiant.umontreal.ca/tableau-de-bord/#tab-c7f51382-24df-9
/* global chrome */
jQuery(document).ready(function ($) {
chrome.storage.local.get('ads', function (data) {
/*******THIS SITE ONLY FOR Montreal city ******/
if (data.ads.city != 'Montreal') {
nextSite(false);
}
});
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'http://logementetudiant.umontreal.ca/identification/#tab-1433182219425-2-8') {
registration();
} else if (url.indexOf('checkmail&uid') + 1) {
getMail('<EMAIL>', function () {
var pattern = /https?:\/\/.*/i;
var forClick = pattern.exec($('#gh-mail-respons').html())[0].replace(/&/g, '&');
window.location.href = forClick;
}, 300, true);
} else if (url.indexOf('account_active') + 1) {
login();
} else if (url.indexOf('/ajouter-une-propriete') + 1 && $('.alert-danger').length ==0) {
setTimeout(function () {
addAllDetails();
}, 5000)
}else if(url.indexOf('/tableau-de-bord') + 1 || url.indexOf('/ajouter-une-propriete') + 1 && $('.alert-danger').length > 0){
nextSite(true);
}else {
nextSite(false);
}
function registration() {
chrome.storage.local.get('ads', function (data) {
/**/ $("[id=user_login-46]").click();
$("[id=user_login-46]").val(data.ads.login);
// $('[id=user_login-46]')[0].dispatchEvent(new Event('click'));
/**/ $('[id=first_name-46]').click();
$('[id=first_name-46]').val(data.ads.name);
/**/ $('[id=last_name-46]').click();
$('[id=last_name-46]').val(data.ads.l_name);
/**/ $('[id=phone_number-46]').click();
$('[id=phone_number-46]').val(data.ads.phone);
/**/ $('[id=user_email-46]').click();
$('[id=user_email-46]').val(data.ads.email);
/**/ $('[id=user_password-46]').click();
$('[id=user_password-46]').val(data.ads.pass);
/**/ $('[id=confirm_user_password-46]').click();
$('[id=confirm_user_password-46]').val(data.ads.pass);
window.setTimeout(function () {
/*-->*/$('[id=confirm_user_password-46]').parents('form').find('[type=submit]').click();
}, 12000);
});
}
function login() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[id=ui-id-3]').parent().click();
/**/ $('[id=username-25]').click();
/**/ $('[id=username-25]').val(data.ads.email);
/**/ $('[id=user_password-25]').click();
/**/ $('[id=user_password-25]').val(data.ads.pass);
setTimeout(function () {
/*-->*/$('[id=user_password-25]').parents('form').find('[type=submit]').click();
}, 8000);
});
}
function addAllDetails() {
addPhoto();
addAdress();
addDetails();
addApartmentAmenities();
chrome.storage.local.get('ads', function (data) {
/**/ $('[id=title]').click();
$('[id=title]').val(data.ads.title);
/**/ $('[id=description]').click();
$('[id=description]').val(data.ads.content);
/**/ $('[id=property_price]').click();
$('[id=property_price]').val(data.ads.rent);
/**/ $('[id=property_label]').click();
$('[id=property_label]').val('mensuel');
});
}
function addPhoto() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
data.append('name', images[i].name);
data.append('aaiu_upload_file', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', '//logementetudiant.umontreal.ca/wp-admin/admin-ajax.php?action=me_upload&base=0&nonce=57fceec609', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var response = JSON.parse(xhr.responseText);
$('#imagelist').append(`<div class="uploaded_images" data-imageid="${response.attach}"><img src="${response.html}" alt="thumb"><i class="fa deleter fa-trash-o"></i> </div>`)
if (++i < images.length) {
_uploadeimage(i);
}else{
/******FINISH*******/
setTimeout(function () {
/*-->*/$('[id=new_post]').find('[type=submit]').click();
}, 15000);
}
}
};
xhr.send(data);
}
});
}
function addAdress() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[id=property_address]').click();
$('[id=property_address]').val(data.ads.address);
/**/ $('[id=property_city_submit]').click();
$('[id=property_city_submit]').val("Montréal");
// $('[id=property_city_submit]')[0].dispatchEvent(new Event('click'));
selector($('[id=property_area_submit]'), data.ads.zone);
/**/ $('[id=property_zip]').click();
$('[id=property_zip]').val(data.ads.postal_code);
/**/ $('[id=property_county]').click();
$('[id=property_county]').val('Québec');
/**/ $('[id=property_country]').click();
$('[id=property_country]').val('Canada');
setTimeout(function () {
/**/ $('[id=google_capture]').click();
$('[id=google_capture]')[0].dispatchEvent(new Event('click'));
}, 7000);
});
}
function addDetails() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[id=property_size]').click();
$('[id=property_size]').val(data.ads.apt_size);
/**/ $('[id=property_bedrooms]').click();
$('[id=property_bedrooms]').val(data.ads.bedroom);
/**/ $('[id=property_bathrooms]').click();
$('[id=property_bathrooms]').val(data.ads.bathroom);
/**/ $('[id=disponible]').click();
$('[id=disponible]').val(data.ads.available_date);
/**/ $('[id=prop_category_submit]').click();
$('[id=prop_category_submit]').val('2');
/**/ $('[id=property_status]').click();
$('[id=property_status]').val('normal');
});
}
function addApartmentAmenities() {
chrome.storage.local.get('ads', function (data) {
for (var key in data.ads.apartment_amenities) {
switch (data.ads.apartment_amenities[key]) {
case 'Furniture':
$('[id=meuble]').click();
break;
case 'Fridge':
$('[id=refrigerateur]').click();
break;
case 'Washer/Dryer':
$('[id=entree_laveusesecheuse]').click();
break;
case 'Washer':
$('[id=laveuse]').click();
break;
case 'Heating':
$('[id=chauffage_inclus]').click();
break;
case 'Electricity':
$('[id=electricite_incluse]').click();
break;
case 'Hot Water':
$('[id=eau_chaude_incluse]').click();
break;
case 'Internet Ready':
$('[id=internet]').click();
break;
case 'Cable(TV)':
$('[id=television_par_cable]').click();
break;
case 'Laundry In-Building':
$('[id=buanderie_dans_limmeuble]').click();
break;
case 'Private Bathroom':
$('[id=salle_de_bain_privee]').click();
break;
case 'Handicap':
$('[id=acces_handicape]').click();
break;
case 'Indoor Parking':
case 'outdoor Parking':
case 'Assigned Parking':
$('[id=stationnement]').prop('checked', true);
break;
}
}
if (data.ads.pets == '1') {
$('[id=animaux_acceptes]').click();
}
});
}
});
<file_sep>/* global chrome */
const $ = jQuery;
const TwoCaptchaKey = '<KEY>';
// const serverUrl = "//secure162.servconfig.com/~ghostservices/bot/backend/web/ads";
const serverUrl = "//localhost/ads/backend/web/ads";
const extensionID = chrome.runtime.id;
var captchaStatus = false;
var toNextSite;
chrome.storage.local.get('devMode', function (data) {
// console.log(data.devMode);
if ('devMode' in data && !data.devMode) {
toNextSite = window.setTimeout(function () {
nextSite(false);
}, 70000);
//if in loop
chrome.storage.local.get('refreshCount', function (data) {
if ('refreshCount' in data) {
if (data.refreshCount < 10) {
console.log(data.refreshCount);
chrome.storage.local.set({'refreshCount': ++data.refreshCount});
} else {
nextSite(false);
}
}
});
}
});
function nextSite(log = false) {
deleteAllCookies();
chrome.storage.local.set({'refreshCount': 0});
chrome.storage.local.get('sites', (data) => {
sendLog(log, function () {
if (data.sites.length && [0] in data.sites) {
var url = data.sites[0];
data.sites.splice(0, 1);
chrome.storage.local.set({'sites': data.sites});
window.location.href = url;
} else {
window.location.href = `chrome-extension://${extensionID}/options.html`;
}
});
});
}
function deleteAllCookies() {
chrome.runtime.sendMessage({
msg: location.protocol + "//" + location.host
}, function(response) {
console.info('Cookies deleted');
});
}
function sendLog(log, callback) {
// callback();
chrome.storage.local.get('ads', function (data) {
var formData = new FormData();
var domainName = /([^.]+)\.\w+$/.exec(document.domain)[1];
formData.append('site', domainName);
formData.append('data_id', data.ads.id);
if (log) {
formData.append('status', '1');
if (typeof log == 'object') {
for (name in log) {
formData.append(name, log[name]);
}
}
} else {
formData.append('status', '0');
}
var xhr = new XMLHttpRequest();
xhr.open("POST", serverUrl + '/log');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
callback();
}
};
xhr.send(formData);
});
}
function recaptcha(selector, siteKey, siteUrl = '', callback = null) {
selector.ready(function () {
var xhrRC = new XMLHttpRequest();
var pageUrl = siteUrl.length > 0 ? `&pageurl=${siteUrl}` : '';
xhrRC.open('GET', `//2captcha.com/in.php?key=${TwoCaptchaKey}&method=userrecaptcha&googlekey=${siteKey}${pageUrl}`, true);
xhrRC.onreadystatechange = function () {
if (xhrRC.readyState == 4) {
var respons = xhrRC.responseText;
if (respons.split('|')[0] == 'OK') {
window.setTimeout(function () {
_recaptch();
}, 7000);
}
function _recaptch() {
var xhrRCSub = new XMLHttpRequest();
xhrRCSub.open('GET', `//2captcha.com/res.php?key=${TwoCaptchaKey}&action=get&id=${respons.split('|')[1]}`, true);
xhrRCSub.onreadystatechange = function () {
if (xhrRCSub.readyState == 4) {
var _respons = xhrRCSub.responseText.split('|');
if (_respons[0] == 'OK') {
console.log(_respons[1]);
$('#g-recaptcha-response').val(_respons[1]);
captchaStatus = true;
if (callback)
callback();
} else {
console.log('geting RECAPCHA...');
window.setTimeout(function () {
_recaptch();
}, 3000);
}
}
};
xhrRCSub.send();
}
}
};
xhrRC.send();
});
}
function captcha(element, input, params = {}, callback = null) {
element = [0] in element ? element[0] : element;
if (element.nodeName.toLowerCase() == 'img') {
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
var image = getBase64Image(element);
getCaptcha(image);
} else {
html2canvas(element, {
onrendered: function (canvas) {
var image = canvas.toDataURL('image/png', 1.0);
getCaptcha(image);
}
});
}
function getCaptcha(image) {
console.log(image);
var data = new FormData();
data.append('key', TwoCaptchaKey);
data.append('method', 'base64');
data.append('body', image);
if ('phrase' in params) // 0 = 1 word (default value); 1 = CAPTCHA contains 2 words
data.append('phrase', params.phrase);
if ('regsense' in params) // 0 = not case sensitive (default value); 1 = case sensitive
data.append('regsense', params.regsense);
if ('numeric' in params) //0 = not specified (default value); 1 = numeric CAPTCHA; 2 = letters CAPTCHA; 3 = either numeric or letters.
data.append('numeric', params.numeric);
if ('calc' in params) // 0 = not specified (default value); 1 = math CAPTCHA (users are to perform calculation)
data.append('calc', params.calc);
if ('min_len' in params) // 0 = not specified (default value); 1..20 = minimal number of symbols in the CAPTCHA text
data.append('min_len', params.min_len);
if ('max_len' in params) // 0 = not specified (default value); 1..20 = maximal number of symbols in the CAPTCHA text
data.append('max_len', params.max_len);
if ('language' in params) // 0 = not specified (default value); 1 = Cyrillic CAPTCHA; 2 = Latin CAPTCHA
data.append('language', params.language);
if ('soft_id' in params) // 0 = default value; 1 = in.php for Access-Control-Allow-Origin: * response title parameter. (Used for cross-domaine AJAX requests in web applications, and for res.php.)
data.append('soft_id', params.soft_id);
if ('header_acao' in params) // this option is necessary to send text, no longer than 140 characters. The picture at the same time also need to be sent.
data.append('header_acao', params.header_acao);
if ('Pingback' in params) // Pingback is a request you can use for the 2Captcha server that tells it to send your image to a given address, after it's been recognized.
data.append('Pingback', params.Pingback);
if ('id_construction' in params) //Number of captcha-constructor
data.append('id_construction', params.id_construction);
var xhrC = new XMLHttpRequest();
xhrC.open('post', '//2captcha.com/in.php', true);
xhrC.onreadystatechange = function () {
if (xhrC.readyState == 4) {
var respons = xhrC.responseText;
if (respons.split('|')[0] == 'OK') {
window.setTimeout(function () {
_captcha();
}, 3000);
}
}
function _captcha() {
var xhrCSub = new XMLHttpRequest();
xhrCSub.open('GET', `//2captcha.com/res.php?key=${TwoCaptchaKey}&action=get&id=${respons.split('|')[1]}`, true);
xhrCSub.onreadystatechange = function () {
if (xhrCSub.readyState == 4) {
var _respons = xhrCSub.responseText;
if (_respons.split('|')[0] == 'OK') {
console.log(_respons);
input.val(_respons.split('|')[1]);
captchaStatus = true;
if (callback)
callback();
} else {
console.log('geting CAPCHA...');
window.setTimeout(function () {
_captcha();
}, 3000);
}
}
};
xhrCSub.send();
}
};
xhrC.send(data);
}
}
function getMail(from, callback, timeAgo = false, utf8 = false) {
chrome.storage.local.get('ads', function (data) {
var mail = data.ads.email;
var pass = data.ads.pass;
var formData = new FormData();
formData.append('from', from);
if (timeAgo)
formData.append('time_ago', timeAgo);
if (utf8)
formData.append('utf8', '1');
formData.append('email', mail);
formData.append('pass', <PASSWORD>);
var xhr = new XMLHttpRequest();
xhr.open("POST", serverUrl + '/mail');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ($('#gh-mail-respons').length)
$('#gh-mail-respons').remove();
var response = xhr.responseText;
if (/^!{3}/.exec(response)) {
nextSite(false);
} else {
var dataHtml = `<div id="gh-mail-respons">${response}</div>`;
$('body').append(dataHtml);
callback(response);
}
}
};
xhr.send(formData);
});
}
function selector(parent, searchText) {
var value = null;
var options = parent.find('option');
searchText = searchText.toLowerCase().replace(/^st\./i, '').replace(/^st-/i, '');
$.each(options, function () {
var text = $(this).text().trim().toLowerCase();
if (text.match(new RegExp('^' + regCharFixer(searchText) + '$', 'gi'))) {
value = $(this).val();
parent.val(value);
parent[0].dispatchEvent(new Event('change'));
return;
}
});
if (!value) {
$.each(options, function () {
var text = $(this).text().trim().toLowerCase();
if (text.match(new RegExp(regCharFixer(searchText), 'gi'))) {
value = $(this).val();
parent.val(value);
parent[0].dispatchEvent(new Event('change'));
return;
}
});
}
if (value) {
return true;
} else {
return false;
}
}
function regCharFixer(data) {
return data.replace(/[\s\-_\/]+/gi, "[\\s-_\\/]+").replace('a', '[aà]').replace('e', '[eèé]').replace('c', '[cç]').replace('o', '[oô]').replace('u', '[uùµ]').replace('i', '[iïí]');
}
function getImages(callback) {
chrome.storage.local.get('ads', function (data) {
var images = {};
var imagesUrl = data.ads.image_url.split(';');
xhrImage(0);
function xhrImage(i = 0) {
imagesUrl[i] = imagesUrl[i].replace('//bot.ghost-services.com', '//secure162.servconfig.com/~ghostservices/bot');
var name = imagesUrl[i].split('/').pop();
var extension = name.split('.').pop().toLowerCase();
var imageType = extension === 'jpg' ? 'jpeg' : extension;
var xhr = new XMLHttpRequest();
xhr.open("GET", imagesUrl[i], true);
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function () {
xhr.onload = function (oEvent) {
var blob = new Blob([xhr.response], {type: 'image/' + imageType});
blob.lastModifiedDate = new Date();
blob.name = name;
images[i++] = {file: blob, name: name};
images.length = i;
if (i < imagesUrl.length) {
xhrImage(i);
} else {
callback(images);
}
};
};
xhr.send();
}
});
}
function event(element, eventName, elIndex = 0) {
if (element.length && elIndex in element) {
switch (eventName) {
case 'click' :
$(element[elIndex]).click();
case 'change' :
$(element[elIndex]).change();
}
element[elIndex].dispatchEvent(new Event(eventName));
console.info(element);
} else {
console.warn(element);
}
return;
}
function exchange(USD, callback) {
var CAD = (data) => {
var rate = data.rates.CAD / data.rates.USD;
callback(Math.ceil(rate * USD));
};
$.getJSON("//api.fixer.io/latest?symbols=USD,CAD", CAD);
}
chrome.storage.local.get('ads', (data) => {
window.login = data.ads.login;
window.pass = data.ads.pass;
window.address = data.ads.address;
window.apartment_amenities = data.ads.apartment_amenities;
window.apartment_ids = data.ads.apartment_ids;
window.apt_size = data.ads.apt_size;
window.available_date = data.ads.available_date;
window.bathroom = data.ads.bathroom;
window.bedroom = data.ads.bedroom;
window.city = data.ads.city;
window.contact_person = data.ads.contact_person;
window.contact_time = data.ads.contact_time;
window.content = data.ads.content;
window.email = data.ads.email;
window.floor_count = data.ads.floor_count;
window.gender = data.ads.gender;
window.house_type = data.ads.house_type;
window.house_type_id = data.ads.house_type_id;
window.image_url = data.ads.image_url;
window.l_name = data.ads.l_name;
window.lease_length = data.ads.lease_length;
window.pets = data.ads.pets;
window.phone = data.ads.phone;
window.postal_code = data.ads.postal_code;
window.published = data.ads.published;
window.region = data.ads.region;
window.region_iso = data.ads.region_iso;
window.rent = data.ads.rent;
window.street = data.ads.street;
window.title = data.ads.title;
window.zone = data.ads.zone;
window.name = data.ads.name;
window.package_id = data.ads.package_id;
window.parking_count = data.ads.parking_count;
window.parking_price = data.ads.parking_price;
});
<file_sep><footer>
<div class="row">
<div class="footer-bottom">
<div class="container">
<div class="row">
<div class="col-md-12">
<p id="footer-info">
© <?= Yii::t('app', 'AUF Posting 2016. All rights reserved.') ?>
</p>
</div>
</div>
</div>
</div>
</div>
</footer>
<file_sep><?php
namespace backend\modules\coupons\helpers;
use Yii;
class HelperStatus
{
public static function GetStatus($id,$className){
$find = $className::findOne(['id' => $id]);
if($find->status == 'active'){
$find->status = 'passive';
$find->save();
}else{
$find->status = 'active';
$find->save();
}
}
}<file_sep>//http://www.usedmontreal.com/FormInsertUsedAdNew?selected_category_code=apartment-rentals
//http://www.usedmontreal.com/classified-ad/Title-test154_28885392?preview=insert&new=true&posted
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url.indexOf('/FormInsertUsedAdNew') + 1) {
addDetails();
}else if(url.indexOf('/classified-ad') + 1 || url.indexOf('&posted') + 1){
chrome.storage.local.get('usedmontrealPass', function (data) {
nextSite({'pass': data.usedmontrealPass});
});
}else {
nextSite(false);
}
function addDetails() {
addPhoto();
chrome.storage.local.get('ads', function (data) {
// $("[name=selectTransactionID][value='4']").parent()[0].dispatchEvent(new Event('click'));
/**/ $('[name=sale_ind][value=sale]').prop('checked', true);
/**/ $('[name=charity_donate][value=N]').prop('checked', true);
/**/ $('[name=price]').click();
$('[name=price]').val(data.ads.rent);
$('[name=price]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=title]').click();
$('[name=title]').val(data.ads.title);
$('[name=title]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=attr_7]').click();
$('[name=attr_7]').val(data.ads.bedroom);
$('[name=attr_7]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=attr_8]').click();
$('[name=attr_8]').val(data.ads.bathroom);
$('[name=attr_8]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=attr_9]').click();
$('[name=attr_9]').val(data.ads.apt_size);
$('[name=attr_9]')[0].dispatchEvent(new Event('change'));
if(find(data.ads.apartment_amenities, 'Smoking') + 1){
/**/ $('[name=attr_11][value=Y]').prop('checked', true);
}else{
/**/ $('[name=attr_11][value=N]').prop('checked', true);
}
if(data.ads.pets == '1'){
/**/ $('[name=attr_10][value=Y]').prop('checked', true);
}else{
/**/ $('[name=attr_10][value=N]').prop('checked', true);
}
/**/ $('[name=description]').click();
$('[name=description]').val(data.ads.content);
$('[name=description]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=email]').click();
$('[name=email]').val(data.ads.email);
$('[name=email]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=want_email]').prop('checked', true);
/**/ $('[name=phone]').click();
$('[name=phone]').val(data.ads.phone);
$('[name=phone]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=postal_code]').click();
$('[name=postal_code]').val(data.ads.postal_code);
$('[name=postal_code]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=commercial_ind][value=N]').prop('checked', true);
/**/$('[name=location_name]').click();
if(data.ads.city == 'Montreal'){
$('[name=location_name]').val('Montreal');
$('[name=location_name]')[0].dispatchEvent(new Event('click'));
}else{
$('[name=location_name]').val('Outside Montreal');
$('[name=location_name]')[0].dispatchEvent(new Event('click'));
}
var pass = data.ads.pass.substr(0, 20).replace(/[^a-z0-9]/ig, '');
chrome.storage.local.set({'usedmontrealPass': <PASSWORD>});
/**/ $('[name=password]').click();
$('[name=password]').val(<PASSWORD>);
$('[name=password]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=confirmTerms]').prop('checked', true);
});
}
function addPhoto() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
data.append('form_id', $('[name=placeAds]').find('[name=form_id]').val());
data.append('position', '0');
data.append('postfile1', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', '//www.usedmontreal.com/insertAd/xhrPhotoUpload', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var response = JSON.parse(xhr.responseText);
var imgUniqId = /\/(\d+)/.exec(response.photo.url)[1];
$('#photoCount').text(i + 1);
$('#usedPreviewContainer').prepend(`<div class="usedPreview dz-processing dz-image-preview dz-success"
data-position="${i}" id="_photo_${i}" data-id="${imgUniqId}">
<div class="img-border">
<img id="_img_${i}" alt="${images[i].name}" src="${response.photo.url}" style="width: 120px">
</div>
<div class="preview-action" title="${images[i].name}">
<span class="dz-edit icon dz-remove" data-dz-remove="" u-remove="" title="Delete photo"></span>
<span class="icon dz-edit" title="Edit photo" u-edit=""></span>
</div>
</div>`);
if (++i < images.length) {
_uploadeimage(i);
}else{
setTimeout(function () {
/*******FINISH*******/
/*-->*/$('[name=placeAds]').find('[type=submit]').click();
}, 5000)
}
}
};
xhr.send(data);
}
});
}
});
<file_sep>//https://montreal.craigslist.ca/?lang=en&cc=us
//https://accounts.craigslist.org/login?lang=en&cc=us&rt=L&rp=%2Flogin%2Fhome%3Flang%3Den%26cc%3Dus
//https://accounts.craigslist.org/login/home?lang=en&cc=us
//https://post.craigslist.org/manage/6007158621
//https://baghdad.craigslist.org/
//https://post.craigslist.org/k/6oe2GPr05hGAwmMhDAOZ5g/Xm6x6?s=type
//https://post.craigslist.org/k/6oe2GPr05hGAwmMhDAOZ5g/Xm6x6?s=hcat
//https://post.craigslist.org/k/6oe2GPr05hGAwmMhDAOZ5g/Xm6x6?s=edit
//https://post.craigslist.org/k/6oe2GPr05hGAwmMhDAOZ5g/Xm6x6?s=editimage
//https://post.craigslist.org/k/6oe2GPr05hGAwmMhDAOZ5g/Xm6x6?s=preview
//https://post.craigslist.org/k/TItPoEf05hGcOoyYbqFClQ/cG6uq?s=mailoop
//https://post.craigslist.org/k/6oe2GPr05hGAwmMhDAOZ5g/Xm6x6?s=redirect
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'https://montreal.craigslist.ca/?lang=en&cc=us') {
$('#postlks').find('a').get(1).click();
}else if(url.indexOf('/login?lang=') + 1 || url.indexOf('/login?rt=') + 1 && $('[name=emailAddress]').length > 0){
login();
}else if(url.indexOf('/login/home') + 1){
if($('[type=submit][value=delete]').length > 0){
$('[type=submit][value=delete]').click();
$('[type=submit][value=delete]')[0].dispatchEvent(new Event('click'));
}else {
window.location.href = 'https://accounts.craigslist.org/login/home?show_tab=postings';
}
}else if(url.indexOf('/manage') + 1){
window.location.href = 'https://baghdad.craigslist.org/';
}else if(url == 'https://baghdad.craigslist.org'){
/****START ADD NEW LISTING******/
$('#postlks').find('a').get(0).click();
}else if (url.indexOf('&s=type') + 1 || url.indexOf('?s=type') + 1) {
$('[value=ho]').click();
$('[name=go]').click();
} else if (url.indexOf('&s=hcat') + 1 || url.indexOf('?s=hcat') + 1) {
houseType();
}else if (url.indexOf('&s=edit') + 1 || url.indexOf('?s=edit') + 1) {
if ($('[name=go][value$=Images]').length){
uploadeImage();
}else{
creat();
}
}else if (url.indexOf('&s=preview') + 1 || url.indexOf('?s=preview') + 1) {
$('[name=continue][value=y]').next('button').click();
}else if (url.indexOf('&s=mailoop') + 1 || url.indexOf('?s=mailoop') + 1) {
mail();
}else if (url.indexOf('&s=tou') + 1 || url.indexOf('?s=tou') + 1) {
$('[name=continue][value=y]').next('button').click();
}else if(url.indexOf('&s=redirect') + 1 || url.indexOf('?s=redirect') + 1){
setTimeout(function () {
nextAccount();
}, 5000);
}else{
setTimeout(function () {
nextAccount();
}, 5000);
}
function login() {
chrome.storage.local.get('ads', function (data) {
/**/
$('[name=inputEmailHandle]').click();
$('[name=inputEmailHandle]').val(data.ads.email);
$('[name=inputEmailHandle]')[0].dispatchEvent(new Event('change'));
/**/
$('[name=inputPassword]').click();
$('[name=inputPassword]').val(data.ads.pass);
$('[name=inputPassword]')[0].dispatchEvent(new Event('change'));
/**/
$('[name=whichForm][value=login]').parents('form').find('[type=submit]').click();
$($('[name=whichForm][value=login]').parents('form').find('[type=submit]'))[0].dispatchEvent(new Event('click'));
})
}
function houseType() {
chrome.storage.local.get('ads', function (data) {
console.log(data.ads.house_type);
if (data.ads.house_type == 'Commercial') {
$('[name=id][value="40"]').click();
}else {
$('[name=id][value="1"]').click();
}
});
}
function creat() {
chrome.storage.local.get('ads', function (data) {
console.log(data.ads);
/**/ $('[name=FromEMail]').val(data.ads.email);
$('[name=FromEMail]').change();
/**/ $('[name=ConfirmEMail]').val(data.ads.email);
$('[name=ConfirmEMail]').change();
/**/ $('#contact_phone_ok').click();
/**/ $('[name=contact_phone]').val(data.ads.phone);
$('[name=ConfirmEMail]').change();
/**/ $('[name=contact_name]').val(data.ads.name + ' ' + data.ads.l_name);
$('[name=contact_name]').change();
/**/ $('[name=PostingTitle]').val(data.ads.title);
$('[name=PostingTitle]').change();
/**/ $('[name=GeographicArea]').val(data.ads.region + ', ' + data.ads.city + ', ' + data.ads.street + ', ' + data.ads.address);
$('[name=GeographicArea]').change();
/**/ $('[name=postal]').val(data.ads.postal_code);
$('[name=postal]').change();
/**/ $('[name=PostingBody]').val(data.ads.content);
$('[name=PostingBody]').change();
/**/ $('[name=Sqft]').val(data.ads.apt_size);
$('[name=Sqft]').change();
/**/ $('[name=Ask]').val(data.ads.rent);
$('[name=Ask]').change();
//houseType
if ($('.category').text().trim().indexOf('housing for rent') + 1) {
/*--*/var date = data.ads.available_date.split('-');
/**/var month = date[1].substr(0, 1) == '0' ? date[1].substr(1, 1) : date[1];
$('[name=moveinMonth]').val(month);
$('[name=moveinMonth]').change();
/**/$('[name=moveinDay]').val(date[2]);
$('[name=moveinDay]').change();
/**/$('[name=moveinYear]').val(date[0]);
$('[name=moveinYear]').change();
/**/selector($('[name=Bedrooms]'), data.ads.bedroom);
/**/selector($('[name=bathrooms]'), data.ads.bathroom);
/**/selector($('[name=housing_type]'), data.ads.house_type);
/**/ if (find(data.ads.apartment_amenities, 'Laundry In-Building') + 1) {
selector($('[name=laundry]'), 'laundry in bldg');
} else if (find(data.ads.apartment_amenities, 'Laundry') + 1) {
selector($('[name=laundry]'), 'laundry on site');
}
/**/if (data.ads.parking_price > 1) {
selector($('[name=parking]'), 'valet parking');
} else if (find(data.ads.apartment_amenities, 'Indoor Parking') + 1) {
selector($('[name=parking]'), 'attached garage');
} else if (find(data.ads.apartment_amenities, 'outdoor Parking') + 1) {
selector($('[name=parking]'), 'street parking');
}
/*--*/if (data.ads.pets == 1) {
/**/$('[name=pets_cat]').click();
$('[name=pets_cat]').change();
/**/$('[name=pets_dog]').click();
$('[name=pets_dog]').change();
}
/**/if (find(data.ads.apartment_amenities, 'Furniture') + 1) {
$('[name=is_furnished]').click();
$('[name=is_furnished]').change();
}
/**/if (find(data.ads.apartment_amenities, 'Wheelchair accessible') + 1) {
$('[name=wheelchaccess]').click();
$('[name=wheelchaccess]').change();
}
}
/**/ $('[name=xstreet0]').val(data.ads.street);
$('[name=xstreet0]').change();
/**/ $('[name=city]').val(data.ads.city);
$('[name=city]').change();
/**/ $('[name=region]').val(data.ads.region);
$('[name=region]').change();
/**/ $('[name=contact_ok]').click();
$('[name=contact_ok]').change();
/*-->*/ $('[name=go][value=Continue]').click();
});
}
function uploadeImage() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
data.append('name', images[i].name);
data.append('cryptedStepCheck', $('[name=cryptedStepCheck]').val());
data.append('ajax', '1');
data.append('a', 'add');
data.append('file', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', $('form.ajax').attr('action'), true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var respons = JSON.parse(xhr.responseText);
$('.imgwrap').append('<img src="' + respons.URL + '>');
if (++i < images.length) {
_uploadeimage(i);
} else {
window.setTimeout(function () {
/**/$('[name=go][value$=Images]').click();
}, 250);
}
}
};
xhr.send(data);
}
});
}
function mail() {
getMail('<EMAIL>', function (data) {
var get = /"(https?:\/\/w{0,3}\.?post\.craigslist\.org\/u\/[^"]+)"/.exec(data)[1];
window.location = get;
}, 86400);
}
});<file_sep>/* global chrome */
const url = 'https://www.kijiji.ca/t-user-registration.html?siteLocale=en_CA';
const serverUrl = "//secure162.servconfig.com/~ghostservices/bot/backend/web/ads";
// const serverUrl = "http://localhost/ads/backend/web/ads";
jQuery(document).ready(function($) {
$('#start').click(function() {
var devMode = $('#dev_mode').is(':checked') ? true : false;
var xhr = new XMLHttpRequest();
xhr.open("GET", serverUrl + '/get-premium-data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var adsArr = $.parseJSON(xhr.responseText);
chrome.storage.local.set({
'userNumber': '0'
});
chrome.storage.local.set({
'ads': adsArr[0]
});
adsArr.splice(0, 1);
chrome.storage.local.set({
'adsArr': adsArr
});
chrome.storage.local.set({
'devMode': devMode
});
window.open(url, '_blank');
}
};
xhr.send();
});
chrome.storage.local.get('devMode', function(data) {
$('#dev_mode').prop('checked', data.devMode);
});
var premiumUpdateStage = new XMLHttpRequest();
premiumUpdateStage.open("GET", serverUrl + "/get-premium-update-stage", true);
premiumUpdateStage.onreadystatechange = function() {
if (premiumUpdateStage.readyState == 4) {
var data = $.parseJSON(premiumUpdateStage.responseText);
chrome.storage.local.set({
'premiumUpdateStage': data
});
var updateSeconds = data.stage_hour * 3600000;
setInterval(function() {
$('#start').click();
}, updateSeconds);
}
};
premiumUpdateStage.send();
});
<file_sep><?php
$this->title = $thread['title'];
$this->registerMetaTag(['name' => 'keywords', 'content' => $thread['keywords']]);
$this->registerMetaTag(['name' => 'description', 'content' => $thread['description']]);
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Blog'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
$getRequest = Yii::$app->request->get();
?>
<section class="paddingT padding-services">
<?php if (!empty($thread)): ?>
<div class="container">
<div class="row">
<button class="visible-xs visible-sm closeUl">
<i class="fa fa-arrow-circle-right fa-lg" aria-hidden="true"></i>
</button>
<div id="showUl" class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
<ul class="list-group left-listGroup pageUl">
<?php foreach ($blogposts as $value) { ?>
<li class="list-group-item <?php if ($getRequest['slug']) {
if ($getRequest['slug'] == $value['slug']) {
echo 'active';
}
} ?>">
<a class="content_title" href="<?= $value['slug']; ?>"><?= $value['title'] ?></a></li>
<?php } ?>
</ul>
</div>
<div id="contentSection" class="col-lg-8 col-md-8 col-sm-12 col-xs-12" data-show="true">
<h2 class="col-xs-12 text-center text-capitalize">
<?= $thread['title']; ?>
</h2>
<p>
<?= $thread['content']; ?>
</p>
</div>
</div>
</div>
<?php endif; ?>
</section><file_sep><?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\redactor\widgets\Redactor;
/* @var $this yii\web\View */
/* @var $model common\models\ListingSection */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="listing-section-form">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'keywords')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'description')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'short_text')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'content')->widget(Redactor::className(),
[
'clientOptions' =>
[
'imageUpload' => \yii\helpers\Url::to(['/redactor/upload/image']),
'fileUpload' => false,
'plugins' => ['fontcolor', 'imagemanager', 'table', 'undoredo','clips', 'fullscreen'],
]
])
?>
<?= $form->field($model, 'is_active')->dropDownList(['0' => Yii::t('app','Passive'), '1' => Yii::t('app','Active')],['prompt' => Yii::t('app','-- Select Activity --')]) ?>
<div class="col-xs-12 divHeader">
<h4>
<?= Yii::t('app', 'Translations') ?>
</h4>
</div>
<div class="col-xs-12 divContent">
<br>
<?= $form->field($model_translations, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model_translations, 'short_text')->textarea(['rows' => 6]) ?>
<?= $form->field($model_translations, 'content')->widget(Redactor::className(),
[
'clientOptions' =>
[
'imageUpload' => \yii\helpers\Url::to(['/redactor/upload/image']),
'fileUpload' => false,
'plugins' => ['fontcolor', 'imagemanager', 'table', 'undoredo','clips', 'fullscreen'],
]
]) ?>
</div>
<div class="clearfix"></div>
<br>
<div class="imageupload">
<?= $form->field($model, 'files[]')->fileInput(["multiple"=>"multiple",'id'=>"files"]) ?>
<?php if(isset($_GET['id'])) { ?>
<div class="old-files">
<?php
$rows = (new \yii\db\Query())
->select(['id', 'files'])
->from('listing_section')
->where(['id' => $_GET['id']])
->limit(1)
->one();
if(!empty($rows['files'])) {
$explodeFiles = explode(',',$rows['files']);
foreach ($explodeFiles as $fir) {
?>
<span id="up-files<?php echo $_GET['id']; ?>" class="pip"><img class="imageThumb" src="http://<?php echo Yii::$app->getRequest()->serverName; ?>/frontend/web/img/uploads/<?php echo $fir; ?>" title="Image"><br><span class="removefile" onclick="removeUploadedFiles('<?php echo $fir; ?>',<?php echo $_GET['id']; ?>)" >Remove image</span></span>
<?php }
}
?>
</div>
<?php } ?>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app','Create') : Yii::t('app','Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<file_sep><?php
use yii\helpers\Html;
/* @var $this \yii\web\View */
/* @var $content string */
?>
<?php
$query = new \yii\db\Query();
$query->select([
'user.username',
])
->from('user')
->where(['id' => Yii::$app->user->identity->id])
->one();
$command = $query->createCommand();
$data = $command->queryAll();
?>
<header class="main-header">
<?= Html::a('<span class="logo-mini">' . Yii::t('app','AUF') . '</span><span class="logo-lg">' . Yii::t('app','AUFPosting') . '</span>', Yii::$app->homeUrl, ['class' => 'logo']) ?>
<nav class="navbar navbar-static-top" role="navigation">
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="<?php echo yii\helpers\Url::to(['/site/logout/']); ?>" class="btn" data-method="post"><i class="fa fa-remove"></i> Sign out</a>
</li>
</ul>
</div>
</nav>
</header>
<file_sep>jQuery(document).ready(function ($) {
let url = String(window.location.href).replace(/\/$/, '');
switch (url) {
case "http://www.montreallisting.ca/post-free-classified-ad/?classification_id=housing-apartments-condos-for-rent-sale-wanted":
setRegistrationForm();
break;
}
function setRegistrationForm() {
/**
* Title
*/
console.log(title);
$("[name=subject]").val(title);
}
});<file_sep><?php
return [
'adminEmail' => '<EMAIL>',
'supportEmail' => '<EMAIL>',
'user.passwordResetTokenExpire' => 3600,
// 'image' => Yii::getAlias('@backend') . '/web/uploads/',
// 'image' => '.../../../frontend/web/img/upload/',
];
<file_sep><?php
use common\models\Translations;
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model common\models\ListingSection */
$this->title = $model->title;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app','Listing Section'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
$translation = Translations::findOne([
'parent_id' => $model->id,
'parent_tbl' => 'listing'
]);
?>
<div class="listing-section-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a( Yii::t('app','Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a( Yii::t('app','Delete'), ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app','Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<div class="table-responsive">
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'title',
'keywords',
'short_text:ntext',
'content:ntext',
'description',
'slug',
'created_at:datetime',
'updated_at:datetime',
[
'label' => Yii::t('app','Is Active'),
'value' => $model->is_active == 1 ? Yii::t('app','Active') : Yii::t('app','Passive'),
],
[
'attribute' => 'title',
'label' => Yii::t('app', 'Translated Title'),
'value' => !empty($translation) ? $translation->title : NULL
],
[
'attribute' => 'short_text',
'label' => Yii::t('app', 'Translated Short Text'),
'value' => !empty($translation) ? $translation->short_text : NULL
],
[
'attribute' => 'content',
'label' => Yii::t('app', 'Translated Content'),
'value' => !empty($translation) ? $translation->content : NULL
]
],
]) ?>
</div>
</div>
<file_sep>//https://www.logement-a-louer.com/proprietaires
//https://www.logement-a-louer.com/compte/logements
//https://www.logement-a-louer.com/compte/logement-form
//https://www.logement-a-louer.com/compte/logements?saved=1
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'https://www.logement-a-louer.com/proprietaires') {
registration();
} else if (url == 'https://www.logement-a-louer.com/compte/logements') {
window.location.href = 'https://www.logement-a-louer.com/compte/logement-form';
} else if (url == 'https://www.logement-a-louer.com/compte/logement-form') {
location();
} else if(url == 'https://www.logement-a-louer.com/compte/logements?saved=1'){
nextSite(true);
}else {
nextSite(false);
}
function registration() {
chrome.storage.local.get('ads', function (data) {
if (!$('.help-block').text().length > 0) {
/**/ $('[id=inputName]').click();
$('[id=inputName]').val(data.ads.name);
/**/ $('[id=inputPhone]').click();
$('[id=inputPhone]').val(data.ads.phone);
/**/ $('[id=inputEmail]').click();
$('[id=inputEmail]').val(data.ads.email);
/**/ $('[id=inputPassword]').click();
$('[id=inputPassword]').val(data.ads.pass);
/**/ $('[name=confirm]').click();
$('[name=confirm]').val(data.ads.pass);
/*-->*/$('[name=confirm]').parents('form').find('[type=submit]').click();
}
});
}
function location() {
addPhoto();
chrome.storage.local.get('ads', function (data) {
/**/ $('[id=title]').click();
$('[id=title]').val(data.ads.title);
/**/ $('[id=price]').click();
$('[id=price]').val(data.ads.rent);
/*****CHOOSE HOUSE TYPE*******/
selector($('[id=type]'), data.ads.house_type);
/**/ $('[id=size]').click();
$('[id=size]').val(data.ads.bedroom + ' 1/2');
/**/ $('[id=address]').click();
$('[id=address]').val(data.ads.address);
/**/ $('[id=city]').click();
$('[id=city]').val(data.ads.city);
/**/ $('[id=phone]').click();
$('[id=phone]').val(data.ads.phone);
/**/ $('[id=description]').click();
$('[id=description]').val(data.ads.content);
});
}
function addPhoto() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
data.append('name', images[i].name);
data.append('tok', $('[name=tok]').val());
data.append('file', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', '//www.logement-a-louer.com/compte/envoie-photo', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var response = JSON.parse(xhr.responseText);
$('#uploadPictureBtn').parent().append(`<div class="thumbnail-img-container" data-id="${response.hash}">
<a href="javascript:deletePicture('${response.hash}');">
<img src="${response.url}" class="img-responsive">
<span class="hover-bottom bg-red">Supprimer la photo</span></a>
</div>`);
if (++i < images.length) {
_uploadeimage(i);
}else{
/******FINISH*******/
/*-->*/$('form').find('[type=submit]').click();
}
}
};
xhr.send(data);
}
});
}
});
<file_sep>//http://free2list.ca/create-account
//http://free2list.ca/members/listing-add.php
//http://free2list.ca/members/listing-map.php?msg=addsuccess&list=103072
//http://free2list.ca/members/listing-images.php?msg=delsuccess&list=103111
//http://free2list.ca/members/new-listing-upgrade.php?msg=addsuccess&list=103117
//http://free2list.ca/members/index.php?msg=addsuccess&list=103117
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url.indexOf('//free2list.ca/create-account') + 1) {
registration();
}else if(url.indexOf('//free2list.ca/members/listing-add.php') + 1 ){
var cookie = document.cookie.split(';');
for (var key in cookie) {
if (cookie[key].search('clicked') + 1) {
setTimeout(function () {
addListing();
}, 5000);
return;
}
}
$('[name=listtype][value=Rental]').parents('.formRes2').find('button').click();
document.cookie = "clicked=" + true;
}else if(url.indexOf('/listing-map.php?') + 1){
setTimeout(function () {
$($('.success').find('a'))[0].click();
$('.success').find('a')[0].dispatchEvent(new Event('click'));
}, 5000)
}else if(url.indexOf('/listing-images.php?') + 1){
setTimeout(function () {
addPhoto();
}, 5000)
}else if(url.indexOf('/new-listing-upgrade.php') + 1){
$('#up-2').find('a').each(function () {
if($(this).attr('onclick').search('closePopup') +1){
$(this)[0].click();
}
});
}else if(url.indexOf('/index.php')){
nextSite(true);
}else {
nextSite(false);
}
function registration() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[name=name]').click();
$('[name=name]').val(data.ads.name);
$('[name=name]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=email]').click();
$('[name=email]').val(data.ads.email);
$('[name=email]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=pw77]').click();
$('[name=pw77]').val(data.ads.pass);
$('[name=pw77]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=agree]').prop('checked', true);
/******CHOOSE THE CATEGORY Owner******/
selector($('[name=category]'), 'Owner');
/**/$('#create-form').find('button').click();
});
}
function addListing() {
chrome.storage.local.get('ads', function (data) {
var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth() + 1;
var currentDay = date.getDate();
if (currentDay < 10){
currentDay = '0' + currentDay;
}
var expirationMonth = '';
if(currentMonth == '12'){
expirationMonth = '01';
}else {
expirationMonth = parseInt(currentMonth) + 1 ;
}
if (expirationMonth < 10){
expirationMonth = '0' + expirationMonth;
}
var currentDate = expirationMonth + '/' + currentDay + '/' + currentYear;
/**/ $('[name=expirydate]').click();
$('[name=expirydate]').val(currentDate);
$('[name=expirydate]')[0].dispatchEvent(new Event('change'));
/********CHOOSE country and province*******/
selector($('[name=country]'), 'Canada');
selector($('[name=cdn_province]'), data.ads.region);
/**/ $('[name=city]').click();
$('[name=city]').val(data.ads.city);
$('[name=city]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=streetaddress]').click();
$('[name=streetaddress]').val(data.ads.street);
$('[name=streetaddress]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=streetaddress2]').click();
$('[name=streetaddress2]').val(data.ads.address);
$('[name=streetaddress2]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=postal]').click();
$('[name=postal]').val(data.ads.postal_code);
$('[name=postal]')[0].dispatchEvent(new Event('change'));
switch (data.ads.house_type){
case 'Apartment':
selector($('[name=typeresi]'), data.ads.house_type);
break;
case 'House':
selector($('[name=typeresi]'), 'Townhouse');
break;
case 'Studio':
selector($('[name=typeresi]'), 'Starter Home');
break;
case 'Commercial':
selector($('[name=typeresi]'), 'Retail');
break;
}
/**/ $('[name=price]').click();
$('[name=price]').val(data.ads.rent);
$('[name=price]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=price]').click();
$('[name=price]').val(data.ads.rent);
$('[name=price]')[0].dispatchEvent(new Event('change'));
var aptSize = Math.ceil(data.ads.apt_size * 10.7639);
/**/ $('[name=size]').click();
$('[name=size]').val(aptSize);
$('[name=size]')[0].dispatchEvent(new Event('change'));
if(data.ads.bathroom < 3){
selector($('[name=criteria1]'), data.ads.bathroom);
}else{
selector($('[name=criteria1]'), '3');
}
$('[name=criteria1]')[0].dispatchEvent(new Event('change'));
for(let key in data.ads.apartment_amenities){
switch (data.ads.apartment_amenities[key]){
case 'Garage':
case 'Secured Garage':
selector($('[name=criteria3]'), 'Indoor');
break;
}
}
if(data.ads.bedroom < 5){
selector($('[name=criteria4]'), data.ads.bedroom);
}else{
selector($('[name=criteria4]'), '5');
}
/**/ $('[name=details]').click();
$('[name=details]').val(data.ads.content);
$('[name=size]')[0].dispatchEvent(new Event('change'));
setTimeout(function () {
$('[name=update]').find('#submitButton').click();
$('[name=update]').find('#submitButton')[0].dispatchEvent(new Event('click'));
}, 5000);
})
}
function addPhoto() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
var imgUploadId = /list=(\d+)/.exec(url)[1];
data.append('file', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', '//free2list.ca/members/scripts/image-upload.php?list='+imgUploadId, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (++i < images.length) {
_uploadeimage(i);
}else{
setTimeout(function () {
/*******FINISH*******/
/*-->*/$($('.success').find('a'))[0].click();
}, 3000)
}
}
};
xhr.send(data);
}
});
}
});
<file_sep><?php
$this->title = $thread['title'];
$this->registerMetaTag(['name' => 'keywords', 'content' => $thread['keywords']]);
$this->registerMetaTag(['name' => 'description', 'content' => $thread['description']]);
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Listing Sections'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
$getRequest = Yii::$app->request->get();
?>
<section class="paddingT padding-services">
<?php if (!empty($thread)): ?>
<div class="container">
<div class="row">
<button class="visible-xs visible-sm closeUl">
<i class="fa fa-arrow-circle-right fa-lg" aria-hidden="true"></i>
</button>
<div id="showUl" class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
<ul class="list-group left-listGroup pageUl">
<?php foreach ($blogposts as $value) { ?>
<li class="list-group-item <?php if ($getRequest['slug']) {
if ($getRequest['slug'] == $value['slug']) {
echo 'active';
}
} ?>">
<a class="content_title" href="<?= $value['slug']; ?>"><?= $value['title'] ?></a></li>
<?php } ?>
</ul>
</div>
<div id="contentSection" class="col-lg-8 col-md-8 col-sm-12 col-xs-12" data-show="true">
<h2 class="col-xs-12 text-center text-capitalize">
<?= $thread['title']; ?>
</h2>
<p>
<div class="front-listings innr-img">
<?= $thread['content']; ?>
</div>
</p>
<div class="front-listings">
<?php if(!empty($thread['files'])) {
$explodeFiles = explode(',',$thread['files']);
foreach ($explodeFiles as $fir) {
?>
<span id="upfiles" class="pip">
<a class="single_image" href="http://<?php echo Yii::$app->getRequest()->serverName; ?>/frontend/web/img/uploads/<?php echo $fir; ?>">
<img class="imageThumb" src="http://<?php echo Yii::$app->getRequest()->serverName; ?>/frontend/web/img/uploads/<?php echo $fir; ?>" title="Image">
</a>
</span>
<?php }
}
?>
</div>
</div>
</div>
</div>
<?php endif; ?>
</section><file_sep><?php
use backend\models\HouseTypeControl;
use backend\models\ApartmentAmenitiesControl;
if (isset($premiumSubmitData)) {
$submit_data = $premiumSubmitData;
foreach ($premiumSubmitData as $key=>$val){
$houseType[] = HouseTypeControl::getHouse($val['house_type_id']);
if ($houseType) {
$submit_data[$key]['house_type'] = $houseType[$key]['house'];
}else{
$submit_data[$key]['house_type'] = null;
}
$ApartmentAmenities[] = ApartmentAmenitiesControl::getApartmentAmenities($submit_data[$key]['apartment_ids']);
if ($ApartmentAmenities) {
foreach ($ApartmentAmenities[$key] as $val){
$submit_data[$key]['apartment_amenities'][$val['id']] = $val['apartment'];
}
}else{
$submit_data[$key]['apartment_amenities'] = null;
}
}
die(json_encode($submit_data));
}
<file_sep><?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model backend\modules\coupons\models\Coupons */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="coupons-form">
<?php $form = ActiveForm::begin([
'options' => [
'enctype' => 'multipart/form-data',
]
]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?php
$initialPreview = [];
$initialPreviewConfig = [];
if (!$model->isNewRecord) {
if ($model->image_url != NULL) {
$imageName = explode('/', $model->image_url);
$imageName = $imageName[count($imageName) - 1];
$initialPreview[] = $model->image_url;
$initialPreviewConfig[] = [
'caption' => $imageName,
'size' => file_exists(Yii::getAlias('@frontend') . '/web/coupons/' . $imageName) ? filesize(Yii::getAlias('@frontend') . '/web/coupons/' . $imageName) : NULL,
'width' => "120px",
];
}
}
?>
<?= $form->field($model, 'image')->widget(\kartik\file\FileInput::classname(), [
'attribute' => 'image',
'options' => [
'accept' => 'image/*',
'multiple' => false,
],
'pluginOptions' => [
'previewFileType' => 'image',
'allowedFileExtensions' => ['jpg', 'png'],
'maxFileSize' => 2048,
'showPreview' => true,
'showUpload' => false,
'showCaption' => true,
'initialPreview' => $initialPreview,
'initialPreviewConfig' => $initialPreviewConfig,
'initialPreviewAsData' => true,
'overwriteInitial' => true,
'initialPreviewShowDelete' => false,
'resizeImages' => true,
],
]) ?>
<div class="form-group field-coupons-generate_coupon_code">
<div class="row">
<div class="col-md-3 col-sm-5">
<label class="control-label">
<?= Yii::t('app', 'Generate Coupon Code') ?>
</label>
</div>
<div class="col-md-9 col-sm-7">
<div id="coupons-generate_coupon_code">
<label class="control-label">
<input type="radio"
name="Coupons[generate_coupon_code]"
value="1"
<?= $model->isNewRecord ? 'checked' : '' ?>
onchange='$("#coupons-coupon_code").hide("slow");'>Yes
</label>
<label class="control-label">
<input type="radio"
name="Coupons[generate_coupon_code]"
value="0"
onchange='$("#coupons-coupon_code").show("slow");'
>No
</label>
</div>
</div>
<div class="help-block"></div>
</div>
</div>
<?= $form->field($model, 'coupon_code')->textInput(['maxlength' => true, 'style' => 'display: none;'])->label(false) ?>
<?= $form->field($model, 'discount_type')->dropDownList(['percent' => 'Percent', 'price' => 'Price'], ['prompt' => 'Select Discount Type']) ?>
<?= $form->field($model, 'discount_count')->textInput() ?>
<?= $form->field($model, 'available_coupons_count')->textInput() ?>
<?= \dosamigos\datetimepicker\DateTimePicker::widget([
'model' => $model,
'attribute' => 'expire_at',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd hh:ii:ss',
'todayBtn' => true
]
]);?>
<?= $form->field($model, 'status')->dropDownList(['active' => 'Active', 'passive' => 'Passive',], ['prompt' => 'Select Availability']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<file_sep><?php
$vendorDir = dirname(__DIR__);
return array (
'yiisoft/yii2-swiftmailer' =>
array (
'name' => 'yiisoft/yii2-swiftmailer',
'version' => '2.0.6.0',
'alias' =>
array (
'@yii/swiftmailer' => $vendorDir . '/yiisoft/yii2-swiftmailer',
),
),
'yiisoft/yii2-codeception' =>
array (
'name' => 'yiisoft/yii2-codeception',
'version' => '2.0.5.0',
'alias' =>
array (
'@yii/codeception' => $vendorDir . '/yiisoft/yii2-codeception',
),
),
'yiisoft/yii2-bootstrap' =>
array (
'name' => 'yiisoft/yii2-bootstrap',
'version' => '2.0.6.0',
'alias' =>
array (
'@yii/bootstrap' => $vendorDir . '/yiisoft/yii2-bootstrap',
),
),
'yiisoft/yii2-debug' =>
array (
'name' => 'yiisoft/yii2-debug',
'version' => '2.0.7.0',
'alias' =>
array (
'@yii/debug' => $vendorDir . '/yiisoft/yii2-debug',
),
),
'yiisoft/yii2-gii' =>
array (
'name' => 'yiisoft/yii2-gii',
'version' => '2.0.5.0',
'alias' =>
array (
'@yii/gii' => $vendorDir . '/yiisoft/yii2-gii',
),
),
'yiisoft/yii2-faker' =>
array (
'name' => 'yiisoft/yii2-faker',
'version' => '2.0.3.0',
'alias' =>
array (
'@yii/faker' => $vendorDir . '/yiisoft/yii2-faker',
),
),
'vova07/yii2-imperavi-widget' =>
array (
'name' => 'vova07/yii2-imperavi-widget',
'version' => '1.2.10.0',
'alias' =>
array (
'@vova07/imperavi' => $vendorDir . '/vova07/yii2-imperavi-widget/src',
),
),
'yiidoc/yii2-redactor' =>
array (
'name' => 'yiidoc/yii2-redactor',
'version' => '2.0.1.0',
'alias' =>
array (
'@yii/redactor' => '/',
),
),
'kartik-v/yii2-krajee-base' =>
array (
'name' => 'kartik-v/yii2-krajee-base',
'version' => '1.8.7.0',
'alias' =>
array (
'@kartik/base' => $vendorDir . '/kartik-v/yii2-krajee-base',
),
),
'kartik-v/yii2-widget-datepicker' =>
array (
'name' => 'kartik-v/yii2-widget-datepicker',
'version' => '9999999-dev',
'alias' =>
array (
'@kartik/date' => $vendorDir . '/kartik-v/yii2-widget-datepicker',
),
),
'yurkinx/yii2-image' =>
array (
'name' => 'yurkinx/yii2-image',
'version' => '9999999-dev',
'alias' =>
array (
'@yii/image' => $vendorDir . '/yurkinx/yii2-image/yii/image',
),
),
'kartik-v/yii2-widget-fileinput' =>
array (
'name' => 'kartik-v/yii2-widget-fileinput',
'version' => '9999999-dev',
'alias' =>
array (
'@kartik/file' => $vendorDir . '/kartik-v/yii2-widget-fileinput',
),
),
'yiisoft/yii2-jui' =>
array (
'name' => 'yiisoft/yii2-jui',
'version' => '2.0.6.0',
'alias' =>
array (
'@yii/jui' => $vendorDir . '/yiisoft/yii2-jui',
),
),
'kongoon/yii2-paypal' =>
array (
'name' => 'kongoon/yii2-paypal',
'version' => '0.1.3.0',
'alias' =>
array (
'@kongoon/yii2/paypal' => $vendorDir . '/kongoon/yii2-paypal',
),
),
'rmrevin/yii2-fontawesome' =>
array (
'name' => 'rmrevin/yii2-fontawesome',
'version' => '2.17.1.0',
'alias' =>
array (
'@rmrevin/yii/fontawesome' => $vendorDir . '/rmrevin/yii2-fontawesome',
),
),
'cebe/yii2-gravatar' =>
array (
'name' => 'cebe/yii2-gravatar',
'version' => '1.1.0.0',
'alias' =>
array (
'@cebe/gravatar' => $vendorDir . '/cebe/yii2-gravatar/cebe/gravatar',
),
),
'dmstr/yii2-adminlte-asset' =>
array (
'name' => 'dmstr/yii2-adminlte-asset',
'version' => '2.3.4.0',
'alias' =>
array (
'@dmstr' => $vendorDir . '/dmstr/yii2-adminlte-asset',
),
),
'2amigos/yii2-date-time-picker-widget' =>
array (
'name' => '2amigos/yii2-date-time-picker-widget',
'version' => '1.0.2.0',
'alias' =>
array (
'@dosamigos/datetimepicker' => $vendorDir . '/2amigos/yii2-date-time-picker-widget/src',
),
),
'zelenin/yii2-slug-behavior' =>
array (
'name' => 'zelenin/yii2-slug-behavior',
'version' => '1.5.1.0',
'alias' =>
array (
'@Zelenin/yii/behaviors' => $vendorDir . '/zelenin/yii2-slug-behavior',
),
),
);
<file_sep><?php
namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
/**
* This is the model class for table "ListingSection".
*
* @property integer $id
* @property string $title
* @property string $keywords
* @property string $short_text
* @property string $content
* @property string $description
* @property string $slug
* @property string $created_at
* @property string $updated_at
* @property integer $is_active
*/
class ListingSection extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'listing_section';
}
/* Struggle behaviour */
public function behaviors()
{
return [
'slug' => [
'class' => 'Zelenin\yii\behaviors\Slug',
'slugAttribute' => 'slug',
'attribute' => 'title',
// optional params
'ensureUnique' => true,
'replacement' => '-',
'lowercase' => true,
'immutable' => false,
// If intl extension is enabled, see http://userguide.icu-project.org/transforms/general.
'transliterateOptions' => 'Russian-Latin/BGN; Any-Latin; Latin-ASCII; NFD; [:Nonspacing Mark:] Remove; NFC;'
],
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => new Expression('NOW()'),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'keywords', 'short_text', 'content', 'description', 'slug'], 'required'],
[['short_text', 'content'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['is_active'], 'integer'],
[['title', 'keywords', 'description', 'slug'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app','ID'),
'title' => Yii::t('app','Title'),
'keywords' => Yii::t('app','Keywords'),
'short_text' => Yii::t('app','Short Text'),
'content' => Yii::t('app','Content'),
'description' => Yii::t('app','Description'),
'slug' => Yii::t('app','Slug'),
'created_at' => Yii::t('app','Created At'),
'updated_at' => Yii::t('app','Updated At'),
'is_active' => Yii::t('app','Is Active'),
];
}
}
<file_sep><?php
use yii\helpers\Url;
$this->title = Yii::t('app', 'Success');
$this->registerMetaTag(['name' => 'keywords', 'content' => 'Success, page']);
$this->registerMetaTag(['name' => 'description', 'content' => 'Success page']);
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="container">
<div class="row">
<div class="col-xs-12">
<?php if (isset($success)): ?>
<?php if (($success == true) && isset($model)): ?>
<div class="marginTB">
<h2 class="text-center success_s">
<?= Yii::t('app', 'Thank you.<br>Payment was successfully finished.<br>We will contact you if problems arise.') ?>
</h2>
<table class="table table-hover table-stripped table-bordered">
<tr>
<th>Name</th>
<td><?= $model->name ?></td>
</tr>
<tr>
<th>Last Name</th>
<td><?= $model->l_name ?></td>
</tr>
<tr>
<th>Phone</th>
<td><?= $model->phone ?></td>
</tr>
<tr>
<th>Gender</th>
<td><?= $model->gender ?></td>
</tr>
<tr>
<th>City</th>
<td><?= $model->city ?></td>
</tr>
<tr>
<th>Region</th>
<td><?= $model->region ?></td>
</tr>
<tr>
<th>Street</th>
<td><?= $model->street ?></td>
</tr>
<tr>
<th>Address</th>
<td><?= $model->address ?></td>
</tr>
<tr>
<th>Postal Code</th>
<td><?= $model->postal_code ?></td>
</tr>
<tr>
<th>Rent (price of rent)</th>
<td>$<?= $model->rent ?></td>
</tr>
<tr>
<th>Bedroom</th>
<td><?= $model->bedroom ?></td>
</tr>
<tr>
<th>Bathroom</th>
<td><?= $model->bathroom ?></td>
</tr>
<tr>
<th>Title</th>
<td><?= $model->title ?></td>
</tr>
<tr>
<th>Content</th>
<td><?= $model->content ?></td>
</tr>
</table>
</div>
<?php elseif ($success == false): ?>
<div class="marginTB">
<h2 class="text-center success_e">
<?= Yii::t('app', 'Ooops.Something went wrong.') ?>
</h2>
<p class="text-center success_e">
<?= Yii::t('app', 'Please check your data and try again.') ?>
</p>
<p class="text-center">
<a class="btn btn-info" href="<?= Yii::$app->homeUrl ?>main/sign-up">
Go Back
</a>
</p>
</div>
<?php else: ?>
<?php return Yii::$app->response->redirect(Url::to(['/main/index'])); ?>
<?php endif; ?>
<?php else: ?>
<?php if (isset($success_contact) == 'success_send'): ?>
<div class="home_top_section">
<div class="success">
<div class="success-content">
<i style="color: #2ea3f2;" class="fa fa-flag fa-2x" aria-hidden="true"></i>
<h2>THANK YOU</h2>
</div>
</div>
<p>
Thank you for contacting AufPosting.com
</p>
<p>
We will check your contact information as soon as possible and send you an answer over the
next 48h.
</p>
<p>Sincerely,</p>
<p>AufPosting Team.</p>
</div>
<?php elseif (isset($success_contact) == 'error_send'): ?>
<div class="marginTB">
<h2 class="text-center success_e">
<?= Yii::t('app', 'Ooops.Something went wrong.') ?>
</h2>
<p class="text-center success_e">
<?= Yii::t('app', 'Please check your data and try again.') ?>
</p>
<p class="text-center">
<a class="btn btn-info" href="<?= Yii::$app->homeUrl ?>main/index">
Go Back
</a>
</p>
</div>
<?php else: ?>
<?php return Yii::$app->response->redirect(Url::to(['/main/index'])); ?>
<?php endif; ?>
<?php endif; ?>
</div>
</div>
</div><file_sep><?php
use backend\models\HouseTypeControl;
use backend\models\ApartmentAmenitiesControl;
$getRequest = Yii::$app->request->get();
if (isset($getRequest['sites'])) {
$submit_data = [];
if ($sites){
foreach ($sites as $val){
$submit_data[] = $val['url'];
}
}
die(json_encode($submit_data));
} else {
if ($getSubmitData) {
$submit_data = $getSubmitData;
$houseType = HouseTypeControl::getHouse($submit_data['house_type_id']);
if ($houseType) {
$submit_data['house_type'] = $houseType['house'];
}else{
$submit_data['house_type'] = null;
}
$ApartmentAmenities = ApartmentAmenitiesControl::getApartmentAmenities($submit_data['apartment_ids']);
if ($ApartmentAmenities) {
foreach ($ApartmentAmenities as $val){
$submit_data['apartment_amenities'][$val['id']] = $val['apartment'];
}
}else{
$submit_data['apartment_amenities'] = null;
}
die(json_encode($submit_data));
}
die("Empty Data");
}<file_sep><?php
namespace common\models;
use Yii;
use yii\db\ActiveRecord;
/**
* This is the model class for table "payments".
*
* @property integer $id
* @property integer $sd_id
* @property string $payer_id
* @property string $token
* @property string $transaction_id
* @property string $created_at
* @property string $updated_at
*
* @property SubmitData $sd
*/
class Payments extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'payments';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['sd_id'], 'integer'],
[['payer_id', 'token', 'transaction_id', 'created_at', 'updated_at'], 'string', 'max' => 500],
[['sd_id'], 'exist', 'skipOnError' => true, 'targetClass' => SubmitData::className(), 'targetAttribute' => ['sd_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'payer_id' => Yii::t('app', 'Payer ID'),
'token' => Yii::t('app', 'Token'),
'transaction_id' => Yii::t('app', 'Transaction ID'),
'created_at' => Yii::t('app', 'Created At'),
'updated_at' => Yii::t('app', 'Updated At'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSd()
{
return $this->hasOne(SubmitData::className(), ['id' => 'sd_id']);
}
}
<file_sep><?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\ListingSection */
$this->title = Yii::t('app','Update Listing Section: ') . $model->title;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app','Listing Sections'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->title, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = Yii::t('app','Update');
?>
<div class="listing-section-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'model_translations' => $model_translations,
]) ?>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function removeUploadedFiles(name, id) {
var confirms = confirm("Are you sure want to delete?");
if(confirms) {
$.ajax({
type: "GET",
url: "http://<?php echo Yii::$app->getRequest()->serverName; ?>/backend/web/listing-section/delete-file?name="+name+"&id="+id,
data: false,
success: function (test) {
$("#up-files"+id).remove();
},
error: function (exception) {
alert(exception);
}
})
} else {
return false;
}
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var validExtensions = ['jpg','png','jpeg']; //array of valid extensions
var fileName = files[i].name;
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
if ($.inArray(fileNameExt, validExtensions) == -1) {
alert("Only these file types are accepted : "+validExtensions.join(', '));
}
else
{
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
// Old code here
/*$("<img></img>", {
class: "imageThumb",
src: e.target.result,
title: file.name + " | Click to remove"
}).insertAfter("#files").click(function(){$(this).remove();});*/
});
fileReader.readAsDataURL(f);
}
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
<style type="text/css">
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
</style><file_sep><?php
namespace frontend\assets;
use yii\web\AssetBundle;
/**
* Main frontend application asset bundle.
*/
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/demo.css',
'css/elephant.css',
'css/styleStep2.css',
'css/style.css',
'css/css.css',
'css/site-style.css',
];
public $js = [
'js/scrolling-nav.js',
'https://www.google.com/recaptcha/api.js',
'js/script.js',
];
public function init()
{
parent::init();
}
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapPluginAsset',
];
}
<file_sep><?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use backend\models\LocationControl;
use common\models\ApartmentAmenities;
use common\models\HouseType;
use kartik\file\FileInput;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $model common\models\SubmitData */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="submit-data-form">
<?php $form = ActiveForm::begin([
'options' => [
'enctype' => 'multipart/form-data',
]
]); ?>
<div class="col-md-6">
<?= $form->field($model, 'published')->dropDownList(['0', '1',], ['prompt' => Yii::t('app', 'Select Published or Not')]) ?>
</div>
<div class="col-md-6">
<?php
$packages = ArrayHelper::map(\common\models\PaymentDetails::find()->all(), 'id', 'name');
if(!$model->isNewRecord) {
$model->package_id = explode(',', $model->package_id);
}
?>
<?= $form->field($model, 'package_id')->checkboxList($packages) ?>
</div>
<div class="clearfix"></div>
<div class="col-xs-12">
<?php
$package_duration_id = ArrayHelper::map(\common\models\PackageDuration::find()->where(['is_status' => 1])->all(), 'id', 'duration');
?>
<?= $form->field($model, 'package_duration_id')->dropDownList($package_duration_id, ['prompt' => Yii::t('app', 'Select Package Duration')])->label(Yii::t('app', 'Package Duration (Months)')) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'login')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'pass')->passwordInput(['maxlength' => true]) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'l_name')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'gender')->dropDownList(['Male' => 'Male', 'Female' => 'Female']) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'phone')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'postal_code')->textInput(['maxlength' => true]) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'street')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'address')->textInput(['maxlength' => true]) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-12">
<?php
$ApartmentAmenitiesData = ArrayHelper::map(ApartmentAmenities::find()->asArray()->all(), 'id', 'apartment');
if (Yii::$app->controller->action->id != "update") {
echo $form->field($model, 'contact_time')->checkboxList(
['a' => 'Afternoon', 'e' => 'Evening', 'm' => 'Morning']);
echo $form->field($model, 'apartment_ids')->checkboxList($ApartmentAmenitiesData, [
'itemOptions' => [
'labelOptions' => ['class' => 'col-md-3']
]
]);
} else {
$selectedContact_time = [];
$selectedApartment_id = [];
foreach (explode(',', $model->contact_time) as $key => $val) {
$selectedContact_time[$val] = $val;
}
echo $form->field($model, 'contact_time')->checkboxList(
['a' => 'Afternoon', 'e' => 'Evening', 'm' => 'Morning'], [
'value' => $selectedContact_time
]);
/**
* sort array selected data
*/
foreach (explode(',', $model->apartment_ids) as $value) {
$selected[$value] = $value;
}
echo $form->field($model, 'apartment_ids')->checkboxList($ApartmentAmenitiesData, [
'itemOptions' => [
'labelOptions' => ['class' => 'col-md-3 col-sm-6 col-xs-12']
],
'value' => $selected
]);
}
$region = ArrayHelper::map(LocationControl::getRegion(), 'name', 'name');
if (!$model->isNewRecord) {
$regionId = LocationControl::getRegionId($model->region);
$city = ArrayHelper::map(LocationControl::getCity($regionId), 'name', 'name');
} else {
$city = ArrayHelper::map(LocationControl::getCity(1), 'name', 'name');
}
?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'region')->dropDownList(
$region,
[
'onChange' => '
$.get("' . yii\helpers\Url::toRoute(['submit-data/get-city']) . '", { name: $(this).val() })
.done(function(data){
$("#submitdata-city").html( data );
});'
]
)
->label(Yii::t('app', 'Region')) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'city')->dropDownList($city, [
$model->city => $model->city
]) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'rent')->textInput() ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'house_type_id')->dropDownList(ArrayHelper::map(HouseType::find()->asArray()->all(), 'id', 'house')) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-12">
<?= $form->field($model, 'title')->textInput() ?>
</div>
<div class="clearfix"></div>
<div class="col-md-12">
<?= $form->field($model, 'content')->textarea(['rows' => 12]) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'apt_size')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'bedroom')->textInput(['maxlength' => true]) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'bathroom')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'available_date')->widget(\kartik\date\DatePicker::className(), [
'name' => 'check_issue_date',
'options' => ['placeholder' => 'Select available date ...'],
'pluginOptions' => [
'format' => 'yyyy-mm-dd',
'todayHighlight' => true
]
]) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'pets')->dropDownList(['0' => 'Not Allowed', '1' => 'Allowed',]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'parking_included')->dropDownList([
'1' => Yii::t('app', 'Yes'),
'2' => Yii::t('app', 'Available with additional fee'),
'0' => Yii::t('app', 'No parking Available'),
],[
'prompt' => Yii::t('app', 'Select Parking')
])->label(Yii::t('app', 'Parking Included'))
?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'parking_count')->textInput() ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'parking_price')->textInput(['maxlength' => true]) ?>
</div>
<div class="clearfix"></div>
<div class="col-md-12">
<?php
$allImage = [];
$initialPreviewConfig = [];
$uploadUrl = false;
if (Yii::$app->controller->action->id == "update") {
$uploadUrl = Url::to(['/submit-data/upload?id=' . $model->id]);
$arrayImgPath = explode(';', $model->image_url);
if ($arrayImgPath[0] != "") {
foreach ($arrayImgPath as $val) {
$img = explode('/', $val);
$img = $img[count($img)-1];
$allImage[] = $val;
$initialPreviewConfig[] = [
'caption' => $img,
'size' => file_exists(Yii::getAlias('@frontend') . '/web/img/upload/' . $img) ? filesize(Yii::getAlias('@frontend') . '/web/img/upload/' . $img) : NULL,
'width' => "120px",
'url' => Yii::$app->homeUrl . "submit-data/file-delete?id=" . $model->id,
'key' => $val,
];
}
} else {
$allImage = 0;
}
}else{
echo "<style>
.kv-file-upload{
display: none !important;
}
</style>";
}
?>
<?= $form->field($model, 'image[]')->widget(FileInput::classname(), [
'attribute' => 'image[]',
'name' => 'image[]',
'options' => [
'accept' => 'image/*',
'multiple' => true,
],
'pluginOptions' => [
'previewFileType' => 'image',
'allowedFileExtensions' => ['jpg'],
'maxFileSize' => 1024,
'showPreview' => true,
'showUpload' => false,
'showCaption' => false,
'uploadUrl' => $uploadUrl,
'initialPreview' => $allImage,
'initialPreviewAsData' => true,
'initialPreviewConfig' => $initialPreviewConfig,
'overwriteInitial' => false,
'initialPreviewShowDelete' => true,
'resizeImages' => true,
],
]);?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'zone')->dropDownList(['Milton-Parc' => 'Milton-Parc', 'West of Campus' => 'West of Campus', 'Concordia Area' => 'Concordia Area', 'Lower Plateau' => 'Lower Plateau', 'UQAM/The Village' => 'UQAM/The Village', 'Hampstead' => 'Hampstead', 'Cote-des-Neiges' => 'Cote-des-Neiges', 'Université de Montréal Area' => 'Université de Montréal Area', 'Plateau' => 'Plateau', 'Mile-End' => 'Mile-End', 'Around MAC campus' => 'Around MAC campus', 'N.D.G.' => 'N.D.G.', 'Outremont' => 'Outremont', 'Old Montréal' => 'Old Montréal', 'Rosemont' => 'Rosemont', 'Little Burgundy/St-Henri' => 'Little Burgundy/St-Henri', 'Town Mont Royal' => 'Town Mont Royal', 'Verdun/St-Charles/LaSalle' => 'Verdun/St-Charles/LaSalle', 'Westmount' => 'Westmount', 'Parc Extension' => 'Parc Extension', 'Areas outside the zone map' => 'Areas outside the zone map',], ['prompt' => Yii::t('app', 'Select Zone')]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'lease_length')->textInput() ?>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<?= $form->field($model, 'region_iso')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<?= $form->field($model, 'floor_count')->textInput(['maxlength' => true]) ?>
</div>
<div class="clearfix"></div>
<div class="form-group">
<div class="col-md-12">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<br>
</div>
<?php ActiveForm::end(); ?>
</div>
<file_sep><?php
return [
'adminEmail' => '<EMAIL>',
'image' => Yii::getAlias('@frontend') . '/web/img/upload/',
];
<file_sep><?php
use yii\helpers\Html;
/* @var $this \yii\web\View view component instance */
/* @var $message \yii\mail\MessageInterface the message being composed */
/* @var $content string main view render result */
?>
<?php $this->beginPage() ?>
<?php $this->beginBody() ?>
<h2 style="color: rgba(151, 151, 151, 0.5); text-align: center;">Contact Message</h2>
<table frame="box" rules="all" cellpadding="15" style="margin:auto;box-shadow: -2px -2px 4px grey, 4px 4px 4px grey;line-height:1.6;width:100%;">
<tr>
<th>Name</th>
<td><?= $name ?></td>
</tr>
<tr>
<th>E-mail</th>
<td><?= $email ?></td>
</tr>
<tr>
<th>Subject</th>
<td><?= $subject ?></td>
</tr>
<tr>
<th>Message</th>
<td><?= $content ?></td>
</tr>
</table>
<?php $this->endBody() ?>
<?php $this->endPage() ?>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="manifest.json">
<link rel="mask-icon" href="safari-pinned-tab.svg" color="#27ae60">
<meta name="theme-color" content="#ffffff">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,700">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/vendor.min.css">
<link rel="stylesheet" href="css/elephant.min.css">
<link rel="stylesheet" href="css/application.min.css">
<link rel="stylesheet" href="css/demo.min.css">
<link rel="stylesheet" href="css/styleStep2.css">
<link href="css/css(1).css" rel="stylesheet" type="text/css">
<link href="css/css.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="build.js?v=6"></script>
<script>
var Dropzone = require("enyo-dropzone");
Dropzone.autoDiscover = false;
</script>
<style>
/* .layout-main {
height: 1900px ;
}
@media (max-width: 768px){
.layout-main {
height: 495% !important;
}
}*/
html, body {
height: 100%;
}
#actions {
margin: 1em 0;
}
/* Mimic table appearance */
div.table {
display: table;
}
div.table .file-row {
display: table-row;
}
div.table .file-row > div {
display: table-cell;
vertical-align: top;
border-top: 1px solid #ddd;
padding: 8px;
}
div.table .file-row:nth-child(odd) {
background: #f9f9f9;
}
/* The total progress gets shown by event listeners */
#total-progress {
opacity: 0;
transition: opacity 0.3s linear;
}
/* Hide the progress bar when finished */
#previews .file-row.dz-success .progress {
opacity: 0;
transition: opacity 0.3s linear;
}
/* Hide the delete button initially */
#previews .file-row .delete {
display: none;
}
/* Hide the start and cancel buttons and show the delete button */
#previews .file-row.dz-success .start,
#previews .file-row.dz-success .cancel {
display: none;
}
#previews .file-row.dz-success .delete {
display: block;
}
@media(min-width:767px) {
.navbar {
padding: 20px 0;
-webkit-transition: background .5s ease-in-out,padding .5s ease-in-out;
-moz-transition: background .5s ease-in-out,padding .5s ease-in-out;
transition: background .5s ease-in-out,padding .5s ease-in-out;
}
.top-nav-collapse {
padding: 0;
}
.navbar-header {
background-color: #ffffff !important;
}
.layout-content-body {
padding: 55px 15px 35px !important;}
}
</style>
</head>
<body class="layout layout-header-fixed">
<input type="hidden" id="_q" value="<?php echo uniqid() . '-' . time(); ?>">
<div class="menu navbar-fixed-top">
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="logo">
<a href="http://www.aufposting.com"><img src="img/Auf Posting Logo.png" class="img_responsive"> </a>
</div>
</div>
<div class="col-md-9">
<nav role="navigation" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class=""><a class="page-scroll" href="http://www.aufposting.com/#success">Marketing Services</a></li>
<li class=""><a class="page-scroll" href="http://www.aufposting.com/#contact_us">Contact Us</a></li>
<li><a href="http://www.aufposting.com/form_property.php">Sign Up</a></li>
</ul>
</div>
</nav>
</div>
</div>
</div>
</div>
<div class="layout-main">
<div class="layout-content">
<div class="layout-content-body">
<!-- Commented <div class="text-center m-b">
<h3 class="m-b-0">With Form Validation</h3>
<small>The following case does not allow moving to the next step without validating the form in the current step successfully.</small>
</div><-->
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="demo-form-wrapper">
<form id="demo-form-wizard-2" data-toggle="validator" novalidate="novalidate">
<ul class="steps">
<li class="step col-xs-4 active">
<a class="step-segment" href="#step-2" data-toggle="tab">
<span class="step-icon icon icon-user"></span>
</a>
<div class="step-content">
<strong class="hidden-xs">About You</strong>
</div>
</li>
<li class="step col-xs-4">
<a class="step-segment" href="#step-2" data-toggle="tab">
<span class="step-icon icon icon-cubes"></span>
</a>
<div class="step-content">
<strong class="hidden-xs">About The Property</strong>
</div>
</li>
<li class="step col-xs-4">
<a class="step-segment" href="#step-3" data-toggle="tab">
<span class="step-icon icon icon-credit-card"></span>
</a>
<div class="step-content">
<strong class="hidden-xs">Payment details</strong>
</div>
</li>
</ul>
<div class="tab-content" style=" margin-top: 30px;">
<div id="step-1" class="tab-pane active">
<h4 class="text-center m-y-md">
<span>About You</span>
</h4>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="form-group">
<label for="name-1" class="control-label">First Name*</label>
<input id="name-1" class="form-control" type="text" name="name_1" spellcheck="false" autocomplete="on" data-rule-required="true">
<small class="help-block">Displayed on your profile and in other places as your name.</small>
</div>
<div class="form-group">
<label for="last_name" class="control-label">Last Name*</label>
<input id="last_name" class="form-control" type="text" name="last_name" spellcheck="false" autocomplete="on" data-rule-required="true">
<small class="help-block">Displayed on your profile and in other places as your Last Name.</small>
</div>
<div class="form-group">
<label for="phone" class="control-label">Phone Number*</label>
<input id="phone" class="form-control" type="text" name="phone" spellcheck="false" autocomplete="on" data-rule-required="true" data-msg-required="Please enter a valid Phone Number." data-rule-minlength="6">
<small class="help-block">Your phone number.</small>
</div>
<div class="form-group">
<label for="email-2" class="control-label">Email address*</label>
<input id="email-2" class="form-control" type="email" name="email_2" spellcheck="false" autocomplete="on" data-rule-required="true" data-rule-email="true" data-msg-required="Please enter your email address.">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block btn-next" type="button">NEXT</button>
</div>
</div>
</div>
</div>
<div id="step-2" class="tab-pane">
<!-- <h4 class="text-center m-y-md">
<span>About The Property</span>
</h4>-->
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="form-group">
<div class="col-sm-6">
<label for="demo-select2-4" class="form-label">Country*</label>
<select id="demo-select2-4" class="form-control">
<option value="us">United States</option>
<option value="af">Afghanistan (افغانستان)</option>
<option value="al">Albania (Shqipëri)</option>
<option value="dz">Algeria</option>
<option value="as">American Samoa</option>
<option value="ad">Andorra</option>
<option value="ao">Angola</option>
<option value="ai">Anguilla</option>
<option value="ag">Antigua & Barbuda</option>
<option value="ar">Argentina</option>
<option value="am">Armenia (Հայաստան)</option>
<option value="aw">Aruba</option>
<option value="au">Australia</option>
<option value="at">Austria (Österreich)</option>
<option value="az">Azerbaijan (Azərbaycan)</option>
<option value="bs">Bahamas</option>
<option value="bh">Bahrain (البحرين)</option>
<option value="bd">Bangladesh (বাংলাদেশ)</option>
<option value="bb">Barbados</option>
<option value="by">Belarus (Беларусь)</option>
<option value="be">Belgium</option>
<option value="bz">Belize</option>
<option value="bj">Benin (Bénin)</option>
<option value="bm">Bermuda</option>
<option value="bt">Bhutan (འབྲུག)</option>
<option value="bo">Bolivia</option>
<option value="ba">Bosnia & Herzegovina (Босна и Херцеговина)</option>
<option value="bw">Botswana</option>
<option value="br">Brazil (Brasil)</option>
<option value="io">British Indian Ocean Territory</option>
<option value="vg">British Virgin Islands</option>
<option value="bn">Brunei</option>
<option value="bg">Bulgaria (България)</option>
<option value="bf">Burkina Faso</option>
<option value="bi">Burundi (Uburundi)</option>
<option value="kh">Cambodia (កម្ពុជា)</option>
<option value="cm">Cameroon (Cameroun)</option>
<option value="ca" selected>Canada</option>
<option value="cv">Cabo Verde (Kabu Verdi)</option>
<option value="cf">Central African Republic (République centrafricaine)</option>
<option value="td">Chad (Tchad)</option>
<option value="cl">Chile</option>
<option value="cn">China (中国)</option>
<option value="co">Colombia</option>
<option value="km">Comoros (جزر القمر)</option>
<option value="cg">Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)</option>
<option value="cg">Congo (Republic) (Congo-Brazzaville)</option>
<option value="ck">Cook Islands</option>
<option value="cr">Costa Rica</option>
<option value="ci">Côte d'Ivoire</option>
<option value="hr">Croatia (Hrvatska)</option>
<option value="cu">Cuba</option>
<option value="cw">Curaçao</option>
<option value="cy">Cyprus (Κύπρος)</option>
<option value="cz">Czech Republic (Česká republika)</option>
<option value="dk">Denmark (Danmark)</option>
<option value="dj">Djibouti</option>
<option value="do">Dominica</option>
<option value="do">Dominican Republic (República Dominicana)</option>
<option value="ec">Ecuador</option>
<option value="eg">Egypt (مصر)</option>
<option value="sv">El Salvador</option>
<option value="gq">Equatorial Guinea (Guinea Ecuatorial)</option>
<option value="er">Eritrea</option>
<option value="ee">Estonia (Eesti)</option>
<option value="et">Ethiopia</option>
<option value="fk">Falkland Islands (Islas Malvinas)</option>
<option value="fo">Faroe Islands (Føroyar)</option>
<option value="fj">Fiji</option>
<option value="fi">Finland (Suomi)</option>
<option value="fr">France</option>
<option value="gf">French Guiana (Guyane française)</option>
<option value="pf">French Polynesia (Polynésie française)</option>
<option value="ga">Gabon</option>
<option value="gm">Gambia</option>
<option value="gs">Georgia (საქართველო)</option>
<option value="de">Germany (Deutschland)</option>
<option value="gh">Ghana (Gaana)</option>
<option value="gi">Gibraltar</option>
<option value="gr">Greece (Ελλάδα)</option>
<option value="gl">Greenland (Kalaallit Nunaat)</option>
<option value="gd">Grenada</option>
<option value="gp">Guadeloupe</option>
<option value="gu">Guam</option>
<option value="gt">Guatemala</option>
<option value="pg">Guinea (Guinée)</option>
<option value="gw">Guinea-Bissau (Guiné-Bissau)</option>
<option value="gy">Guyana</option>
<option value="ht">Haiti</option>
<option value="hn">Honduras</option>
<option value="hk">Hong Kong (香港)</option>
<option value="hu">Hungary (Magyarország)</option>
<option value="is">Iceland (Ísland)</option>
<option value="in">India (भारत)</option>
<option value="id">Indonesia</option>
<option value="ir">Iran (ایران)</option>
<option value="iq">Iraq (العراق)</option>
<option value="ie">Ireland</option>
<option value="il">Israel (ישראל)</option>
<option value="it">Italy (Italia)</option>
<option value="jm">Jamaica</option>
<option value="jp">Japan (日本)</option>
<option value="jo">Jordan (الأردن)</option>
<option value="kz">Kazakhstan (Казахстан)</option>
<option value="ke">Kenya</option>
<option value="ki">Kiribati</option>
<option value="kw">Kuwait (الكويت)</option>
<option value="kg">Kyrgyzstan (Кыргызстан)</option>
<option value="la">Laos (ລາວ)</option>
<option value="lv">Latvia (Latvija)</option>
<option value="lb">Lebanon (لبنان)</option>
<option value="ls">Lesotho</option>
<option value="lr">Liberia</option>
<option value="ly">Libya (ليبيا)</option>
<option value="li">Liechtenstein</option>
<option value="lt">Lithuania (Lietuva)</option>
<option value="lu">Luxembourg</option>
<option value="mo">Macau (澳門)</option>
<option value="mk">Macedonia (FYROM) (Македонија)</option>
<option value="mg">Madagascar (Madagasikara)</option>
<option value="mw">Malawi</option>
<option value="my">Malaysia</option>
<option value="mv">Maldives</option>
<option value="so">Mali</option>
<option value="mt">Malta</option>
<option value="mh">Marshall Islands</option>
<option value="mq">Martinique</option>
<option value="mr">Mauritania (موريتانيا)</option>
<option value="mu">Mauritius (Moris)</option>
<option value="mx">Mexico (México)</option>
<option value="fm">Micronesia</option>
<option value="md">Moldova (Republica Moldova)</option>
<option value="mc">Monaco</option>
<option value="mn">Mongolia (Монгол)</option>
<option value="me">Montenegro (Crna Gora)</option>
<option value="ms">Montserrat</option>
<option value="ma">Morocco</option>
<option value="mz">Mozambique (Moçambique)</option>
<option value="mm">Myanmar (Burma) (မြန်မာ)</option>
<option value="na">Namibia (Namibië)</option>
<option value="nr">Nauru</option>
<option value="np">Nepal (नेपाल)</option>
<option value="nl">Netherlands (Nederland)</option>
<option value="nc">New Caledonia (Nouvelle-Calédonie)</option>
<option value="nz">New Zealand</option>
<option value="ni">Nicaragua</option>
<option value="ng">Niger (Nijar)</option>
<option value="ng">Nigeria</option>
<option value="nu">Niue</option>
<option value="nf">Norfolk Island</option>
<option value="mp">Northern Mariana Islands</option>
<option value="kp">North Korea (조선민주주의인민공화국)</option>
<option value="no">Norway (Norge)</option>
<option value="ro">Oman (عُمان)</option>
<option value="pk">Pakistan (پاکستان)</option>
<option value="pw">Palau</option>
<option value="ps">Palestine (فلسطين)</option>
<option value="pa">Panama (Panamá)</option>
<option value="pg">Papua New Guinea</option>
<option value="py">Paraguay</option>
<option value="pe">Peru (Perú)</option>
<option value="ph">Philippines</option>
<option value="pl">Poland (Polska)</option>
<option value="pt">Portugal</option>
<option value="pr">Puerto Rico</option>
<option value="qa">Qatar (قطر)</option>
<option value="re">Réunion (La Réunion)</option>
<option value="ro">Romania (România)</option>
<option value="ru">Russia (Россия)</option>
<option value="rw">Rwanda</option>
<option value="ws">Samoa</option>
<option value="sm">San Marino</option>
<option value="st">São Tomé & Príncipe (São Tomé e Príncipe)</option>
<option value="sa">Saudi Arabia (المملكة العربية السعودية)</option>
<option value="sn">Senegal</option>
<option value="rs">Serbia (Србија)</option>
<option value="sc">Seychelles</option>
<option value="sl">Sierra Leone</option>
<option value="sg">Singapore</option>
<option value="sx">Sint Maarten</option>
<option value="sk">Slovakia (Slovensko)</option>
<option value="si">Slovenia (Slovenija)</option>
<option value="sb">Solomon Islands</option>
<option value="so">Somalia (Soomaaliya)</option>
<option value="za">South Africa</option>
<option value="kr">South Korea (대한민국)</option>
<option value="ss">South Sudan (جنوب السودان)</option>
<option value="es">Spain (España)</option>
<option value="lk">Sri Lanka (ශ්රී ලංකාව)</option>
<option value="bl">Saint Barthélemy (Saint-Barthélemy)</option>
<option value="sh">Saint Helena, Ascension & Tristan da Cunha</option>
<option value="kn">Saint Kitts & Nevis</option>
<option value="lc">Saint Lucia</option>
<option value="mf">Saint Martin (Saint-Martin)</option>
<option value="pm">Saint Pierre & Miquelon (Saint-Pierre-et-Miquelon)</option>
<option value="vc">Saint Vincent & Grenadines</option>
<option value="sd">Sudan (السودان)</option>
<option value="sr">Suriname</option>
<option value="sz">Swaziland</option>
<option value="se">Sweden (Sverige)</option>
<option value="ch">Switzerland (Schweiz)</option>
<option value="sy">Syria (سوريا)</option>
<option value="tw">Taiwan (台灣)</option>
<option value="tj">Tajikistan</option>
<option value="tz">Tanzania</option>
<option value="th">Thailand (ไทย)</option>
<option value="tl">Timor-Leste</option>
<option value="tg">Togo</option>
<option value="tk">Tokelau</option>
<option value="to">Tonga</option>
<option value="tt">Trinidad & Tobago</option>
<option value="tn">Tunisia</option>
<option value="tr">Turkey (Türkiye)</option>
<option value="tm">Turkmenistan</option>
<option value="tc">Turks & Caicos Islands</option>
<option value="tv">Tuvalu</option>
<option value="vi">U.S. Virgin Islands</option>
<option value="ug">Uganda</option>
<option value="ua">Ukraine (Україна)</option>
<option value="ae">United Arab Emirates (الإمارات العربية المتحدة)</option>
<option value="gb">United Kingdom</option>
<option value="us">United States</option>
<option value="uy">Uruguay</option>
<option value="uz">Uzbekistan (Oʻzbekiston)</option>
<option value="vu">Vanuatu</option>
<option value="va">Vatican City (Città del Vaticano)</option>
<option value="ve">Venezuela</option>
<option value="vn">Vietnam (Việt Nam)</option>
<option value="wf">Wallis & Futuna</option>
<option value="ye">Yemen (اليمن)</option>
<option value="zm">Zambia</option>
<option value="zw">Zimbabwe</option>
</select>
</div>
<div class="col-sm-6 ">
<label for="State" class="control-label">Province*</label>
<input id="city" class="form-control" type="text" name="state" spellcheck="false" autocomplete="on" data-rule-required="true">
</div>
</div>
<div class="col-sm-6 ">
<div class="form-group">
<label for="city" class="control-label">City*</label>
<input id="city" class="form-control" type="text" name="city" spellcheck="false" autocomplete="on" data-rule-required="true">
</div>
</div>
<div class="col-sm-6 ">
<div class="form-group">
<label for="postalcode" class="control-label">Postal Code*</label>
<input id="postalcode" class="form-control" type="text" name="postalcode" spellcheck="false" autocomplete="on" data-rule-required="true">
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<label for="street" class="control-label">Street Name*</label>
<input id="street" class="form-control" type="text" name="street" spellcheck="false" autocomplete="on" data-rule-required="true">
<!--<small class="help-block">Your Property Street Name.</small>-->
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<label for="address" class="control-label">Address*</label>
<input id="address" class="form-control" type="text" name="address" spellcheck="false" autocomplete="on" data-rule-required="true">
<!--<small class="help-block">Your Property Address.</small>-->
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<label for="sizeOfApt" class="control-label">Size of apartment (square feet)</label>
<input id="sizeOfApt" class="form-control" type="text" name="sizeOfApt" spellcheck="false" autocomplete="on" data-rule-required="true">
<!--<small class="help-block">Your Property Address.</small>-->
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<p class="signup__label">Property type <span class="ui-req">*</span></p>
<div class="col-sm-12 text-center">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success btn-pill active">
<input type="radio" name="Tpropiedad" value="Apartment" checked="checked"> Apartment
</label>
<label class="btn btn-success">
<input type="radio" value="House" name="Tpropiedad"> House
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="Studio" name="Tpropiedad"> Studio
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="Commercial" name="Tpropiedad"> Commercial
</label>
</div>
</div>
<br/>
<div class="signup__row signup__row--padded tooltips" id="divTotalNumberOfBedrooms">
<p class="signup__label">Total number of bedrooms <span class="ui-req">*</span></p>
<div class="col-sm-12 text-center">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success btn-pill active">
<input type="radio" value="1" name="numBeds" checked="checked"> 1
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="2" name="numBeds"> 2
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="3" name="numBeds"> 3
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="4" name="numBeds"> 4
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="5" name="numBeds"> 5
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="6" name="numBeds"> 6
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="7" name="numBeds"> 7
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="8" name="numBeds"> 8
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="More than 9" name="numBeds"> 9+
</label>
</div>
</div>
</div>
<br/>
<div class="signup__row signup__row--padded tooltips" id="divTotalNumberOfBathrooms">
<br/>
<p class="signup__label">Total number of bathrooms <span class="ui-req">*</span></p>
<div class="col-sm-12 text-center">
<select id="form-control-6" name="numBath" class="form-control" data-rule-required="true">
<option value="1">1 bathroom</option>
<option value="1.5" >1.5 bathrooms</option>
<option value="2">2 bathrooms</option>
<option value="2.5">2.5 bathrooms</option>
<option value="3">3 bathrooms</option>
<option value="3.5">3.5 bathrooms</option>
<option value="4">4 bathrooms</option>
<option value="4.5">4.5 bathrooms</option>
<option value="5">5 bathrooms</option>
<option value="5.5">5.5 bathrooms</option>
<option value="6">6 or more bathrooms</option>
</select>
</div>
</div>
<br/>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<br/>
<!-- <p class="signup__label">Property amenities</p>-->
<div class="signup__row signup__row--padded grid grid--split-4">
<div class="col-sm-12">
<div class="col-sm-7">
<label for="demo-select2-4" class="form-label" >Apartment Amenities</label><br>
<label for="A/C"><input type="checkbox" id="one" name="Apartmentamenities[]" value="A/C"/> A/C </label><br>
<label for=" Heating"><input type="checkbox" id="two" name="Apartmentamenities[]" value="Heating"/> Heating </label><br>
<label for="Hot Water"><input type="checkbox" id="three" name="Apartmentamenities[]" value="Hot Water"/> Hot Water </label><br>
<label for="Electricity"><input type="checkbox" id="four" name="Apartmentamenities[]" value="Electricity"/> Electricity </label><br>
<label for="Wifi"><input type="checkbox" id="five" name="Apartmentamenities[]" value="Wifi"/> Wifi</label><br>
<label for="TV"><input type="checkbox" id="six" name="Apartmentamenities[]" value="TV"/> TV </label><br>
<label for="Home Phone"><input type="checkbox" id="seven" name="Apartmentamenities[]" value="Home Phone"/> Home Phone</label><br>
<label for="Laundry"><input type="checkbox" id="eight" name="Apartmentamenities[]" value="Laundry In-Unit"/> Laundry In-Unit</label><br>
<label for="Fridge"><input type="checkbox" id="nine" name="Apartmentamenities[]" value="Fridge"/> Fridge </label><br>
<label for="Stove"><input type="checkbox" id="ten" name="Apartmentamenities[]" value="Stove"/> Stove </label><br>
<label for="Dishwasher"><input type="checkbox" id="eleven" name="Apartmentamenities[]" value="Dishwasher"/> Dishwasher </label><br>
<label for="Microwave"><input type="checkbox" id="twelve" name="Apartmentamenities[]" value="Microwave"/> Microwave </label><br>
<label for="Kitchen Amenities"><input type="checkbox" id="thirteen" name="Apartmentamenities[]" value="HeaOther Kitchen Amenitiesting"/> Other Kitchen Amenities </label><br>
<label for="Furnished"><input type="checkbox" id="fourteen" name="Apartmentamenities[]" value="Furnished"/> Furnished </label><br>
<label for="Wood Floor"><input type="checkbox" id="fiveteen" name="Apartmentamenities[]" value="Wood Floor"/> Wood Floor </label><br>
<label for="Tiles Floor"><input type="checkbox" id="sixteen" name="Apartmentamenities[]" value="Tiles Floor"/> Tiles Floor</label><br>
<label for="Carpet"><input type="checkbox" id="seveteen" name="Apartmentamenities[]" value="Carpet"/> Carpet </label><br>
<label for="Friendly"><input type="checkbox" id="eighteen" name="Apartmentamenities[]" value="Pet Friendly"/> Pet Friendly </label><br>
<label for="Balcony"><input type="checkbox" id="nineteen" name="Apartmentamenities[]" value="Balcony"/> Balcony </label><br>
</div>
<div class="col-sm-5">
<label for="demo-select2-4" class="form-label">Property Amenities</label><br>
<label for="one"><input type="checkbox" id="one" name="amenities[]" value="Hi-Rise /Low Rise"/> Hi-Rise /Low Rise </label><br>
<label for="two"><input type="checkbox" id="two" name="amenities[]" value="Elevator"/> Elevator</label><br>
<label for="three"><input type="checkbox" id="three" name="amenities[]" value="Concierge/Janitor"/> Concierge/Janitor</label><br>
<label for="four"><input type="checkbox" id="four" name="amenities[]" value="Security/Doorman"/> Security/Doorman </label><br>
<label for="five"><input type="checkbox" id="five" name="amenities[]" value="Administration"/> Administration</label><br>
<label for="six"><input type="checkbox" id="six" name="amenities[]" value="Gym"/> Gym </label><br>
<label for="seven"><input type="checkbox" id="seven" name="amenities[]" value="Pool"/> Pool</label><br>
<label for="eight"><input type="checkbox" id="eight" name="amenities[]" value="Sauna"/> Sauna</label><br>
<label for="nine"><input type="checkbox" id="nine" name="amenities[]" value="Laundry In-Building"/> Laundry In-Building</label> <br>
<label for="ten"><input type="checkbox" id="ten" name="amenities[]" value="Terrace"/> Terrace</label><br>
<label for="eleven"><input type="checkbox" id="eleven" name="amenities[]" value="Indoor Parking"/> Indoor Parking</label><br>
<label for="twuelve"><input type="checkbox" id="twelve" name="amenities[]" value="outdoor Parking"/> outdoor Parking</label><br>
<label for="thirteen"><input type="checkbox" id="thirteen" name="amenities[]" value="Storage/Locker Space"/> Storage/Locker Space</label><br>
<label for="fourteen"><input type="checkbox" id="fourteen" name="amenities[]" value="Cleaning Service"/> Cleaning Service</label><br>
</div>
</div>
</div>
</div>
</div>
<br/>
<!-- Aca se agrego los nuevos campos-->
<div class="col-sm-6">
<div class="form-group">
<label for="leaseterm" class="control-label">Minimum Lease Term</label>
<select id="demo-select2-4" name="minLease" class="form-control" data-rule-required="true">
<option value="Month to Month">Month to Month</option>
<option value="6months">6 months</option>
<option value="1year">1 year</option>
<option value="Over1year" selected="selected">Over 1 year</option>
</select>
</div>
</div>
<div class="col-sm-3" style="padding-right: 0;">
<div class="form-group">
<label for="rent" class="control-label" style=" font-size: 0.8em;">Rent (price of rent)</label><br>
<label for="rent" class="control-label">$</label><input id="priceAmount" class="price-button" data-dependent-change="required,disabled,focus,clear" data-type="price" data-dependent="true" data-max="99999999.99" data-dependent-on="#priceType1" name="rentPrice" type="number" value="" maxlength="11" data-rule-required="true" data-msg-required="Please enter a value" data-rule-min="15">
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label for="demo-select2-8" class="form-label">Furnished</label>
<select id="demo-select2-8" name="furnished" class="form-control" data-rule-required="true">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="demo-select2-6" class="form-label">Pets Allowed</label>
<select id="demo-select2-6" name="petsAllow" class="form-control" data-rule-required="true">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="demo-select6-7" class="form-label">Parking Included</label>
<select id="demo-select6-7" name="parkingInc" class="form-control" data-rule-required="true">
<option value="Yes">Yes</option>
<option value="Available with additional fee">Available with additional fee</option>
<option value="No parking Available">No parking Available</option>
</select>
</div>
</div>
<br/>
<button class="btn btn-primary btn-block btn-next" type="button">NEXT</button>
</div>
</div>
</div>
<div id="step-3" class="tab-pane">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="form-group">
<label for="titlead" class="control-label">Title of the Ad*</label>
<input id="titlead" class="form-control" type="text" name="titleAd" spellcheck="false" autocomplete="on" data-rule-required="true">
</div>
<div class="form-group">
<label for="descriptionAd" class="control-label">Description (500 characters max)*</label>
<textarea id="descriptionAd" class="form-control" name="descriptionAd" rows="5" data-rule-required="true"></textarea>
</div>
<div class="form-group">
<div id="actions" class="row">
<label for="address" class="control-label">Upload Pictures*</label><br>
<div class="col-lg-12">
<!-- The fileinput-button span is used to style the file input field as button -->
<small> * You MUST click Upload on the images or they won't be sent to us</small>
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
</span>
<button type="button" class="btn btn-primary start">
<i class="fa fa-upload"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="fa fa-ban"></i>
<span>Cancel upload</span>
</button>
</div>
<div class="col-lg-5">
<!-- The global file processing state -->
<span class="fileupload-process">
<div id="total-progress" class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</span>
</div>
</div>
<div class="table table-striped files" id="previews">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail /></span>
</div>
<div>
<p class="name" data-dz-name></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div>
<p class="size" data-dz-size></p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
<div>
<button type="button" class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start</span>
</button>
<button type="button" data-dz-remove class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel</span>
</button>
<button type="button" data-dz-remove class="btn btn-danger delete">
<i class="glyphicon glyphicon-trash"></i>
<span>Delete</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<h4 class="text-center m-y-md">
<!-- <span>Enter your payment details</span>-->
</h4>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<!-- <div class="form-group">
<label for="creditcard-type-2" class="control-label">Card type</label>
<select id="creditcard-type-2" class="custom-select" name="creditcard_type_2" data-rule-required="true" data-msg-required="Please select your credit card type.">
<option value="" selected="selected">Select a card</option>
<option value="Visa">Visa</option>
<option value="MasterCard">MasterCard</option>
<option value="American Express">American Express</option>
<option value="Discover">Discover</option>
</select>
</div>
<div class="form-group">
<label for="creditcard-number-2" class="control-label">Card number</label>
<input id="creditcard-number-2" class="form-control" type="text" name="creditcard_number_2" data-rule-required="true" data-rule-creditcard="true" data-msg-required="Please enter your credit card number." data-msg-creditcard="Please enter a valid credit card number.">
</div>
<div class="form-group">
<div class="row gutter-xs">
<div class="col-xs-6">
<div class="form-group">
<label for="creditcard-expdate-month-2" class="control-label">Expiration Date</label>
<div class="row gutter-xs">
<div class="col-xs-6">
<select id="creditcard-expdate-month-2" class="custom-select" name="creditcard_expdate_month_2">
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
<option value="4">04</option>
<option value="5">05</option>
<option value="6">06</option>
<option value="7">07</option>
<option value="8">08</option>
<option value="9" selected="selected">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<div class="col-xs-6">
<select class="custom-select" name="creditcard_expdate_year_2">
<option value="2016" selected="selected">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
<option value="2026">2026</option>
<option value="2027">2027</option>
<option value="2028">2028</option>
<option value="2029">2029</option>
<option value="2030">2030</option>
<option value="2031">2031</option>
<option value="2032">2032</option>
<option value="2033">2033</option>
<option value="2034">2034</option>
<option value="2035">2035</option>
<option value="2036">2036</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-xs-5 col-xs-offset-1">
<div class="form-group">
<label for="creditcard-csc-2" class="control-label">Card Security Code</label>
<input id="creditcard-csc-2" class="form-control" type="text" name="creditcard_csc_2" data-rule-required="true" data-rule-minlength="3" data-rule-maxlength="4" data-msg-required="Please enter your credit card CSC (Card Security Code)." data-msg-minlength="Please enter a valid CSC (Card Security Code)" data-msg-maxlength="Please enter a valid CSC (Card Security Code)">
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="coupon-code-2" class="control-label">Coupon code</label>
<input id="coupon-code-2" class="form-control" type="text" name="coupon_code_2">
</div>-->
<div class="form-group">
<br>
<!-- <p>
<small>By clicking Submit, you agree to our <a href="#">Terms</a> and that you have read our <a href="#">Data Policy</a>, including our <a href="#">Cookie Use</a>.</small>
</p>-->
<button id="formFinal" class="btn btn-primary btn-block" type="button">Pay now</button>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="hFrmPaypal"> <form id="frmPaypal" style="text-align: center;" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="FK99BZ6WQLQD2">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_paynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="js/jquery_003.js.descarga" type="text/javascript"></script>
<script src="js/bootstrap.min.js.descarga" type="text/javascript"></script>
<script src="js/jquery.js.descarga"></script>
<script src="js/scrolling-nav.js.descarga"></script>
<script src="js/vendor.min.js"></script>
<script src="js/elephant.min.js"></script>
<script src="js/application.min.js"></script>
<script src="js/demo.min.js"></script>
<script>
$('#hFrmPaypal').hide();
$( "#formFinal" ).on( "click", function() {
if($("#demo-form-wizard-2").valid()){
var datos = $('#demo-form-wizard-2').find('input, select, textarea, button').serialize();
var _q = $('#_q').val();
console.log(datos);
$.ajax({
url: "mail.php?method=sendMail&_q=" + _q,
type: "POST",
data: {
datos: datos
},
success: function(data) {
//alert(data);
$('#frmPaypal').submit();
},
error: function(error) {
alert("ERROR: " + error);
}
});
}
});
// Get the template HTML and remove it from the doument
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
url: "upload.php", // Set the url
thumbnailWidth: 80,
thumbnailHeight: 80,
parallelUploads: 20,
previewTemplate: previewTemplate,
autoQueue: false, // Make sure the files aren't queued until manually added
previewsContainer: "#previews", // Define the container to display the previews
clickable: ".fileinput-button" // Define the element that should be used as click trigger to select files.
});
myDropzone.on("success", function(file, responseText) {
//console.log(responseText);
});
myDropzone.on("addedfile", function(file) {
// Hookup the start button
file.previewElement.querySelector(".start").onclick = function() { myDropzone.enqueueFile(file); };
console.log("start ".file);
});
// Update the total progress bar
myDropzone.on("totaluploadprogress", function(progress) {
document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
});
myDropzone.on("sending", function(file) {
// Show the total progress bar when upload starts
document.querySelector("#total-progress").style.opacity = "1";
// And disable the start button
file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});
// Hide the total progress bar when nothing's uploading anymore
myDropzone.on("queuecomplete", function(progress) {
document.querySelector("#total-progress").style.opacity = "0";
});
// Setup the buttons for all transfers
// The "add files" button doesn't need to be setup because the config
// `clickable` has already been specified.
document.querySelector("#actions .start").onclick = function() {
myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
console.log("start img ".file);
};
document.querySelector("#actions .cancel").onclick = function() {
myDropzone.removeAllFiles(true);
};
</script>
<div class="footer">
<div class="footer-bottom">
<div class="container">
<div class="row">
<div class="col-md-12">
<p id="footer-info">
© AUF Posting 2016. All rights reserved.
</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html><file_sep>//https://my.locanto.info/register?cid=6&paf&continue=http%3A%2F%2Fwww.locanto.ca%2Fpost%2FR%2F301%2F1%2F
//http://www.locanto.ca/post/R/301/1/
//https://my.locanto.info/register?cid=6&continue=http%3A%2F%2Fwww.locanto.ca%2Fpost%2FR%2F301%2F1%2F
//https://my.locanto.info/activate?email=ads.submiter%40gmail.com&ctrlStr=065338&cid=6
//http://mb.locanto.ca/manage/1174557606/TBNSyQ/?published
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url.indexOf('my.locanto.info/register') + 1 && $("[id=email]").length > 0) {
registration();
} else if (url.indexOf('/post/R/301/1') && $("[id=target_form]").length) {
addDetails();
} else if (url == 'http://www.locanto.ca/post/R/301/1' || url.indexOf('my.locanto.info/register') + 1 && !$("[id=target_form]").length && !$("[id=email]").length) {
chrome.storage.local.get('ads', function (data) {
getMail('<EMAIL>', function () {
var email = /(\w+)@/.exec(data.ads.email)[1];
var pattern = new RegExp('href=["\'](.*?locanto\.ca.*?' + email + '[^"\']+)', 'igm');
var href = pattern.exec($('#gh-mail-respons').html())[1].replace(/&/g, '&');
window.location.href = href;
}, 300);
});
} else if (url.indexOf('activate?email') + 1 || url.indexOf('activate?cid=') + 1) {
activateProfile();
} else if (url.indexOf('?published') + 1) {
nextSite(true);
} else {
nextSite(false);
}
function registration() {
chrome.storage.local.get('ads', function (data) {
/**/
$("[id=email]").click();
$('[id=email]').val(data.ads.email);
/*-->*/
$('form').find('[type=submit]').click();
});
}
function addDetails() {
addPhoto();
chrome.storage.local.get('ads', function (data) {
/**/
$("[id=post_type_1]").click();
/**/
$('[name=price]').click();
$('[name=price]').val(data.ads.rent);
/**/
$('[name=itv]').click();
$('[name=itv]').val('1');
/**/
$('[id=subject]').click();
$('[id=subject]').val(data.ads.title);
/**/
$('[id=textEmail]').click();
// $('[id=textEmail]').val(data.ads.email);
$('[id=textEmail]').val('<EMAIL>');
/**/
$('[id=description]').click();
$('[id=description]').val(data.ads.content);
/*******CHOOSE BEDROOMS*******/
selector($('[name=rooms]'), data.ads.bedroom + ' ' + 'BR');
/**/
$('[name=size]').click();
$('[name=size]').val(data.ads.apt_size);
/**/
$('[name=phone_number]').click();
$('[name=phone_number]').val('n');
$("[name=phone_number]")[0].dispatchEvent(new Event('change'));
/**/
$('[name=phone_number_input]').click();
$('[name=phone_number_input]').val(data.ads.phone);
/**/
$('[id=mapStreet]').click();
$('[id=mapStreet]').val(data.ads.street);
$("[id=mapStreet]")[0].dispatchEvent(new Event('click'));
/**/
$('[id=geo_search_post]').click();
$('[id=geo_search_post]').val(data.ads.city + ', ' + data.ads.region);
/**/
$('[id=mapZip]').click();
$('[id=mapZip]').val(data.ads.postal_code);
});
}
function addPhoto() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
$.each($('form').find('input'), function () {
if ($(this).attr('type') != 'checkbox' || $(this).attr('type') != 'radio' || ($(this).attr('type') == 'checkbox' && !$(this).is(':checked')) || ($(this).attr('type') == 'radio' && !$(this).is(':checked')))
data.append($(this).attr('name'), $(this).val());
});
$.each($('form').find('textarea'), function () {
data.append($(this).attr('name'), $(this).val());
});
$.each($('form').find('select'), function () {
data.append($(this).attr('name'), $(this).val());
});
data.append('img_upload', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', '//www.locanto.ca/api/ajax/upload/', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var response = JSON.parse(xhr.responseText);
$('#img_upload_container').find('ul').prepend(`<li class="single_image js-single_image gallery"><input type="hidden" name="img_uploaded[]" value="${response.img_upload[0].name}"><div class="container"><img src="${response.img_upload[0].tn_url}" alt=""></div><a href="#" class="js-img_delete">Delete image</a><div class="gallery_label">Preview image</div></li>`);
if (++i < images.length) {
_uploadeimage(i);
} else {
/*****GO TO NEXT STEP*******/
$('[id=target_form]').find('[name=post_directly]').click();
}
}
};
xhr.send(data);
}
});
}
function activateProfile() {
chrome.storage.local.get('ads', function (data) {
/**/
$("[name=professional][value='0']").click();
switch (data.ads.gender) {
case "Male":
$("[name=sex][value='mr']").click();
break;
case "Female":
$("[name=sex][value='mrs']").click();
break;
}
$('[name=nickname]').click();
$('[name=nickname]').val(data.ads.login);
$('[name=given_name]').click();
$('[name=given_name]').val(data.ads.name);
/**/
$('[name=name]').click();
$('[name=name]').val(data.ads.l_name);
/**/
$('[name=pwd]').click();
$('[name=pwd]').val(data.ads.pass);
/**/
$('[name=pwd2]').click();
$('[name=pwd2]').val(data.ads.pass);
/**/
$('[name=terms_of_use_accept]').click();
$("[name=terms_of_use_accept]")[0].dispatchEvent(new Event('click'));
/**/
$('[name=newsletter_subscribe]').click();
$("[name=newsletter_subscribe]")[0].dispatchEvent(new Event('click'));
$('[id=submit]').click();
/**/
});
}
});
<file_sep>//https://www.snapuprealestate.ca/listing/create
//https://www.snapuprealestate.ca/listing/index
//https://www.snapuprealestate.ca/listing/Montreal-QC/condos-for-rent-2100-Saint-Marc-Montreal-7546332866
/* global chrome, captchaStatus */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'https://www.snapuprealestate.ca/listing/create') {
start();
} else if (url == 'https://www.snapuprealestate.ca/listing/index') {
myMail();
} else if (url.indexOf('https://www.snapuprealestate.ca/listing') + 1 && $('#myTab').length > 0) {
nextSite(true);
} else {
nextSite(false);
}
function start() {
chrome.storage.local.get('ads', function (data) {
$('[name=category][id=category2]').click();
/**/ $('[name=day_available]').click();
/**/$('[name=propertyType]')[0].click();
$('[name=propertyType]').change(function () {
window.setTimeout(function () {
if (data.ads.house_type != 'Apartment') {
selector($('[name=type]'), 'Other');
} else {
selector($('[name=condominiumType]'), 'Apartment');
}
}, 1000);
});
if (data.ads.house_type != 'Studio') {
selector($('[name=propertyType]'), data.ads.house_type);
} else {
selector($('[name=propertyType]'), 'Houses');
}
/**/$('[name=numberOfBedrooms]').click();
$('[name=numberOfBedrooms]').val(data.ads.bedroom);
/**/$('[name=numberOfBathrooms]').click();
$('[name=numberOfBathrooms]').val(data.ads.bathroom);
/**/$('[name=areaCovered]').click();
$('[name=areaCovered]').val(data.ads.apt_size);
/**/$('[name=streetName]').click();
$('[name=streetName]').val(data.ads.address + ', ' + data.ads.street);
/**/$('[name=city]').click();
$('[name=city]').val(data.ads.city);
selector($('[name=province]'), data.ads.region);
/**/$('label[for=amount]').next('div').find('#amount').click();
$('label[for=amount]').next('div').find('#amount').val(parseInt(data.ads.rent));
/**/$('[name=availableFrom]').click();
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10)
dd = '0' + dd;
if (mm < 10)
mm = '0' + mm;
today = mm + '/' + dd + '/' + yyyy;
$('[name=availableFrom]').val(today);
/**/if (find(data.ads.apartment_amenities, 'Furniture') + 1)
$('[name=furnished]').click();
/**/if (data.ads.pets != '0')
$('[name=petFriendly]').click();
/**/$('[name=title]').click();
$('[name=title]').val(data.ads.title);
/**/$('[name=description]').click();
$('[name=description]').val(data.ads.content);
/**/$('[name=email]').click();
$('[name=email]').val(data.ads.email);
/**/$('[name=phoneNumber]').click();
$('[name=phoneNumber]').val(data.ads.phone);
console.log(data);
uploadeImage();
});
}
function uploadeImage() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
data.append('name', 'uploadFile');
data.append('listingID', '');
data.append('uploadedFile', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.snapuprealestate.ca/listing/uploadFile', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
$('#sessionList').append(xhr.responseText);
if (++i < images.length) {
_uploadeimage(i);
} else {
console.log('end ' + i);
/**/getRecaptcha();
}
}
};
xhr.send(data);
}
});
}
function getRecaptcha() {
/**/recaptcha($('.g-recaptcha').find('iframe'), $('.g-recaptcha').attr('data-sitekey'), 'https://www.snapuprealestate.ca', function () {
$('#postBtn').click();
});
}
function myMail() {
getMail('<EMAIL>', function (data) {
var get = /(https?:\/\/w{0,3}\.?snapuprealestate\.ca\/activateAd[^\s]+)[\n\r\t\s]*<\/a/i.exec(data.replace('<wbr>', '').replace('&', '&'))[1];
window.location = get;
});
}
});<file_sep><h1 style="text-align: center;">Installation</h1>
<h3>Migrations</h3>
yii migrate --migrationPath=@backend/modules/coupons/migrations
<h3>Requirements</h3>
<strong>Kartik File Input</strong>
php composer.phar require kartik-v/yii2-widget-fileinput "@dev"
<strong>2Amigos DateTimePicker</strong>
composer require 2amigos/yii2-date-time-picker-widget:~1.0
<h3>Usage</h3>
<strong>In config/main.php add this...</strong>
'modules' => [
'coupons' => [
'class' => 'backend\modules\coupons\Coupons',
],
],
<strong>Use Coupons Module</strong>
$coupons = Yii::$app->getModule('coupons');
<strong>Getting price after entering coupon code</strong>
$price = $coupons->getPrice('COUPON CODE GOES HERE', 'PRICE GOES HERE');
<strong>Reduce coupons count after use</strong>
$coupons->reduceCouponCount('COUPON CODE GOES HERE');
<file_sep>//https://www.rentcompass.com/list-rental-homes
//http://www.rentcompass.com/CreateAd?pl=0
//https://www.rentcompass.com/listing-complete?id=B126594
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url.indexOf('/list-rental-homes') + 1 && $('[id=ctl00_ctl00_MainPlaceholder_MainPlaceholder_PlansTable]').length == 0) {
step1();
} else if (url.indexOf('/list-rental-homes') + 1 && $('[id=ctl00_ctl00_MainPlaceholder_MainPlaceholder_PlansTable]').length > 0) {
step2();
} else if (url. indexOf('/CreateAd?pl=0') + 1) {
step3();
} else if (url.indexOf('/listing-complete') + 1) {
nextSite(true);
} else {
nextSite(false);
}
function step1() {
chrome.storage.local.get('ads', function (data) {
if (!$('#FailureText.loginError').text().length) {
/**/
$('[id=UserName]').click();
$('[id=UserName]').val(data.ads.email);
$('[id=UserName]')[0].dispatchEvent(new Event('change'));
/**/
$('[id=NewRadio]').click();
/*-->*/$('[id=form1]').find('[type=submit]').click();
}
});
}
function step2() {
chrome.storage.local.get('ads', function (data) {
/**/
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceholder_PlaceFreeButton]').click();
});
}
function step3() {
setTimeout(function () {
additionalInfo();
}, 3000);
chrome.storage.local.get('ads', function (data) {
var changed = false;
/*****CHOOSE Province*****/
if (data.ads.region == 'Prince Edward Island') {
selector($('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_Province]'), 'PEI');
} else {
selector($('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_Province]'), data.ads.region);
}
$('[id=TheMap]').bind('DOMSubtreeModified', function () {
if (!$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_City_CityTextBox]').val()) {
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_City_CityTextBox]').val(data.ads.city);
} else if (!$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_StreetName]').val()) {
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_StreetName]')[0].dispatchEvent(new Event('click'));
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_StreetName]').val(data.ads.street + ', ' + data.ads.address);
} else if (!$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_PostalCode]').val()) {
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_PostalCode]').val(data.ads.postal_code);
} else {
if (!changed) {
changed = true;
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_StreetName]')[0].dispatchEvent(new Event('change'));
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_PostalCode]')[0].dispatchEvent(new Event('change'));
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_City_CityTextBox]')[0].dispatchEvent(new Event('change'));
}
}
});
});
}
function additionalInfo() {
addFeatures();
contactInfo();
registrInfo();
addPhoto();
chrome.storage.local.get('ads', function (data) {
/**/
$('[name*=PriceTextBox]').click();
$('[name*=PriceTextBox]').val(data.ads.rent);
/**/
$('[name*=BedroomsTextBox]').click();
$('[name*=BedroomsTextBox]').val(data.ads.bedroom);
/**/
$('[name*=BathroomsTextBox]').click();
$('[name*=BathroomsTextBox]').val(data.ads.bathroom);
/**/
$('[name*=AvailRadio][value="2"]').click();
var dateArray = /(\d+)-(\d+)-(\d+)/.exec(data.ads.available_date);
var date = dateArray[3] + '/' + dateArray[2] + '/' + dateArray[1];
/**/
$('[name*=Cal]').click();
$('[name*=Cal]').val(date);
/********CHOOSE HOUSE TYPE************/
switch (data.ads.house_type) {
case 'Studio':
selector($('[name="ctl00$ctl00$MainPlaceholder$MainPlaceHolder$PropertyType"]'), 'Room');
break;
case 'Commercial':
selector($('[name="ctl00$ctl00$MainPlaceholder$MainPlaceHolder$PropertyType"]'), 'Shared');
break;
default:
selector($('[name="ctl00$ctl00$MainPlaceholder$MainPlaceHolder$PropertyType"]'), data.ads.house_type);
}
/**/
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_DescriptionTextBox]').addClass('toDelete');
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_DescriptionTextBox]').parent('div').append('<textarea name="ctl00$ctl00$MainPlaceholder$MainPlaceHolder$DescriptionTextBox" id="ctl00_ctl00_MainPlaceholder_MainPlaceHolder_DescriptionTextBox"></textarea>')
$('.toDelete').remove();
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_DescriptionTextBox]').val(data.ads.content);
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_DescriptionTextBox]')[0].dispatchEvent(new Event('change'));
for (var i = 0; i < data.ads.content.length; i++) {
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_DescriptionTextBox]')[0].dispatchEvent(new Event('keyup'));
}
});
}
function addFeatures() {
chrome.storage.local.get('ads', function (data) {
if (data.ads.pets == '1') {
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_PetFriendlyCB]').click();
}
for (var key in data.ads.apartment_amenities) {
switch (data.ads.apartment_amenities[key]) {
case "Furniture":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_FurnishedCB]').click();
break;
case "A/C":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HasAcCB]').click();
break;
case "Balcony":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HasBalconyCB]').click();
break;
case "Laundry":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HasLaundryCB]').click();
break;
case "Dishwasher":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_DishwasherCB]').click();
break;
case "Locker":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_LockerCB]').click();
break;
case "Tennis":
case "Racquet Court":
if (!$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HasTennisCB]').hasClass('clicked')) {
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HasTennisCB]').click();
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HasTennisCB]').addClass('clicked');
}
break;
case "Pool":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HasPool]').click();
break;
case "Utilities Included":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HydroIncludedCB]').click();
break;
case "Fireplace":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HasFireplaceCB]').click();
break;
case "Yard":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HasYardCB]').click();
break;
case "Near Subway":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_NearSubwayCB]').click();
break;
case "Gym":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_GymCB]').click();
break;
case "Virtual golf":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HasGolfCB]').click();
break;
case "Wheelchair accessible":
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_HandicapCB]').click();
break;
}
}
});
return true;
}
function contactInfo() {
chrome.storage.local.get('ads', function (data) {
/**/
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_ContactName]').click();
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_ContactName]').val(data.ads.name);
/**/
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_ContactPhone]').click();
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_ContactPhone]').val(data.ads.phone);
/**/
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_EmailRadio_0]').click();
});
return true;
}
function registrInfo() {
chrome.storage.local.get('ads', function (data) {
/**/
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_Password]').click();
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_Password]').val(data.ads.pass);
/**/
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_Password2]').click();
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_Password2]').val(data.ads.pass);
/**/
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_ContactsCheckBox]').click();
/**/
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_FullNameTextBox]').click();
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_FullNameTextBox]').val(data.ads.name + ' ' + data.ads.l_name);
/**/
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_PhoneTextBox]').click();
$('[id=ctl00_ctl00_MainPlaceholder_MainPlaceHolder_PhoneTextBox]').val(data.ads.phone);
/**/
$('[id=TermsCB]').click();
});
}
function addPhoto() {
var img = false;
if (!img) {
img = true;
getImages(function (images) {
var i = 0;
_uplodeImage();
function _uplodeImage() {
var data = new FormData();
var imageParent = $('#ctl00_ctl00_MainPlaceholder_MainPlaceHolder_PhotoUpload' + (i + 1) + '_Root');
data.append('type', 'unit');
data.append('Filedata', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.rentcompass.com/upload.aspx', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
imageParent.find('.photoId').val(xhr.responseText);
imageParent.find('.uploadImage').attr('src', ('ImageHandler.ashx?tid=' + xhr.responseText));
i++;
if ([i] in images && i <= 10) {
_uplodeImage();
} else {
window.setTimeout(function () {
$('[name=aspnetForm]').find('[type=submit]').click();
}, 3000);
}
}
};
xhr.send(data);
}
});
}
}
});
<file_sep>//https://www.kangalou.com/en/member/create-owner-account/
//https://www.kangalou.com/en/member/creation-success/YWRzLnN1Ym1pdGVyNEBnbWFpbC5jb20%3D/
//https://management.kangalou.com/en/member/informations/
//https://management.kangalou.com/en/building/details/
//https://management.kangalou.com/en/appartment/details/
//https://management.kangalou.com/en/building/dashboard/10901/
/* global chrome */
jQuery(document).ready(function (data) {
/******THIS SITE WORKED ONLY FOR Quebec region*******/
chrome.storage.local.get('ads', function (data) {
if (data.ads.region != 'Quebec') {
nextSite(false);
}
});
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'https://www.kangalou.com/en/member/create-owner-account') {
registration();
} else if (url.indexOf('creation-success') + 1) {
getMail('<EMAIL>', function () {
var pattern = /(https?:\/\/.*?confirm[^\s\n\r\t]+)/im;
var forClick = pattern.exec($('#gh-mail-respons').html())[1].replace('&', '&').replace('®', '®');
window.location.href = forClick;
}, 30000);
} else if (url == 'https://management.kangalou.com/en/member/informations' && $(".alert-success").length == 0) {
addUserInfo();
} else if (url == 'https://management.kangalou.com/en/member/informations' && $(".alert-success").length > 0) {
window.location.href = 'https://management.kangalou.com/en/building/details/';
} else if (url.indexOf('kangalou.com/en/building/details') + 1 && $("[name=title]").length > 0) {
addBuildingInfo();
}else if(url == 'https://management.kangalou.com/en/appartment/details'){
addUnit();
}else if(url.indexOf('dashboard') + 1 && $('.btn__group').length > 0){
nextSite(true);
} else {
nextSite(false);
}
function registration() {
chrome.storage.local.get('ads', function (data) {
/**/ $("[id=lastname]").click();
$("[id=lastname]").val(data.ads.l_name);
// $('[name=type_id]').parent()[0].dispatchEvent(new Event('click'));
/**/ $("[id=firstname]").click();
$("[id=firstname]").val(data.ads.name);
/**/ $("[id=email]").click();
$("[id=email]").val(data.ads.email);
/**/ $("[id=password-proprio]").click();
$("[id=password-proprio]").val(data.ads.pass);
/**/ $("[id=password-confirm]").click();
$("[id=password-confirm]").val(data.ads.pass);
/**/ $("[id=terms]").click();
/*-->*/$('[id=form2]').find('[type=submit]').click();
});
}
function addUserInfo() {
chrome.storage.local.get('ads', function (data) {
/**/ $("[name=phone]").click();
$("[name=phone]").val(data.ads.phone);
// $('[name=phone]')[0].dispatchEvent(new Event('click'));
/**/ $("[id=chkPhoneListing]").click();
$('#sexe').show();
selector($('#sexe'), data.ads.gender);
/*****OPEN ALL SECTIONS*******/
/**/ $(".panel--large a span").click();
/**/ $("form").find('.js-button-confirm-before-save').click();
});
}
function addBuildingInfo() {
getCity();
chrome.storage.local.get('ads', function (data) {
/****SHOW ALL SELECTES*******/
$('select').show();
/**/ $("[name=title]").click();
$("[name=title]").val(data.ads.address + ' ' + data.ads.street);
switch (data.ads.house_type) {
case 'Apartment':
selector($('#type'), 'Condominium');
break;
case 'House':
selector($('#type'), 'Single family');
break;
case 'Studio':
case 'Commercial':
selector($('#type'), 'Commercial');
break;
}
/**/ $("[id=unitcount]").click();
$("[id=unitcount]").val(data.ads.bedroom);
/**/ $("[id=floorcount]").click();
$("[id=floorcount]").val(data.ads.floor_count);
/**/ $("[id=zipcode]").click();
$("[id=zipcode]").val(data.ads.postal_code);
/**/ $("[id=zipcode]").click();
$("[id=zipcode]").val(data.ads.postal_code);
$('[name=zipcode]')[0].dispatchEvent(new Event('change'));
/**/ $("[id=number]").click();
$("[id=number]").val(data.ads.address);
/**/ $("[id=street]").click();
$("[id=street]").val(data.ads.street);
});
}
function getCity() {
chrome.storage.local.get('ads', function (data) {
var i = 1;
$('#cities').bind('DOMSubtreeModified', function () {
var length = $('[name=region]').find('option').length;
if ($('[name=cities]').find('option').length > 2) {
selector($('[name=cities]'), data.ads.city);
if (!($('[name=cities]').val() > 0) && ++i < length) {
setCity();
} else if ($('[name=cities]').val() > 0) {
nextStep();
}
}
});
setCity();
function setCity() {
var optionVal = $($('[name=region]').find('option')[i]).val();
$('[name=cities]').html('');
$('[name=region]').val(optionVal);
$('[name=region]')[0].dispatchEvent(new Event('change'));
}
});
}
function nextStep() {
addDetails();
uploadeImage();
}
function addDetails() {
chrome.storage.local.get('ads', function (data) {
for (var key in data.ads.apartment_amenities) {
switch (data.ads.apartment_amenities[key]) {
case 'Elevator':
$("[id=criteria-elevator]").click();
break;
case 'Gym':
$("[id=criteria-gym-1]").click();
$("[id=criteria-gym-2]").click();
break;
case 'Sauna':
$("[id=criteria-sauna]").click();
break;
case 'Laundry':
$("[id=criteria-laundromat-1]").click();
break;
case 'Shared Room':
$("[id=criteria-shared-rooms]").click();
break;
case 'Indoor Parking':
$("[id=criteria-interior]").click();
break;
case 'outdoor Parking':
$("[id=criteria-exterior]").click();
break;
case 'Pool':
$("[id=criteria-pool]").click();
break;
case 'Tennis':
$("[id=criteria-tennis]").click();
break;
case 'Security System':
$("[id=criteria-alarm-system-cameras]").click();
break;
}
}
});
}
function uploadeImage() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
data.append('files[]', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://management.kangalou.com/en/photo/ajax/upload-photo/', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var file = JSON.parse(xhr.responseText).files[0];
var html = `<input type="hidden" name="photoupload[newuploads][id][]" data-filename="" data-fileurl="" value="">`
+ `<input type="hidden" class="position" name="photoupload[newuploads][position][]" value="${++i}">`
+ `<input type="hidden" name="photoupload[newuploads][file][]" value="${file.url}">`
+ `<input type="hidden" name="photoupload[newuploads][name][]" value="${file.name}">`;
$('.uploaded__photos').append(html);
if (i < images.length) {
_uploadeimage(i);
} else {
window.setTimeout(function () {
submit();
}, 250);
}
}
};
xhr.send(data);
}
});
}
function submit() {
var inputs = $('form.js-confirm-before-exit').find('input');
var textareas = $('form.js-confirm-before-exit').find('textarea');
var selects = $('form.js-confirm-before-exit').find('select');
var data = new FormData();
$.each(inputs, function () {
data.append($(this).attr('name'), $(this).val());
});
$.each(textareas, function () {
data.append($(this).attr('name'), $(this).val());
});
$.each(selects, function () {
data.append($(this).attr('name'), $(this).val());
});
var xhr = new XMLHttpRequest();
xhr.open('post', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var innerBody = xhr.responseText.replace(/([\n\r]|.)+<body[^>]+>/, '').replace(/<\/body[^>]*>([\n\r]|.)+/, '');
$('body').html(innerBody);
window.location.href = 'https://management.kangalou.com/en/appartment/details/';
}
};
xhr.send(data);
}
function addUnit() {
addApartmentAmenities();
chrome.storage.local.get('ads', function (data) {
/**/ $("[type=radio][name=building]")[0].click();
setTimeout(function () {
/**/ $("[type=radio][name=address]")[0].click();
/**/ $("[name=doornumber]").click();
$("[name=doornumber]").val(data.ads.street);
/******CHOOSE HOUSE TYPE*********/
selector($("[name=type]"), data.ads.house_type);
$("[id=type_chosen]").find('span').text(data.ads.house_type);
/*******CHOOSE ROOMS*******/
if(parseInt(data.ads.bedroom) + parseInt(data.ads.bathroom) >= 6){
selector($("[name=appartmentsize]"), '6');
$("[id=appartmentsize_chosen]").find('span').text('6 ½ +')
}else {
selector($("[name=appartmentsize]"), String(parseInt(data.ads.bedroom) + parseInt(data.ads.bathroom)));
$("[id=appartmentsize_chosen]").find('span').text(parseInt(data.ads.bedroom) + parseInt(data.ads.bathroom) + ' ½ +')
}
if(data.ads.bedroom >= 9){
selector($("[name=bedroomcount]"), '9');
$("[id=bedroomcount_chosen]").find('span').text('9 ½ +')
}else {
selector($("[name=bedroomcount]"), data.ads.bedroom );
$("[id=bedroomcount_chosen]").find('span').text(data.ads.bedroom + ' ½ +')
}
if(data.ads.bathroom >= 5){
selector($("[name=bathroomcount]"), '5');
$("[id=bathroomcount_chosen]").find('span').text('5 ½ +')
}else {
selector($("[name=bathroomcount]"), data.ads.bathroom );
$("[id=bathroomcount_chosen]").find('span').text(data.ads.bathroom + ' ½ +')
}
/**/ $("[name=size]").click();
$("[name=size]").val(data.ads.apt_size);
$("[name=size_type][value='m']").click();
/**/ $("[name=monthlycost]").click();
$("[name=monthlycost]").val(data.ads.rent);
selector($("[name=rentfrequency]"), 'Every month');
$("[id=rentfrequency_chosen]").find('span').text('Every month');
/**/ $("[name=availability]").click();
$("[name=availability]").val(data.ads.available_date);
/**/ $("[href*=description-en_CA]")[0].click();
/**/ $("[name*=en_CA]").click();
$("[name*=en_CA]").val(data.ads.content);
/********FINISH*********/
setTimeout(function () {
$(".form--aligned").find('[type=submit]').click();
}, 3000);
}, 3000);
});
}
function addApartmentAmenities(){
chrome.storage.local.get('ads', function (data) {
$('[id*=collapse]').addClass('in');
if(data.ads.pets == '1'){
$('[id=criteria-cat-allowed]').click();
$('[id=criteria-dog-allowed]').click();
$('[id=criteria-small-dog-allowed]').click();
}else{
$('[id=criteria-no-animals-allowed]').click();
}
if(data.ads.parking_count > 0){
$('[id=criteria-parking]').click();
}
for(var key in data.ads.apartment_amenities){
switch (data.ads.apartment_amenities[key]){
case 'Air Conditioning':
$('[id=criteria-air-conditioning]').click();
break;
case 'Hot Water':
$('[id=criteria-hot-water]').click();
break;
case 'Furniture':
$('[id=criteria-furnished]').click();
break;
case 'Heating':
$('[id=criteria-heated]').click();
break;
case 'Fridge':
$('[id=criteria-fridge]').click();
break;
case 'Washer':
$('[id=criteria-washer]').click();
break;
case 'Dishwasher':
$('[id=criteria-dishwasher]').click();
break;
case 'Stove':
$('[id=criteria-stove]').click();
break;
case 'Dryer':
$('[id=criteria-dryer]').click();
break;
case 'Washer/Dryer':
$('[id=criteria-washer-and-dryer-connectors]').click();
break;
case 'Storage Locker':
case 'Storage/Locker Space':
$('[id=criteria-storage]').prop('checked', true);
$('[id=criteria-storage-1]').prop('checked', true);
break;
case 'Fireplace':
$('[id=criteria-fireplace]').click();
break;
case 'Carpet':
$('[id=criteria-carpet]').click();
break;
case 'Maintenance On Site':
$('[id=criteria-access-to-site]').click();
break;
case 'Landscaped/Fenced Yard':
$('[id=criteria-private-yard]').click();
break;
case 'Terrace':
$('[id=criteria-terrace]').click();
break;
case 'Elevator':
$('[id=criteria-elevator-1]').click();
break;
case 'Wheelchair accessible':
$('[id=criteria-wheelchair-ramp]').click();
break;
case 'Meals Included':
$('[id=criteria-meal-service]').click();
break;
case 'Internet Ready':
$('[id=criteria-internet]').click();
break;
case 'Satellite Dish':
$('[id=criteria-satellite-tv]').click();
break;
case 'Cable(TV)':
$('[id=criteria-tv-cable]').click();
break;
case 'Balcony':
$('[id=criteria-balcony]').click();
break;
case 'Yard':
$('[id=criteria-yard-accessible]').click();
break;
case 'Renovated':
$('[id=criteria-renovated]').click();
break;
case 'Close to Transit':
$('[id=criteria-public-transit]').click();
break;
case 'Hardwood Floors':
$('[id=criteria-wood-floors]').click();
break;
}
}
});
}
});
<file_sep><?php
namespace frontend\controllers;
use common\models\Translations;
use Yii;
use yii\data\Pagination;
use yii\web\Controller;
use common\models\ListingSection;
class ListingSectionController extends Controller
{
public $layout = 'aufpostingMain';
public function actions()
{
Yii::$app->language = isset($_COOKIE['lang']) ? $_COOKIE['lang'] : 'en-US';
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
if(isset($_COOKIE['lang']) && ($_COOKIE['lang'] == 'en-US')){
$blog = ListingSection::find()->where(['is_active' => 1])->orderBy('listing_section.created_at desc');
}else{
$blog = ListingSection::find()
->where(['listing_section.is_active' => 1])
->innerJoin(Translations::tableName(), 'translations.parent_id=listing_section.id')
->andWhere(['translations.parent_tbl' => 'listing'])
->select('listing_section.created_at,listing_section.keywords, listing_section.description, listing_section.slug,translations.title,translations.short_text,translations.content')->orderBy('listing_section.created_at desc');
}
$pagination = new Pagination([
'defaultPageSize' => 10,
'totalCount' => $blog->count(),
]);
$blogContent = $blog->offset($pagination->offset)->limit($pagination->limit)->asArray()->all() ;
return $this->render('index', [
'pagination' => $pagination,
'blogContent' => $blogContent
]);
}
public function actionListing()
{
$getRequest = Yii::$app->request->get();
if(isset($_COOKIE['lang']) && ($_COOKIE['lang'] == 'en-US')){
$blogposts = ListingSection::find()
->where(['is_active' => 1])
->asArray()
->all();
if (isset($getRequest['slug']) && $getRequest['slug'] !== '') {
$thread = ListingSection::find()->where([
'is_active' => 1,
'slug' => $getRequest['slug']
])->asArray()->one();
if($thread == null){
$this->redirect('main/error');
}
} else {
return $this->redirect('index');
}
}else{
$blogposts = ListingSection::find()
->where(['listing_section.is_active' => 1])
->innerJoin(Translations::tableName(), 'translations.parent_id=listing_section.id')
->andWhere(['translations.parent_tbl' => 'listing'])
->select('listing_section.slug, translations.title')
->asArray()
->all();
if (isset($getRequest['slug']) && $getRequest['slug'] !== '') {
$thread = ListingSection::find()
->where([
'listing_section.is_active' => 1,
'listing_section.slug' => $getRequest['slug']
])
->innerJoin(Translations::tableName(), 'translations.parent_id=listing_section.id')
->andWhere(['translations.parent_tbl' => 'listing'])
->select('listing_section.keywords, listing_section.description, listing_section.files, listing_section.slug, translations.title,translations.short_text,translations.content,')
->asArray()
->one();
if($thread == null){
$this->redirect('main/error');
}
} else {
return $this->redirect('index');
}
}
return $this->render('listing', [
'thread' => $thread,
'blogposts' => $blogposts,
]);
}
}<file_sep>//http://posting.montreal.backpage.com/online/classifieds/PostAdPPI.html/ymx/montreal.backpage.com/?serverName=montreal.backpage.com&superRegion=Montreal&u=ymx§ion=4376&category=4416
//TODO step2 chi erta
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url.indexOf('superRegion=') + 1) {
step1();
}
// else if(url.indexOf('ad-submitted') ){
//
// // getMail('<EMAIL>', function () {
// // var pattern = /(https?:\/\/w{0,3}\.?doodloo.com\/activate-ad.php[^\s\r\n\t]+)/igm;
// // var forClick = pattern.exec($('#gh-mail-respons').html())[1].replace(/&/g, '&').replace(/®/g, '®');
// //
// // window.location.href = forClick;
// // }, 300, true);
// }else {
//
// // nextSite(false);
// }
function step1() {
//TODO add photo
addPhoto();
chrome.storage.local.get('ads', function (data) {
console.log(data.ads);
/**/
$("[name=title]").click();
$('[name=title]').val(data.ads.title);
// $('[name=title]').parent()[0].dispatchEvent(new Event('click'));
/**/
$("[name=ad]").click();
$('[name=ad]').val(data.ads.content);
exchange(data.ads.rent, function (currencyForCanada) {
/**/
$("[name=price]").click();
$('[name=price]').val(currencyForCanada);
});
/**/
$("[name=regionOther]").click();
$('[name=regionOther]').val(data.ads.region);
if (data.ads.bedroom >= 8) {
selector($("[name=bedrooms]"), '8');
} else {
selector($("[name=bedrooms]"), data.ads.bedroom);
}
if (data.ads.pets == '1') {
$("[name=petsAccepted][value='Cats Ok']").click();
$("[name=petsAccepted][value='Dogs Ok']").click();
}
/**/
$("[name=mapAddress]").click();
$('[name=mapAddress]').val(data.ads.street);
/**/
$("[name=mapZip]").click();
$('[name=mapZip]').val(data.ads.postal_code);
/**/
$("[name=email]").click();
$('[name=email]').val(data.ads.email);
/**/
$("[name=emailConfirm]").click();
$('[name=emailConfirm]').val(data.ads.email);
/**/
$("[name=allowReplies][value='Anonymous']").prop('checked', true);
/**/
$("[name=mobileNumber]").click();
$('[name=mobileNumber]').val(data.ads.phone);
selector($("[name=mobileNumberCountry]"), 'Canada');
/**/
$("[name=showAdLinks]").prop('checked', true);
/**/
$("[name=moveAdToTop]").prop('checked', false);
/**/
$("[name=autoRepostAd]").prop('checked', false);
/**/
$("[name=sponsorAd]").prop('checked', false);
console.log($('[name=f]').find('[type=submit]'));
// /*-->*/$('[name=f]').find('[type=submit]').click();
// $('[name=f]')[0].dispatchEvent(new Event('click'));
});
}
});
function addPhoto() {
chrome.storage.local.get('ads', function (data) {
});
}
<file_sep>//http://www.doodloo.com/additem.php?catId=13&subID=96
//http://www.doodloo.com/ad-submitted.php?pid=14514&view=1&id=0
//http://www.doodloo.com/activate-ad.php?id=14755®ion=11&key=4620699
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'http://www.doodloo.com/additem.php?catId=13&subID=96') {
addDetails();
}else if(url.indexOf('ad-submitted') + 1){
getMail('<EMAIL>', function () {
var pattern = /(https?:\/\/w{0,3}\.?doodloo.com\/activate-ad.php[^\s\r\n\t]+)/igm;
var forClick = pattern.exec($('#gh-mail-respons').html())[1].replace(/&/g, '&').replace(/®/g, '®');
window.location.href = forClick;
}, 300, true);
}else if(url.indexOf('/activate-ad.php')){
nextSite(true);
}else {
nextSite(false);
}
function addDetails() {
addPhoto();
chrome.storage.local.get('ads', function (data) {
/**/ $("[name=type_id][value='1']").parent().click();
$('[name=type_id]').parent()[0].dispatchEvent(new Event('click'));
/**/ $("[name=selectTransactionID][value='4']").parent().click();
$("[name=selectTransactionID][value='4']").parent()[0].dispatchEvent(new Event('click'));
/**/ $('[id=textTitle]').click();
$('[id=textTitle]').val(data.ads.title);
/**/ $('[id=textPhone]').click();
$('[id=textPhone]').val(data.ads.phone);
/**/ $('[id=textZip]').click();
$('[id=textZip]').val(data.ads.postal_code);
/**/ $('[id=textEmail]').click();
$('[id=textEmail]').val(data.ads.email);
/**/ $('[id=editor1]').click();
$('[id=editor1]').val(data.ads.content);
});
}
function addPhoto() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
$.each($('[name=formPlaceAd]').find('input'), function () {
if (($(this).attr('type') != 'checkbox' && $(this).attr('type') != 'radio' && $(this).attr('type') != 'file') || ($(this).attr('type') == 'checkbox' && $(this).is(':checked')) || ($(this).attr('type') == 'radio' && $(this).is(':checked'))){
data.append($(this).attr('name'), $(this).val());
}
});
$.each($('[name=formPlaceAd]').find('textarea'), function () {
data.append($(this).attr('name'), $(this).val());
});
$.each($('[name=formPlaceAd]').find('select'), function () {
data.append($(this).attr('name'), $(this).val());
});
data.append('files[]', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', '//www.doodloo.com/server/php/', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var response = JSON.parse(xhr.responseText);
$('#files').append(`<div class="col-xs-3">
<div class="thumbnail">
<label>Default <input type="radio" name="primary" value="${response.files[0].name}"></label><br>
<div class="thumb-wrapper"><img src="${response.files[0].thumbnailUrl}" width="60" height="60" ></div><br>
<input type="hidden" name="images[]" value="${response.files[0].name}">
<button type="button" class="btn btn-primary" data-image="${response.files[0].name}">Delete</button>
</div>
</div>`);
if (++i < images.length) {
_uploadeimage(i);
}else{
setTimeout(function () {
/*******FINISH*******/
/*-->*/$('[id=formPlaceAd]').find('[type=submit]').click();
}, 3000)
}
}
};
xhr.send(data);
}
});
}
});
<file_sep>//http://www.rentmtl.com/editRegistration.do?action=Create
//http://www.rentmtl.com/prepareMap.do
//http://www.rentmtl.com/logon.jsp
//http://www.rentmtl.com/account.jsp
//http://www.rentmtl.com/editAd.do?action=Create&username=
//http://www.rentmtl.com/account.jsp
/* global chrome */
jQuery(document).ready(function ($) {
chrome.storage.local.get('ads', function (data) {
/*******THIS SITE ONLY FOR Montreal city ******/
if (data.ads.city != 'Montreal') {
nextSite(false);
}
});
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'http://www.rentmtl.com/editRegistration.do?action=Create') {
registration();
}else if(url == 'http://www.rentmtl.com/prepareMap.do'){
window.location.href = 'http://www.rentmtl.com/logon.jsp';
}else if(url == 'http://www.rentmtl.com/logon.jsp'){
login();
}else if(url == 'http://www.rentmtl.com/account.jsp' && $("[class=enabled]").length == 0){
window.location.href = 'http://www.rentmtl.com/editAd.do?action=Create&username=';
}else if(url.indexOf('Create&username') + 1 ){
addDetails();
}else if(url == 'http://www.rentmtl.com/account.jsp' && $("[class=enabled]").length > 0){
chrome.storage.local.get('ads', function (data) {
var login = data.ads.login.replace(/\W+/g, '');
var pass = <PASSWORD>;
nextSite({'login':login, 'pass': pass});
});
}else {
nextSite(false);
}
function registration() {
chrome.storage.local.get('ads', function (data) {
var login = data.ads.login.replace(/\W+/g, '');
var pass = <PASSWORD>;
/**/ $("[name=username]").click();
$("[name=username]").val(login);
// $('[name=username]')[0].dispatchEvent(new Event('click'));
/**/ $("[name=password]").click();
/**/ $("[name=password]").val(pass);
/**/ $("[name=password2]").click();
$("[name=password2]").val(pass);
/**/ $("[name=fullName]").click();
$("[name=fullName]").val(data.ads.name + ' ' + data.ads.l_name);
/**/ $("[name=email]").click();
$("[name=email]").val(data.ads.email);
/**/ $("[name=phone]").click();
$("[name=phone]").val(data.ads.phone);
$("[name=language]").val('en');
/*-->*/$('[name=registrationForm]').find('[type=submit][name!=doneButton]').click();
});
}
function login() {
chrome.storage.local.get('ads', function (data) {
var login = data.ads.login.replace(/\W+/g, '');
var pass = <PASSWORD>;
/**/ $("[name=username]").click();
$("[name=username]").val(login);
/**/ $("[name=password]").click();
$("[name=password]").val(pass);
/*-->*/$('[name=logonForm]').find('[type=submit]').click();
});
}
function addDetails() {
chrome.storage.local.get('ads', function (data) {
/**/ $("[name=type][value='RN00030001']").click();
$("[name=type][value='RN00030001']")[0].dispatchEvent(new Event('click'));
/**/ $("[name=name]").click();
$("[name=name]").val(data.ads.title);
selector($("[name=area]"), data.ads.zone);
$("[name=priceValue]").click();
$("[name=priceValue]").val(data.ads.rent);
$("[name=text]").click();
$("[name=text]").val(data.ads.content + '\n phone: ' + data.ads.phone + '\n email: ' + data.ads.email);
$("[name=allIncl]").click();
for(var key in data.ads.apartment_amenities){
switch (data.ads.apartment_amenities[key]){
case 'Indoor Parking':
case 'outdoor Parking':
$("[name=parking]").prop('checked', true);
break;
}
}
$("[name=postalCode]").click();
$("[name=postalCode]").val(data.ads.postal_code);
/****FINISHED*******/
/*-->*/$('[type=submit][name=saveAd]').click();
});
}
});<file_sep><?php
namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
/**
* This is the model class for table "payment_details".
*
* @property integer $id
* @property string $name
* @property string $price
* @property string $currency
* @property string $shipping
* @property string $tax
* @property string $payment_description
* @property string $content
* @property string $content_translation
* @property string $created_at
* @property string $updated_at
*/
class PaymentDetails extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'payment_details';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => new Expression('NOW()'),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['price', 'shipping', 'tax'], 'number'],
[['content', 'content_translation'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['name', 'currency'], 'string', 'max' => 255],
[['payment_description'], 'string', 'max' => 500],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'price' => Yii::t('app', 'Price'),
'currency' => Yii::t('app', 'Currency'),
'shipping' => Yii::t('app', 'Shipping'),
'tax' => Yii::t('app', 'Tax'),
'payment_description' => Yii::t('app', 'Payment Description'),
'content' => Yii::t('app', 'Content'),
'content_translation' => Yii::t('app', 'Content Translation'),
'created_at' => Yii::t('app', 'Created At'),
'updated_at' => Yii::t('app', 'Updated At'),
];
}
}
<file_sep><?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\SubmitData;
/**
* SubmitDataControl represents the model behind the search form about `common\models\SubmitData`.
*/
class SubmitDataControl extends SubmitData
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['published', 'login', 'pass', 'title', 'content', 'name', 'l_name', 'gender', 'phone', 'email', 'contact_time', 'city', 'postal_code', 'street', 'address', 'apartment_ids', 'apt_size', 'bedroom', 'bathroom', 'available_date', 'pets', 'parking_price', 'image_url', 'contact_person', 'zone', 'region', 'region_iso'], 'safe'],
[['id', 'house_type_id', 'parking_count','floor_count', 'lease_length', 'package_id', 'package_duration_id'], 'integer'],
[['rent'], 'number'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = SubmitData::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'rent' => $this->rent,
'house_type_id' => $this->house_type_id,
'available_date' => $this->available_date,
'parking_count' => $this->parking_count,
'lease_length' => $this->lease_length,
'package_id' => $this->package_id,
'package_duration_id' => $this->package_duration_id,
]);
$query->andFilterWhere(['like', 'published', $this->published])
->andFilterWhere(['like', 'login', $this->login])
->andFilterWhere(['like', 'pass', $this->pass])
->andFilterWhere(['like', 'title', $this->title])
->andFilterWhere(['like', 'content', $this->content])
->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'l_name', $this->l_name])
->andFilterWhere(['like', 'gender', $this->gender])
->andFilterWhere(['like', 'phone', $this->phone])
->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'contact_time', $this->contact_time])
->andFilterWhere(['like', 'city', $this->city])
->andFilterWhere(['like', 'postal_code', $this->postal_code])
->andFilterWhere(['like', 'street', $this->street])
->andFilterWhere(['like', 'address', $this->address])
->andFilterWhere(['like', 'apartment_ids', $this->apartment_ids])
->andFilterWhere(['like', 'apt_size', $this->apt_size])
->andFilterWhere(['like', 'bedroom', $this->bedroom])
->andFilterWhere(['like', 'bathroom', $this->bathroom])
->andFilterWhere(['like', 'pets', $this->pets])
->andFilterWhere(['like', 'parking_price', $this->parking_price])
->andFilterWhere(['like', 'image_url', $this->image_url])
->andFilterWhere(['like', 'contact_person', $this->contact_person])
->andFilterWhere(['like', 'zone', $this->zone])
->andFilterWhere(['like', 'region', $this->region])
->andFilterWhere(['like', 'region_iso', $this->region_iso])
->andFilterWhere(['like', 'floor_count', $this->floor_count]);
return $dataProvider;
}
/**
* @return $this
*/
public static function getSubmitData()
{
$model = SubmitData::find()
->where(['published' => '0'])
->orderBy('id desc')
->asArray()
->one();
return $model;
}
/**
* @return $this
*/
public static function getPremiumSubmitData()
{
$model = SubmitData::find()
->where(['published' => '1'])
->andWhere(['package_id' =>'2'])
->orderBy('id desc')
->asArray()
->all();
return $model;
}
}
<file_sep><?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use frontend\assets\AppAsset;
use common\widgets\Alert;
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="manifest" href="<?= Yii::$app->homeUrl?>manifest.json">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
<link href="<?php echo Yii::$app->homeUrl; ?>/css/fancybox/jquery.fancybox.css" rel="stylesheet">
<script> var baseUrl = "<?= Yii::$app->homeUrl ?>"</script>
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
<script type='text/javascript' src='https://ssl.p.jwpcdn.com/6/6/jwplayer.js'></script>
</head>
<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<?php $this->beginBody() ?>
<div class="container-fluid">
<?= $this->render("../partials/header.php") ?>
<section class="paddingT">
<div class="container">
<div class="row">
<div class="col-xs-12">
<?= Breadcrumbs::widget(
[
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]
) ?>
</div>
</div>
</div>
</section>
<?= $content ?>
<?= $this->render("../partials/footer.php") ?>
</div>
<?php $this->endBody() ?>
<script src="<?php echo Yii::$app->homeUrl; ?>/js/fancybox/jquery.fancybox.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.innr-img img').each(function() {
$(this).wrap("<a class='single_image' href='" + this.src + "'/>");
});
$(".single_image").fancybox();
});
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-100485100-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
<?php $this->endPage() ?>
<!----menu-slider------>
<script src="js/slick-min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/slick.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.testimonial-slider').slick({
centerMode: true,
centerPadding: '0px',
slidesToShow: 1,
autoplay: false,
arrows: true,
dots:false,
responsive: [
{
breakpoint: 1024,
settings: {
arrows: false,
centerMode: true,
centerPadding: '0px',
slidesToShow: 1
}
},
{
breakpoint: 800,
settings: {
arrows: false,
centerMode: true,
centerPadding: '0px',
slidesToShow: 1
}
}
]
});
$('.client-slider').slick({
centerMode: true,
centerPadding: '0px',
slidesToShow: 3,
autoplay: true,
arrows: false,
dots:false,
responsive: [
{
breakpoint: 1024,
settings: {
arrows: false,
centerMode: true,
centerPadding: '0px',
slidesToShow: 3
}
},
{
breakpoint: 800,
settings: {
arrows: false,
centerMode: true,
centerPadding: '0px',
slidesToShow: 1
}
}
]
});
});
</script>
<script type="text/javascript">
jwplayer("player").setup({
playlist: [{
sources: [{
file: "../frontend/web/video/video.mp4"
}]
}],
width: 500,
height:350,
autostart: 'true',
stretching: "fill",
});
jwplayer().onComplete(function() {
var el = document.createElement("div");
var el2 = document.createElement("div");
var el3 = document.createElement("div");
var el4 = document.createElement("div");
var txt = document.createElement('a');
if (jwplayer().getRenderingMode() == "html5"){
var theBody = document.getElementById(player.id);
} else {
var theBody = document.getElementById(player.id+"_wrapper");
}
var playerWidthPX2 = theBody.style.width;
var playerWidthPX = parseFloat(playerWidthPX2);
var playerHeightPX2 = theBody.style.height;
var playerHeightPX = parseFloat(playerHeightPX2);
el3.setAttribute('id', 'bg');
el3.style.height = playerHeightPX + "px";
el3.style.width = playerWidthPX2;
el3.style.background = "#333333";
el3.style.opacity = "0.70";
el3.style.position = "absolute";
el3.style.backgroundImage="url('')";
el.setAttribute('src', '');
if (jwplayer().getRenderingMode() == "html5"){
} else {
el3.style.top = playerHeightPX-playerHeightPX+"px";
}
el3.style.zIndex = "999";
el3.width = playerWidthPX;
el3.height = playerHeightPX;
el2.setAttribute('id', 'bg2');
el2.style.height = playerHeightPX + "px";
el2.style.width = playerWidthPX2;
el2.style.position = "absolute";
el2.style.zIndex = "999";
el2.width = playerWidthPX;
el2.height = playerHeightPX;
theBody.appendChild(el3);
theBody.appendChild(el2);
el2.style.textAlign = "center";
el2.style.left = ((playerWidthPX*2)/6) -"5" + "px";
el2.style.top = ((playerHeightPX*3)/6) -"30" + "px";
el.setAttribute('id', 'hyperlink');
el.style.height = "30px";
el.style.width = "30px";
el2.width = "30";
el2.height = "30";
el.style.position = "relative";
el.setAttribute('frameBorder', '0');
el.style.top = "11px";
el.style.left = "202px";
el.style.textAlign = "center";
el.style.marginBottom = "-16px";
el.style.marginRight = "8px";
var message = '';
txt.innerHTML = message;
txt.href = ""
txt.target = "_blank";
txt.style.textDecoration = "none";
txt.style.outline = "0";
txt.style.MozUserSelect = 'none';
txt.style.KhtmlUserSelect = 'none';
txt.style.WebkitUserSelect = 'none';
txt.style.OUserSelect = 'none';
txt.style.UserSelect = 'none';
txt.style.fontSize = "18px";
txt.style.fontWeight = "600";
txt.style.color = "#fff"
txt.style.backgroundColor = "#008080"
txt.style.textAlign = "center"
txt.style.padding = "8px 20px"
txt.style.position = "absolute";
txt.style.marginLeft = "auto";
txt.style.marginTop = "4px";
txt.style.fontFamily = "arial,_sans";
txt.setAttribute('id', 'txt');
el4.setAttribute('id', 'replay');
el4.style.height = "20px";
el4.style.width = "20px";
el4.height = "20";
el4.width = "20";
el4.style.position = "absolute";
el4.style.top = "-" + playerHeightPX/2 + "px";
el4.style.marginTop = "50px";
el4.style.left = playerWidthPX/2 + "px";
el4.style.marginLeft = "50px";
el4.style.backgroundImage="url('replay.png')";
el4.setAttribute('src', 'replay.png');
el2.appendChild(txt);
el2.appendChild(el);
el2.appendChild(el4);
el.style.backgroundImage="url('hyperlink.png')";
el.setAttribute('src', 'hyperlink.png');
el.style.cursor = "pointer";
el.style.display = "table";
el2.style.display = "table";
el3.style.display = "table";
el4.style.display = "table";
txt.style.display = "table";
el.onmouseup = function(){
window.open("../frontend/web/video/video.mp4");
}
el4.style.cursor = "pointer";
el4.onmouseup = function(){
el.style.display = "none";
el2.style.display = "none";
el3.style.display = "none";
el4.style.display = "none";
txt.style.display = "none";
jwplayer().play();
}
});
</script>
<file_sep>//http://www.city-data.com/forum/registeradv.php
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'http://www.city-data.com/forum/registeradv.php') {
registration();
} else if (url == '') {
// window.location.href = 'http://elistr.com/index.php?a=cart&action=process&main_type=classified&step=classified%3Acategory&b=232&c=terminal';
}
else {
if (url == 'http://elistr.com/index.php?a=cart&action=process&main_type=classified&step=other_details') {
//TODO UPDATE
}
// nextSite();
}
function registration() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[name=username]').click();
$('[name=username]').val(data.ads.login);
/**/ $('[name=password]').click();
$('[name=password]').val(data.ads.pass);
/**/ $('[name=passwordconfirm]').click();
$('[name=passwordconfirm]').val(data.ads.pass);
/**/ $('[name=email]').click();
$('[name=email]').val(data.ads.email);
/**/ $('[id=cb_rules_agree]').click();
/**/ $('[id=ctb_field28]').click();
$('[id=ctb_field28]').val(data.ads.postal_code);
/*-->*/$('form').find('[type=submit]').click();
});
}
});
<file_sep><?php
use yii\db\Schema;
use yii\db\Migration;
class m151218_234654_create_table extends Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%coupons}}', [
'id' => Schema::TYPE_PK,
'name' => Schema::TYPE_STRING . '(500)',
'image_url' => Schema::TYPE_STRING . '(500)',
'coupon_code' => Schema::TYPE_STRING . '(255) UNIQUE NOT NULL',
'discount_type' => "ENUM('percent', 'price') NOT NULL",
'discount_count' => Schema::TYPE_INTEGER . ' NOT NULL',
'available_coupons_count' => Schema::TYPE_INTEGER . ' NOT NULL',
'expire_at' => Schema::TYPE_TIMESTAMP,
'created_at' => Schema::TYPE_TIMESTAMP,
'updated_at' => Schema::TYPE_TIMESTAMP,
'status' => "ENUM('active', 'passive')",
], $tableOptions);
}
public function down()
{
$this->dropTable('{{%coupons}}');
}
}
<file_sep><?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\HouseType;
/**
* HouseTypeControl represents the model behind the search form about `common\models\HouseType`.
*/
class HouseTypeControl extends HouseType
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id'], 'integer'],
[['house', 'translation_fr'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = HouseType::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
]);
$query->andFilterWhere(['like', 'house', $this->house])
->andFilterWhere(['like', 'translation_fr', $this->translation_fr]);
return $dataProvider;
}
public static function getHouse($id){
$model = HouseType::find()
->select('house')
->where(['id'=>$id])
->asArray()
->one();
return $model;
}
}
<file_sep><?php
namespace common\models;
use Yii;
/**
* This is the model class for table "premium_update_stage".
*
* @property integer $id
* @property integer $stage_hour
*/
class PremiumUpdateStage extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'premium_update_stage';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['stage_hour'], 'integer'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'stage_hour' => Yii::t('app', 'Stage Hour'),
];
}
}
<file_sep>//https://www.facebook.com/login
//https://www.facebook.com/
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'https://www.facebook.com/login') {
login();
}
else if(url == 'https://www.facebook.com' || url == 'https://www.facebook.com/?sk=welcome'){
window.location.href = 'https://www.facebook.com/groups/1713784562267402/';
// nextSite(true);
}
else if(url == 'https://www.facebook.com/groups/1713784562267402'){
addDetails();
}
else {
// nextSite(false);
}
function login() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[name=email]').click();
// $('[name=email]').val(data.ads.email);
$('[name=email]').val('<EMAIL>');
$('[name=email]')[0].dispatchEvent(new Event('change'));
/**/ $('[name=pass]').click();
// $('[name=pass]').val(data.ads.pass);
$('[name=pass]').val('<PASSWORD>');
$('[name=pass]')[0].dispatchEvent(new Event('change'));
$('#login_form').find('[type=submit]').click();
console.log($('#login_form').find('[type=submit]'))
;
});
}
function addDetails() {
addPhoto();
chrome.storage.local.get('ads', function (data) {
// $("[name=selectTransactionID][value='4']").parent()[0].dispatchEvent(new Event('click'));
// $('#pagelet_group_composer').find('div').each(function () {
// );
var fullContent = data.ads.title + "\n\r" + data.ads.content + "\n\r" + "Address: " + data.ads.street + " " +
+ data.ads.address + "\n" + "Price: " + data.ads.rent + "\n" + "Email: "
+ data.ads.email + "\n" + "Phone: " + data.ads.phone;
$('[name=xhpc_message_text]').val(fullContent);
$("[name=xhpc_message_text]")[0].dispatchEvent(new Event('change'));
});
}
function addPhoto() {
// POST /v2.8/{group-id}/photos HTTP/1.1
// Host: graph.facebook.com
//
// source=%7Bimage-data%7D
FB.api(
"/{group-id}/photos",
"POST",
{
"source": "{image-data}"
},
function (response) {
if (response && !response.error) {
alert(1111)
/* handle the result */
}
}
);
// getImages(function (images) {
// // _uploadeimage(0);
// // function _uploadeimage(i = 0) {
// // var data = new FormData();
// //
// // $.each($('[name=formPlaceAd]').find('input'), function () {
// // if (($(this).attr('type') != 'checkbox' && $(this).attr('type') != 'radio' && $(this).attr('type') != 'file') || ($(this).attr('type') == 'checkbox' && $(this).is(':checked')) || ($(this).attr('type') == 'radio' && $(this).is(':checked'))){
// // data.append($(this).attr('name'), $(this).val());
// // }
// // });
// // $.each($('[name=formPlaceAd]').find('textarea'), function () {
// // data.append($(this).attr('name'), $(this).val());
// // });
// // $.each($('[name=formPlaceAd]').find('select'), function () {
// // data.append($(this).attr('name'), $(this).val());
// // });
// //
// // data.append('files[]', images[i].file, images[i].name);
// //
// // var xhr = new XMLHttpRequest();
// // xhr.open('post', '//www.doodloo.com/server/php/', true);
// //
// // xhr.onreadystatechange = function () {
// // if (xhr.readyState == 4) {
// // var response = JSON.parse(xhr.responseText);
// // $('#files').append(`<div class="col-xs-3">
// // <div class="thumbnail">
// // <label>Default <input type="radio" name="primary" value="${response.files[0].name}"></label><br>
// // <div class="thumb-wrapper"><img src="${response.files[0].thumbnailUrl}" width="60" height="60" ></div><br>
// // <input type="hidden" name="images[]" value="${response.files[0].name}">
// // <button type="button" class="btn btn-primary" data-image="${response.files[0].name}">Delete</button>
// // </div>
// // </div>`);
// //
// // if (++i < images.length) {
// // _uploadeimage(i);
// // }else{
// // setTimeout(function () {
// // /*******FINISH*******/
// // /*-->*/$('[id=formPlaceAd]').find('[type=submit]').click();
// // }, 3000)
// // }
// // }
// // };
// // xhr.send(data);
// // }
//
// });
}
});
<file_sep><?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'defaultRoute' => 'main',
'sourceLanguage' => 'en-US',
'controllerNamespace' => 'frontend\controllers',
'modules' => [
'coupons' => [
'class' => 'backend\modules\coupons\Coupons',
],
],
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
'mailer' => [
'class'=>'yii\swiftmailer\Mailer',
'useFileTransport'=>true,
'sender' => ['<EMAIL>' => 'Sender name'], // or ['<EMAIL>' => 'Sender name']
'welcomeSubject' => 'Welcome',
'confirmationSubject' => 'Confirmation',
'reconfirmationSubject' => 'Email change',
'recoverySubject' => 'Recovery',
],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'main/error',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'blog/index' => "blog/index",
'blog/<slug>' => "blog/blog",
'listing-section/index' => "listing-section/index",
'listing-section/<slug>' => "listing-section/listing",
],
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@frontend/mail',
'useFileTransport' => false,//set this property to false to send mails to real email addresses
//comment the following array to send mail using php's mail function
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'cloud1032.hostgator.com',
'username' => '<EMAIL>',
'password' => '<PASSWORD>', //Move this into params
'port' => '465',
'encryption' => 'ssl',
'streamOptions' => [
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
],
],
],
],
],
'params' => $params,
];
<file_sep>file.reference.extensions-ads=.
files.encoding=UTF-8
site.root.folder=${file.reference.extensions-ads}
<file_sep><?php
use backend\modules\coupons\models\Coupons;
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $searchModel backend\modules\coupons\models\Search\CouponsSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Coupons');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="coupons-index table-responsive">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('app', 'Create Coupons'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(); ?> <?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
// ['class' => 'yii\grid\SerialColumn'],
// 'id',
'name',
[
'attribute' => 'image_url',
'format' => 'raw',
'label' => Yii::t('app', 'Image Url'),
'value' => function ($model) {
if($model->image_url != NULL){
return Html::img($model->image_url, ['width' => '50px']);
}else{
return NULL;
}
},
],
// 'coupon_code',
'discount_type',
'discount_count',
'available_coupons_count',
'expire_at',
// 'created_at',
// 'updated_at',
[
'attribute' => 'status',
'format' => 'raw',
'label' => Yii::t('app', 'Status'),
'value' => function ($model) {
if($model->status == 'active'){
return Html::a(Yii::t('app', 'Active'), ['status', 'id' => $model->id, 'className' => Coupons::className()], [
'class' => 'btn btn-xs btn-success btn-block',
'data-method' => 'post',
'data-confirm' => Yii::t('app', 'Are you sure you want to disable this coupon?'),
]);
}else{
return Html::a(Yii::t('app', 'Disabled'), ['status', 'id' => $model->id, 'className' => Coupons::className()], [
'class' => 'btn btn-xs btn-danger btn-block',
'data-method' => 'post',
'data-confirm' => Yii::t('app', 'Are you sure you want to activate this coupon?'),
]);
}
},
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?></div>
<file_sep><?php
$this->title = Yii::t('app', 'Our Services');
$this->registerMetaTag(['name' => 'keywords', 'content' => 'Our, Services, Page']);
$this->registerMetaTag(['name' => 'description', 'content' => 'Our Services Page']);
$this->params['breadcrumbs'][] = $this->title;
?>
<section class="paddingT padding-services">
<div class="container">
<div class="row">
<div id="contentSection" class="col-xs-12">
<h1 class="col-xs-12 text-center text-capitalize">
<?= $this->title ?>
</h1>
<p>
<?= Yii::t('app', 'We know and understand that the process of filling vacancies can be tedious AND expensive. The good news is that it doesn’t have to be, IF you join the countless landlords and building owners with Auf Posting by their side!
Auf Posting is an online listing distribution solution that allows you to effortlessly extend your marketing reach. Here are few our amazing services:') ?>
</p>
<dl>
<dt>
<?= Yii::t('app', 'Regular package- refreshed one week') ?>
</dt>
<dd>
<?= Yii::t('app', 'This package offers you instant visibility on over 50 sites and we renew your listing once a week.') ?>
</dd>
<dt>
<?= Yii::t('app', 'Kijiji Premium Package') ?>
</dt>
<dd>
<?= Yii::t('app', 'The Kijiji premium package offers you daily re-post on the most visited site on the internet.
The premium package boosts your vacancy, commercial or real estate, every day, to the front page of the section.') ?>
</dd>
<dt>
<?= Yii::t('app', 'Kijiji Premium Hourly Package') ?>
</dt>
<dd>
<?= Yii::t('app', 'As the name indicates, this options offers you the ability to have your vacancy re-posted every hour to the front page of the section.') ?>
</dd>
<dt>
<?= Yii::t('app', 'Apartment Hunter feature. // only available for Residential properties.') ?>
</dt>
<dd>
<?= Yii::t('app', 'This feature allows us to generates leads from people actively looking to move. We match your leads based on three (3) criteria: a. Rent amount b. Location c. Size of the unit.') ?>
</dd>
<dt>
<?= Yii::t('app', 'Craigslist Auto Re-Post Package') ?>
</dt>
<dd>
<?= Yii::t('app', 'This feature offers the ability to have your ads posted on the first page of Craigslist, every hour for up to 9 hours per day for a max of 12 days per month.') ?>
</dd>
</dl>
<p>
<?= Yii::t('app', 'YOUR success is OUR priority, and exposing your vacancies is what we do best.
Make Auf Posting a part of your life today, and finally give your vacancies the exposure they deserve!
Contact us today for more information or to create your own custom package.') ?>
</p>
<br>
</div>
</div>
</div>
</section>
<file_sep><?php
use kartik\file\FileInput;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
$this->title = Yii::t('app', 'Sign Up');
$this->registerMetaTag(['name' => 'keywords', 'content' => 'Sign, up']);
$this->registerMetaTag(['name' => 'description', 'content' => 'Sign up']);
$this->params['breadcrumbs'][] = $this->title;
$apartment = isset($_COOKIE['lang']) ? (($_COOKIE['lang'] == 'fr-FR') ? 'translation_fr' : 'apartment') : 'apartment';
$house = isset($_COOKIE['lang']) ? (($_COOKIE['lang'] == 'fr-FR') ? 'translation_fr' : 'house') : 'house';
?>
<div class="layout-main">
<div class="layout-content">
<div class="layout-content-body padding-signup">
<div class="row">
<div class="col-lg-10 col-sm-10 col-sm-offset-1">
<div class="demo-form-wrapper">
<?php $form = ActiveForm::begin([
'validateOnType' => true,
'validateOnBlur' => false,
'validationDelay' => 10,
'options' => [
'id' => 'sign-up-form',
'enctype' => 'multipart/form-data',
'onSubmit'=>"return image_upload();"
]
]) ?>
<ul class="steps">
<li class="step col-xs-4 active">
<a class="step-segment" href="#step-1" data-toggle="tab">
<i class="step-icon fa fa-user"></i>
</a>
<div class="step-content">
<strong class="hidden-xs">
<?= Yii::t('app', 'About You') ?>
</strong>
</div>
</li>
<li class="step col-xs-4">
<a id="step-two" class="step-segment">
<i class="step-icon fa fa-cubes"></i>
</a>
<div class="step-content">
<strong class="hidden-xs">
<?= Yii::t('app', 'About The Property') ?>
</strong>
</div>
</li>
<li class="step col-xs-4">
<a id="step-three" class="step-segment">
<i class="step-icon fa fa-credit-card"></i>
</a>
<div class="step-content">
<strong class="hidden-xs">
<?= Yii::t('app', 'Payment details') ?>
</strong>
</div>
</li>
</ul>
<div class="tab-content" style=" margin-top: 30px;">
<div id="step-1" class="tab-pane active">
<h4 class="text-center m-y-md">
<span>
<?= Yii::t('app', 'About You') ?>
</span>
</h4>
<div class="row">
<div class="col-sm-8 col-sm-offset-1 step2validcheck">
<?= $form->field($model, 'name', [
'template' => '{label} <div class="row"><div class="col-xs-12">{input}{hint}
<small class="help-block">
' . Yii::t("app", "Displayed on your profile and in other places as your name.") . '
</small>
</div>
</div>'
])->textInput()->label(Yii::t('app', 'First Name') . '*') ?>
<?= $form->field($model, 'l_name', [
'template' => '{label} <div class="row"><div class="col-xs-12">{input}{hint}
<small class="help-block">
' . Yii::t("app", "Displayed on your profile and in other places as your Last Name.") . '
</small>
</div>
</div>'
])->textInput()->label(Yii::t('app', 'Last Name') . '*') ?>
<?= $form->field($model, 'email')->textInput()->label(Yii::t('app', 'Email Address') . '*') ?>
<?= $form->field($model, 'phone', [
'template' => '{label} <div class="row"><div class="col-xs-12">{input}{hint}
<small class="help-block">
' . Yii::t("app", "Your phone number.") . '
</small>
</div>
</div>'
])->textInput()->label(Yii::t('app', 'Phone Number') . '*') ?>
<p class="signup__label">
<?= Yii::t('app', 'Gender') ?>
</p>
<div class="col-sm-12 text-center">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success btn-pill active" style="width: 100px;">
<input type="radio" name="SubmitData[gender]" value="Male" checked="checked">
<?= Yii::t('app', 'Male') ?>
</label>
<label class="btn btn-success btn-pill" style="width: 100px;">
<input type="radio" name="SubmitData[gender]" value="Female">
<?= Yii::t('app', 'Female') ?>
</label>
</div>
</div>
<br><br>
<div class="form-group">
<button data-step="2" class="btn btn-primary btn-block btn-next" type="submit"><?= Yii::t('app', 'NEXT') ?></button>
</div>
</div>
</div>
</div>
<div id="step-2" class="tab-pane">
<div class="row">
<div class="col-sm-8 col-sm-offset-1 step3validcheck">
<div class="col-sm-6">
<?php
$region = ArrayHelper::map(\common\models\Location::find()->where([
'parent_id' => 0
])->all(), 'name', 'name');
?>
<?= $form->field($model, 'region')->dropDownList($region,[
'prompt' => 'Select Region',
'onchange' => '$.get("' . yii\helpers\Url::toRoute(['/main/get-city']) . '", { id: $(this).val() })
.done(function(data){
$("#submitdata-city").html( data );
});'
])->label(Yii::t('app', 'Province') . '*') ?>
</div>
<div class="col-sm-6 ">
<?= $form->field($model, 'city')->dropDownList([],[
'prompt' => 'Select City',
])->label(Yii::t('app', 'City') . '*') ?>
</div>
<div class="clearfix"></div>
<div class="col-sm-6">
<?= $form->field($model, 'zone')->dropDownList([
'Milton-Parc' => Yii::t('app', 'Milton-Parc'),
'West of Campus' => Yii::t('app', 'West of Campus'),
'Concordia Area' => Yii::t('app', 'Concordia Area'),
'Lower Plateau' => Yii::t('app', 'Lower Plateau'),
'UQAM/The Village' => Yii::t('app', 'UQAM/The Village'),
'Hampstead' => Yii::t('app', 'Hampstead'),
'Cote-des-Neiges' => Yii::t('app', 'Cote-des-Neiges'),
'Université de Montréal Area' => Yii::t('app', 'Université de Montréal Area'),
'Plateau' => Yii::t('app', 'Plateau'),
'Mile-End' => Yii::t('app', 'Mile-End'),
'Around MAC campus' => Yii::t('app', 'Around MAC campus'),
'N.D.G.' => Yii::t('app', 'N.D.G.'),
'Outremont' => Yii::t('app', 'Outremont'),
'Old Montréal' => Yii::t('app', 'Old Montréal'),
'Rosemont' => Yii::t('app', 'Rosemont'),
'Little Burgundy/St-Henri' => Yii::t('app', 'Little Burgundy/St-Henri'),
'Town Mont Royal' => Yii::t('app', 'Town Mont Royal'),
'Verdun/St-Charles/LaSalle' => Yii::t('app', 'Verdun/St-Charles/LaSalle'),
'Westmount' => Yii::t('app', 'Westmount'),
'Parc Extension' => Yii::t('app', 'Parc Extension'),
'Areas outside the zone map' => Yii::t('app', 'Areas outside the zone map'),
], [
'prompt' => Yii::t('app', 'Select Zone'),
])->label(Yii::t('app', 'Zone') . '*')
?>
</div>
<div class="col-sm-6 ">
<?= $form->field($model, 'postal_code')->textInput(['maxlength' => true])->label(Yii::t('app', 'Postal Code') . '*') ?>
</div>
<div class="clearfix"></div>
<div class="col-sm-6">
<?= $form->field($model, 'street')->textInput(['maxlength' => true])->label(Yii::t('app', 'Street Name') . '*') ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'address')->textInput(['maxlength' => true])->label(Yii::t('app', 'Address') . '*') ?>
</div>
<div class="clearfix"></div>
<div class="col-sm-12">
<?= $form->field($model, 'apt_size')->textInput()->label(Yii::t('app', 'Size of apartment (square feet)') . '*') ?>
</div>
<div class="col-sm-12">
<p class="signup__label">
<?= Yii::t('app', 'Property type') ?>
<span class="ui-req">*</span>
</p>
<div class="col-sm-12 text-center">
<div class="btn-group" data-toggle="buttons">
<?php
$house_type = \common\models\HouseType::find()->all();
foreach($house_type as $key => $value):
?>
<label class="btn btn-success btn-pill <?= ($key == 0) ? 'active' : '' ?>">
<input type="radio" name="SubmitData[house_type_id]" value="<?= $value['id'] ?>"
<?= ($key == 0) ? 'checked="checked"' : '' ?> >
<?= Yii::t('app', $value[$house]) ?>
</label>
<?php endforeach; ?>
</div>
</div>
<br/>
<div class="signup__row signup__row--padded tooltips" id="divTotalNumberOfBedrooms">
<p class="signup__label">
<?= Yii::t('app', 'Total number of bedrooms') ?>
<span class="ui-req">*</span>
</p>
<div class="col-sm-12 text-center">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success btn-pill active">
<input type="radio" value="1" name="SubmitData[bedroom]"
checked="checked"> 1
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="2" name="SubmitData[bedroom]"> 2
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="3" name="SubmitData[bedroom]"> 3
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="4" name="SubmitData[bedroom]"> 4
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="5" name="SubmitData[bedroom]"> 5
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="6" name="SubmitData[bedroom]"> 6
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="7" name="SubmitData[bedroom]"> 7
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="8" name="SubmitData[bedroom]"> 8
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="9"
name="SubmitData[bedroom]"> 9
</label>
</div>
</div>
</div>
<br/>
<div class="signup__row signup__row--padded tooltips" id="divTotalNumberOfBedrooms">
<p class="signup__label">
<?= Yii::t('app', 'Total number of bathrooms') ?>
<span class="ui-req">*</span>
</p>
<div class="col-sm-12 text-center">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-success btn-pill active">
<input type="radio" value="1" name="SubmitData[bathroom]"
checked="checked"> 1
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="2" name="SubmitData[bathroom]"> 2
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="3" name="SubmitData[bathroom]"> 3
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="4" name="SubmitData[bathroom]"> 4
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="5" name="SubmitData[bathroom]"> 5
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="6" name="SubmitData[bathroom]"> 6
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="7" name="SubmitData[bathroom]"> 7
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="8" name="SubmitData[bathroom]"> 8
</label>
<label class="btn btn-success btn-pill">
<input type="radio" value="9"
name="SubmitData[bathroom]"> 9
</label>
</div>
</div>
</div>
<br/>
</div>
<div class="col-sm-12">
<br/>
<div class="signup__row signup__row--padded grid grid--split-4">
<?php
$ApartmentAmenitiesData = ArrayHelper::map(\common\models\ApartmentAmenities::find()->asArray()->all(), 'id', $apartment);
echo $form->field($model, 'apartment_ids')->checkboxList($ApartmentAmenitiesData, [
'itemOptions' => [
'labelOptions' => ['class' => 'col-xs-12 col-sm-6']
]
])->label(Yii::t('app', 'Apartment Amenities') . '*');
?>
</div>
<br>
</div>
<div class="col-sm-6">
<?php
$oprions = ['1' => '1' . Yii::t('app', ' Month')];
for($i = 2; $i <= 36; $i++){
$oprions[$i] = $i . Yii::t('app', ' Months');
}
?>
<?= $form->field($model, 'lease_length')->dropDownList($oprions,
[
'prompt' => Yii::t('app', 'Select Minimum Lease Term')
])->label(Yii::t('app', 'Lease Length') . '*')
?>
</div>
<div class="col-sm-3" style="padding-right: 0;">
<?= $form->field($model, 'rent', [
'template' => '{label} <div class="row"><div class="col-xs-12">
<span class="control-label dollar">$</span>
{input}{error}{hint}
</div>
</div>'
])->textInput([
'type' => 'number'
])->label(Yii::t('app', 'Rent (price of rent)') . '*',['style' => 'font-size: 0.68em;']) ?>
</div>
<div class="col-sm-3">
<?= $form->field($model, 'pets')->dropDownList([
'0' => Yii::t('app', 'No'),
'1' => Yii::t('app', 'Yes'),
], [
'prompt' => Yii::t('app', 'Pet Friendly') . '?'
])->label(Yii::t('app', 'Pet Friendly'),['style' => isset($_COOKIE['lang']) ? (($_COOKIE['lang'] == 'fr-FR') ? 'font-size: 0.72em;' : '') : ''])
?>
</div>
<div class="clearfix"></div>
<div class="col-xs-12">
<?= $form->field($model, 'parking_included')->dropDownList([
'1' => Yii::t('app', 'Yes'),
'2' => Yii::t('app', 'Available with additional fee'),
'0' => Yii::t('app', 'No parking Available'),
],[
'prompt' => Yii::t('app', 'Select Parking')
])->label(Yii::t('app', 'Parking Included') . '*')
?>
</div>
<div class="clearfix"></div>
<div class="col-xs-12" style="display: none;">
<?= $form->field($model, 'parking_count')->textInput([
'type' => 'number'
])->label(Yii::t('app', 'Parking Count') . '*')
?>
</div>
<div class="col-sm-12 parking">
<?= $form->field($model, 'parking_price')->textInput([
'type' => 'number'
])->label(Yii::t('app', 'Parking Price'))
?>
</div>
<div class="clearfix"></div>
<br/>
<div class="form-group">
<button data-step="3" class="btn btn-primary btn-block btn-next" type="submit">
<?= Yii::t('app', 'NEXT') ?>
</button>
</div>
</div>
</div>
</div>
<div id="step-3" class="tab-pane">
<div class="row">
<div class="col-sm-9 col-sm-offset-1">
<?= $form->field($model, 'title')->textInput()->label(Yii::t('app', 'Title of the Ad') . '*') ?>
<?= $form->field($model, 'content')->textarea(['rows' => 5])->label(Yii::t('app', 'Description (500 characters max)') . '*') ?>
<?= $form->field($model, 'contact_time')->checkboxList(
[
'a' => Yii::t('app', 'Afternoon'),
'e' => Yii::t('app', 'Evening'),
'm' => Yii::t('app', 'Morning'),
])->label(Yii::t('app', 'Contact Time') . '*') ?>
<?= $form->field($model, 'available_date')->widget(\kartik\date\DatePicker::className(), [
'name' => 'available_date',
'value' => date('Y-m-d'),
'options' => ['placeholder' => Yii::t('app', 'Select available date ...')],
'pluginOptions' => [
'format' => 'yyyy-mm-dd',
'todayHighlight' => true
]
])->label(Yii::t('app', 'Available Date') . '*') ?>
<?php
$allImage = [];
$initialPreviewConfig = [];
if (Yii::$app->controller->action->id == "create") {
$uploadUrl = Url::to(['/form-property/upload']);
} else {
$uploadUrl = Url::to(['/form-property/upload?id=' . $model->id]);
$arrayImgPath = explode(';', $model->image_url);
if ($arrayImgPath[0] != "") {
foreach ($arrayImgPath as $val) {
$img = explode('/', $val);
$img = $img[count($img)-1];
$allImage[] = $val;
$initialPreviewConfig[] = [
'caption' => $img,
'size' => filesize(Yii::getAlias('@frontend') . '/web/img/upload/' . $img),
'width' => "120px",
'url' => Yii::$app->homeUrl . "main/file-delete?id=" . $model->id,
'key' => $val,
];
}
} else {
$allImage = 0;
}
}
?>
<?= $form->field($model, 'image[]')->widget(FileInput::classname(), [
'attribute' => 'image',
'name' => 'image',
'options' => [
'accept' => 'image/*',
'multiple' => true,
'id' => 'image_upload_file',
],
'pluginOptions' => [
'dropZoneEnabled'=>false,
'previewFileType' => 'image',
'allowedFileExtensions' => ['jpg','png','gif','jpeg'],
'maxFileSize' => 4096,
'showPreview' => true,
'showUpload' => false,
'showCaption' => false,
'uploadUrl' => false,
'initialPreview' => [],
'initialPreviewAsData' => true,
'overwriteInitial' => false,
'initialPreviewShowDelete' => true,
'resizeImages' => true,
],
])->label(Yii::t('app', 'Image')); ?>
<script>
function image_upload()
{
$('.file-preview-thumbnails').each(function() {
if ($(this).find('img').length) {
return true;
} else {
$(".kv-fileinput-error").show().html('Please select image for upload');
return false;
}
});
}
</script>
<div class="form-group field-submitdata-packages required">
<label class="control-label package-m">
<?= Yii::t('app', 'Packages') . '*' ?>
</label>
<div id="submitdata-packages" class="text-center">
<?php $packages = \common\models\PaymentDetails::find()->all(); ?>
<?php foreach($packages as $key => $value): ?>
<div class="col-md-4 col-sm-4 col-xs-12">
<input id="<?= strtolower($value->name) ?>_package" class="package_id" type="checkbox" name="SubmitData[package_id][]" value="<?= $value->id ?>">
<label class="col-xs-12" for="<?= strtolower($value->name) ?>_package">
<?= isset($_COOKIE['lang']) ? (($_COOKIE['lang'] == 'en-US') ? $value->content : $value->content_translation) : $value->content ?>
</label>
</div>
<?php endforeach; ?>
</div>
<div class="help-block"></div>
</div>
<div class="clearfix"></div>
<br>
<div class="row">
<div class="col-xs-6">
<?php
$package_duration_id = ArrayHelper::map(\common\models\PackageDuration::find()->where(['is_status' => 1])->all(), 'id', 'duration');
?>
<?= $form->field($model, 'package_duration_id')->dropDownList($package_duration_id, ['prompt' => Yii::t('app', 'Select Package Duration')])->label(Yii::t('app', 'Package Duration (Months)')) ?>
</div>
<div class="col-xs-6 text-center">
<p class="discount_size center-block" style="display: none;">
<span>
<?= Yii::t('app', 'Discount') ?>
</span>
</p>
</div>
</div>
<div class="clearfix"></div>
<?= $form->field($model, 'promo_code')->textInput()
->label(Yii::t('app', 'Promo Code'), ['class' => 'package-m']) ?>
</div>
</div>
<div class="row">
<div class="col-sm-8 col-sm-offset-1">
<div class="form-group">
<br>
<button id="formFinal" class="btn btn-primary btn-block" type="submit">
<?= Yii::t('app', 'Pay Now') ?>
</button>
</div>
</div>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
</div>
</div><file_sep>/* global chrome */
//cityleases.com
//sublet.com
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'https://www.sublet.com' || url == "https://www.cityleases.com/") {
isRegistered();
} else if (url == 'https://www.sublet.com/lrregister.asp' || url == "https://www.cityleases.com/lrregister.asp") {
setData();
} else if (url.indexOf('/spider/lraptdetls.asp') + 1) {
setRegion();
} else if (url.indexOf('/spider/lraptdetls2.asp') + 1) {
setRegion2();
} else if (url.indexOf('/spider/lraptdetls3.asp') + 1) {
setHouseData();
} else if (url.indexOf('/spider/lrapt_otherdetls.asp') + 1) {
setContent();
} else if (url.indexOf('/spider/uploadphotos.asp') + 1) {
upload()
} else if (url.indexOf('/spider/postingtype.asp') + 1) {
selectedListingUpgrades()
}
//https://www.sublet.com/spider/lraptdetls.asp?supplierID=666809&country=5&state=Canada&City=Quebec&Area=
function setData() {
chrome.storage.local.get('ads', function (data) {
console.log(data.ads);
/**/
$('[name=username]').val(data.ads.email);
$('[name=username]').change();
/**/
$('[name=username1]').val(data.ads.email);
$('[name=username1]').change();
/**/
$('[name=password]').val(data.ads.pass);
$('[name=password]').change();
/**/
$('[name=password1]').val(data.ads.pass);
$('[name=password1]').change();
/**/
$('[name=first_name]').val(data.ads.name);
$('[name=first_name]').change();
/**/
$('[name=last_name]').val(data.ads.l_name);
$('[name=last_name]').change();
/**/
selector($('[name=country]'), 'Canada');
if (data.ads.region == 'Northwest Territories') {
selector($('[name=state]'), 'Canada Territories');
} else {
selector($('[name=state]'), 'Canada');
}
/**/
selector($('[name=city]'), data.ads.region);
/**/
$('[name=dphone]').val(data.ads.phone);
$('[name=dphone]').change();
/**/
selector($('[name=Relation]'), 'Owner');
/**/
if (data.ads.house_type == 'Apartment')
selector($('[name=RentalType]'), 'Rental Apartments');
else if (data.ads.house_type == 'House')
selector($('[name=RentalType]'), 'Rental Houses');
else
selector($('[name=RentalType]'), 'Corporate Housing');
/**/
selector($('[name=multiapt]'), '1 Unit');
window.setTimeout(function () {
captcha($('#recapcha_image'), $('[name=ImageField]'), {
numeric: 1,
min_len: 4,
max_len: 4
}, function () {
/*--->*/
$('[name=Submit]').click();
$('[name=Submit]')[0].dispatchEvent(new Event('click'));
});
}, 1500);
});
}
function setRegion() {
chrome.storage.local.get('ads', function (data) {
console.log(data.ads);
selector($('[name=country]'), 'Canada');
window.setTimeout(function () {
if (data.ads.region == 'Northwest Territories') {
selector($('[name=state]'), 'Canada Territories');
} else {
selector($('[name=state]'), 'Canada');
}
/**/
$('[name=zip]').val(data.ads.postal_code);
$('[name=zip]').change();
window.setTimeout(function () {
/*--->*/
$('[name=order_form_button]').click();
window.setTimeout(function () {
/*--->*/
$('#continue_lrapt').click();
}, 2000);
}, 2000);
}, 2000);
});
}
function setRegion2() {
chrome.storage.local.get('ads', function (data) {
console.log(data.ads);
/**/
$('[name=unitno]').val('My House');
$('[name=last_name]').change();
/**/
selector($('[name=city]'), data.ads.region);
/**/
selector($('[name=city]'), data.ads.region);
window.setTimeout(function () {
setCity();
}, 1500);
function setCity() {
var optionVal = $($('[name=areasel]').find('option')[i]).val();
console.log(optionVal);
$('[name=areasel]').val(optionVal);
$('[name=areasel]')[0].dispatchEvent(new Event('change'));
_setCity();
}
var i = 1;
function _setCity() {
window.setTimeout(function () {
selector($('[name=area2]'), 'Select Town Name');
var length = $('[name=areasel]').find('option').length;
selector($('[name=area2]'), data.ads.city);
if (!($('[name=area2]').val() && $('[name=area2]').val().length) && ++i < length) {
setCity();
} else if ($('[name=area2]').val() && $('[name=area2]').val().length) {
nextStep();
}
}, 3000);
}
function nextStep() {
/**/
$('[name=house_no]').val(data.ads.address);
$('[name=house_no]').change();
/**/
$('[name=cross_street]').val(data.ads.street);
$('[name=cross_street]').change();
/**/
$('[name=order_form_button]').click();
}
});
}
function setHouseData() {
chrome.storage.local.get('ads', function (data) {
console.log(data.ads);
/**/
var houseType = data.ads.house_type;
if (houseType == 'Studio' || houseType == 'Commercial') {
selector($('[name=Rental_type]'), 'Apartment');
/**/
selector($('[name=Apt_Size]'), 'Studio');
} else {
selector($('[name=Rental_type]'), houseType);
/**/
selector($('[name=Apt_Size]'), 'Studio');
var bedroomsArr = ['', 'One', 'Two', 'Three', 'Four', 'Five+'];
var key = parseInt(data.ads.bedroom) < 5 ? parseInt(data.ads.bedroom) : 5;
/**/
selector($('[name=Apt_Size]'), bedroomsArr[key]);
}
/**/
// selector($('[name=Private]'), 'Private Rental');
/**/
var bathroom = parseInt(data.ads.bathroom) < 3 ? data.ads.bathroom : '3+';
selector($('[name=Bathrooms]'), bathroom);
/*--*/
var date = data.ads.available_date.split('-');
/**/
var month = date[1].substr(0, 1) == '0' ? date[1].substr(1, 1) : date[1];
/**/
var dey = date[2].substr(0, 1) == '0' ? date[2].substr(1, 1) : date[2];
$('[name=sdatemm]').val(month);
$('[name=sdatemm]')[0].dispatchEvent(new Event('change'));
/**/
selector($('[name=sdatedd]'), dey);
/**/
selector($('[name=sdateyy]'), date[0]);
/**/
selector($('[name=end_opt]'), 'Minimum 1 Month');
/**/
selector($('[name=currency]'), 'US Dollar');
/**/
selector($('[name=Apt_Share]'), "Private");
selector($('[name=rental_available]'), "Yes");
/**
* Square Meters To Square Feet
* @type {number}
*/
var apt_size = Math.ceil(data.ads.apt_size * 10.764);
$('[name=area]').val(apt_size);
$('[name=area]')[0].dispatchEvent(new Event('change'));
window.setTimeout(function () {
var apartment_amenities = data.ads.apartment_amenities;
$('[name=mprice]').prop('readonly', false);
if (data.ads.parking_count > 0) {
$('[name=parking]').prop('checked', true);
}
if (find(apartment_amenities, "Elevator") + 1) {
$('[name=Elevator]').prop('checked', true);
}
if (find(apartment_amenities, "Air conditioning") + 1) {
$('[name=Aircond]').prop('checked', true);
}
if (find(apartment_amenities, "Maintenance On Site") + 1) {
$('[name=Internet]').prop('checked', true);
}
if (find(apartment_amenities, "Cable(TV)") + 1) {
$('[name=Cable]').prop('checked', true);
}
if (find(apartment_amenities, "Utilities Included") + 1) {
$('[name=Dishwasher]').prop('checked', true);
}
$('[name=mprice]').val(data.ads.rent);
if (find(apartment_amenities, 'Furniture') + 1) {
selector($('[name=furnished]'), 'Yes');
} else {
selector($('[name=furnished]'), 'No');
}
/**
* Handicapped Access
*/
if (find(apartment_amenities, 'Handicap') + 1) {
selector($('[name=handicap]'), 'Yes');
} else {
selector($('[name=handicap]'), 'No');
}
selector($('[name=Security]'), "None");
selector($('[name=Credit]'), "No");
var lease_length = parseInt(data.ads.lease_length);
if (lease_length > 3) {
selector($('[name=summer]'), "No");
} else {
selector($('[name=summer]'), "Yes");
}
/**/
if (data.ads.pets == '1') {
selector($('[name=Pets]'), 'Yes');
} else {
selector($('[name=Pets]'), 'No');
}
}, 1500);
window.setTimeout(function () {
$('[name=order_form_button]').click();
}, 2000);
});
}
function setContent() {
chrome.storage.local.get('ads', function (data) {
console.log(data.ads);
$('[name=other_details]').val(data.ads.content);
$('[name=other_details]').change();
$('[name=order_form_button]').click();
});
}
function setContent() {
chrome.storage.local.get('ads', function (data) {
console.log(data.ads);
$('[name=other_details]').val(data.ads.content);
$('[name=other_details]').change();
$('[name=order_form_button]').click();
});
}
function selectedListingUpgrades() {
chrome.storage.local.get('ads', function (data) {
$('[name=defpremcost]').prop('checked', true);
$('[name=agcheck]').prop('checked', true);
$('[name=Submit]').click();
});
}
function upload() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
// $.each($('#upload-form').find('input'), function () {
// data.append($(this).attr('name'), $(this).val());
// });
data.append('supplyid', $('[name=supplyid]').val());
data.append('picture' + (i + 1), images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.open('POST', 'https://www.cityleases.com/spider/' + $('#upload-form').attr('action'), true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
// var innerBody = xhr.responseText.replace(/([\n\r]|.)+<body[^>]+>/, '').replace(/<\/body[^>]*>([\n\r]|.)+/, '');
// $('body').html(innerBody);
if (++i < images.length && i <= 10) {
// _uploadeimage(i);
} else {
alert('end');
}
}
};
xhr.send(data);
}
});
}
});
<file_sep>
<?php
$directorio = '../archivos/';
$gestor_dir = opendir($directorio);
$archivos = '';
while (false !== ($nombre_fichero = readdir($gestor_dir))) {
$ficheros[] = $nombre_fichero;
$rutaArchivo = 'Archivos/'.$nombre_fichero;
$archivos .='<br><a target="_blank" href="'.$rutaArchivo.'" >'.$nombre_fichero.'</a>';
}
echo $archivos;
?>
<file_sep><?php
namespace common\models;
use Yii;
/**
* This is the model class for table "location".
*
* @property string $id
* @property string $name
* @property integer $parent_id
*/
class Location extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'location';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'parent_id'], 'required'],
[['parent_id'], 'integer'],
[['name'], 'string', 'max' => 120],
[['name', 'parent_id'], 'unique', 'targetAttribute' => ['name', 'parent_id'], 'message' => 'The combination of Name and Parent ID has already been taken.'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'parent_id' => Yii::t('app', 'Parent ID'),
];
}
}
<file_sep><?php
namespace backend\controllers;
use common\models\Translations;
use Yii;
use common\models\ListingSection;
use backend\models\ListingSectionControll;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Url;
use yii\web\UploadedFile;
/**
* ListingSectionController implements the CRUD actions for ListingSection model.
*/
class ListingSectionController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionStatus($id,$className)
{
$find = $className::findOne(['id' => $id]);
if($find->is_active == 1){
$find->is_active = 0;
$find->save();
}else{
$find->is_active = 1;
$find->save();
}
return $this->redirect('index');
}
/**
* Lists all ListingSection models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new ListingSectionControll();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single ListingSection model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
public function actionDeleteFile()
{
$name = $_GET['name'];
$id = $_GET['id'];
$rows = (new \yii\db\Query())
->select(['id', 'files'])
->from('listing_section')
->where(['id' => $_GET['id']])
->limit(1)
->one();
$explodeFiles = explode(',',$rows['files']);
$newfiles = array_diff($explodeFiles, array($name));
if(!empty($newfiles)) {
$newfiles = implode(",", $newfiles);
} else {
$newfiles = '';
}
Yii::$app->db->createCommand()
->update('listing_section', ['files' => $newfiles], "id=$id")
->execute();
exit;
}
/**
* Creates a new ListingSection model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new ListingSection();
$model_translations = new Translations();
if(!empty($_FILES['ListingSection'])) {
$totalFiles = count($_FILES['ListingSection']['name']['files']);
$nameArr = array();
if(!empty($_FILES['ListingSection']['name']['files'][0])) {
for($i = 0; $i<$totalFiles; $i++) {
$name =strtotime(date('y-m-d h:i:s')).$_FILES['ListingSection']['name']['files'][$i];
$nameArr[] = $name;
$tempPath = $_FILES['ListingSection']['tmp_name']['files'][$i];
$uploadDir = '/home3/x0s6j5b1/public_html/frontend/web/img/uploads/';
move_uploaded_file($tempPath, $uploadDir.$name);
}
}
}
if(!empty($nameArr)) {
$files = implode(',',$nameArr);
} else {
$files = '';
}
if ($model->load(Yii::$app->request->post()) && $model_translations->load(Yii::$app->request->post()) && $model->save()) {
// update files
$model_id = $model->id;
Yii::$app->db->createCommand()
->update('listing_section', ['files' => $files], "id=$model_id")
->execute();
$model_translations->parent_id = $model->id;
$model_translations->parent_tbl = 'listing';
$model_translations->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'model_translations' => $model_translations,
]);
}
}
/**
* Updates an existing ListingSection model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model_translations = Translations::findOne([
'parent_id' => $id,
'parent_tbl' => 'listing'
]);
if(!empty($_FILES['ListingSection'])) {
$totalFiles = count($_FILES['ListingSection']['name']['files']);
$nameArr = array();
if(!empty($_FILES['ListingSection']['name']['files'][0])) {
for($i = 0; $i<$totalFiles; $i++) {
$name =strtotime(date('y-m-d h:i:s')).$_FILES['ListingSection']['name']['files'][$i];
$nameArr[] = $name;
$tempPath = $_FILES['ListingSection']['tmp_name']['files'][$i];
$uploadDir = '/home3/x0s6j5b1/public_html/frontend/web/img/uploads/';
move_uploaded_file($tempPath, $uploadDir.$name);
}
}
}
if(!empty($nameArr)) {
$files = implode(',',$nameArr);
} else {
$files = '';
}
$model_translations = empty($model_translations) ? new Translations() : $model_translations;
if ($model->load(Yii::$app->request->post()) && $model_translations->load(Yii::$app->request->post()) && $model->save()) {
$rows = (new \yii\db\Query())
->select(['id', 'files'])
->from('listing_section')
->where(['id' =>$model->id])
->limit(1)
->one();
$explodeFiles = explode(',',$rows['files']);
$newfiles = array_merge($explodeFiles, $nameArr);
$newfiles = implode(",", $newfiles);
// update files
$model_id = $model->id;
Yii::$app->db->createCommand()
->update('listing_section', ['files' => $newfiles], "id=$model_id")
->execute();
$model_translations->parent_id = $model->id;
$model_translations->parent_tbl = 'listing';
$model_translations->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
'model_translations' => $model_translations,
]);
}
}
/**
* Deletes an existing ListingSection model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
Translations::findOne([
'parent_id' => $id,
'parent_tbl' => 'listing'
])->delete();
return $this->redirect(['index']);
}
/**
* Finds the ListingSection model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return ListingSection the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = ListingSection::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
<file_sep><?php
namespace backend\modules\coupons\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
/**
* This is the model class for table "coupons".
*
* @property integer $id
* @property string $name
* @property string $image_url
* @property string $coupon_code
* @property string $discount_type
* @property integer $discount_count
* @property integer $available_coupons_count
* @property string $expire_at
* @property string $created_at
* @property string $updated_at
* @property string $status
* @property string $image
* @property string $generate_coupon_code
*
*/
class Coupons extends \yii\db\ActiveRecord
{
public $image;
public $generate_coupon_code;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'coupons';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => new Expression('NOW()'),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['discount_type', 'discount_count', 'available_coupons_count', 'status'], 'required'],
[['discount_type', 'status'], 'string'],
[['discount_count', 'available_coupons_count'], 'integer'],
[['created_at', 'updated_at', 'expire_at'], 'safe'],
[['name', 'image_url'], 'string', 'max' => 500],
[['coupon_code'], 'string', 'max' => 255],
[['coupon_code'], 'unique'],
[['generate_coupon_code'], 'safe'],
[['image'], 'safe'],
[['image'], 'file', 'extensions'=>'jpg, png', 'maxSize'=> 2000000], //max 2 mb
[['image'], 'image'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'image_url' => Yii::t('app', 'Image Url'),
'coupon_code' => Yii::t('app', 'Coupon Code'),
'discount_type' => Yii::t('app', 'Discount Type'),
'discount_count' => Yii::t('app', 'Discount Count'),
'available_coupons_count' => Yii::t('app', 'Available Coupons Count'),
'expire_at' => Yii::t('app', 'Expire At'),
'created_at' => Yii::t('app', 'Created At'),
'updated_at' => Yii::t('app', 'Updated At'),
'status' => Yii::t('app', 'Status'),
'image' => Yii::t('app', 'Image'),
'generate_coupon_code' => Yii::t('app', 'Generate Coupon Code'),
];
}
}<file_sep><?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model common\models\SubmitData */
$this->title = $model->title;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Submit Datas'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="submit-data-view table-responsive">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<?php
function setPackageId($model){
$all = \common\models\PaymentDetails::findAll(['id' => explode(',', $model->package_id)]);
$names = '';
foreach ($all as $key => $value) {
$names .= $value->name . ', ';
}
$names = rtrim($names, ', ');
return $names;
}
?>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'attribute' => 'published',
'value' => $model->published == 0 ? 'Unpublished' : 'Published'
],
'id',
[
'attribute' => 'package_id',
'format' => 'raw',
'value' => setPackageId($model)
],
'package_duration_id',
'login',
'pass',
'rent',
'title:ntext',
'content:ntext',
'name',
'l_name',
'gender',
'phone',
'email:email',
'contact_time',
'city',
'postal_code',
'street',
'address',
'apartment_ids',
'apt_size',
'bedroom',
'bathroom',
'house_type_id',
'available_date',
[
'attribute' => 'pets',
'value' => $model->pets == 0 ? 'No' : 'Yes'
],
'parking_count',
'parking_price',
'image_url:ntext',
'contact_person',
'zone',
'lease_length',
'region',
'region_iso',
],
]) ?>
</div>
<file_sep><?php
use yii\bootstrap\ActiveForm;
?>
<div class="new-banner" style="background-image:url(img/banner1.jpg);">
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="home_top_section">
<h1>
<?= Yii::t('app', 'Accelerated Marketing for Residential and Commercial Real Estate') ?>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="top-slider-content padding-right-section">
<h2>
<?= Yii::t('app', 'Extend the reach of your marketing effortlessly!') ?>
</h2>
<div class="size">
<p class="MsoNormal" style="box-sizing: border-box; margin: 0px 0px 10px;">
<?= Yii::t('app', 'With just one click, AUF Posting will:') ?>
</p>
<ul style="box-sizing: border-box; margin-top: 10px; margin-bottom: 10px; padding-left: 23px;">
<li style="box-sizing: border-box; list-style: none outside none; margin-bottom: 10px;">
<?= Yii::t('app', 'Automatically publish your rental listing to our syndicated network of OVER 40 websites (and counting)') ?>
</li>
<li style="box-sizing: border-box; list-style: none outside none; margin-bottom: 10px;">
<?= Yii::t('app', 'Reach over 500 thousand monthly targeted visitors across the web.') ?>
</li>
<li style="box-sizing: border-box; list-style: none outside none; margin-bottom: 10px;">
<?= Yii::t('app', 'Help you fill your vacancies with ease.') ?>
</li>
</ul>
<span class="promo-btn-m">
<a href="<?= Yii::$app->homeUrl ?>main/sign-up">
<?= Yii::t('app', 'Get Started') ?>
</a>
</span>
<a href="<?= Yii::$app->homeUrl ?>main/sign-up">
<img src="<?= Yii::$app->homeUrl?>img/icons-01.png" width="200px">
</a>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="padding-section">
<div id="player"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="success" id="success">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>
<?= Yii::t('app', 'AUF Posting focuses solely on your success') ?>
</h2>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="success-detail">
<div class="success-detail-img">
<img src="<?= Yii::$app->homeUrl?>img/boarding.png" alt="">
</div>
<div class="success-content">
<h2>
<?= Yii::t('app', 'Effortless Onboarding') ?>
</h2>
<p class="MsoNormal">
<?= Yii::t('app', 'A few simple clicks to provide basic information will get all of your leasing opportunities ready to go; making it easy for you to start generating interest immediately.Getting your rental listing rented has never been so easy.') ?>
</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="success-detail">
<div class="success-detail-img">
<img src="<?= Yii::$app->homeUrl?>img/marketing3.png" alt="">
</div>
<div class="success-content">
<h2>
<?= Yii::t('app', 'Marketing<br>Expertise') ?>
</h2>
<p class="MsoNormal">
<?= Yii::t('app', 'Whether you need professional photography, customized content or would like to discuss the right tools and strategies to generate the most interest for your leasing opportunities; our experts are ready to help you.') ?>
</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="success-detail">
<div class="success-detail-img">
<img src="<?= Yii::$app->homeUrl?>img/megaphone_icon (2).jpg" alt="">
</div>
<div class="success-content">
<h2>
<?= Yii::t('app', 'Customer<br>Service') ?>
</h2>
<p class="MsoNormal">
<?= Yii::t('app', 'Our goal is to ensure that you get the full potential of the AUF Posting Platform. Our support team will answer any questions that you may have.') ?>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="our-testimonial">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Our Testimonials</h2>
<div class="testimonial-slider">
<div class="testimonial-detail">
<div class="testimonial-content">
<h6>Gestion Immobilier San Mar</h6>
<p>“We never had as many calls for our vacancies this is the Real Deal"</p>
</div>
</div>
<div class="testimonial-detail">
<div class="testimonial-content">
<h6><NAME> (Property Management)</h6>
<p>"I think it is an amazing service, Turn key, with one access point for responses (in other words, very streamlined). This type of service doesn't really exist. All other syndication services require a lot of time. If you want to move your property quickly, use this service. If you’re considering, STOP. Just do it. Money can be created, time cannot." </p>
</div>
</div>
<div class="testimonial-detail">
<div class="testimonial-content">
<h6><NAME>.(Management Titanium)</h6>
<p>I needed a maximum visibility at a reasonable price and Aufposting was exactly what i needed.
They provided Visibility, communication, support and posted all my ads in 48H.
No one has been able to help me in generate leads like you, I strongly your service
Aufposting is the best!!!</p>
</div>
</div>
<div class="testimonial-detail">
<div class="testimonial-content">
<h6>CasaSanMarcos</h6>
<p>"Thank you Aufposting.com, we save so much time in posting on different sites worth every penny, we have such a variety of leads, amazing"</p>
</div>
</div>
<div class="testimonial-detail">
<div class="testimonial-content">
<h6>Minko Property Management Inc.</h6>
<p>The personalized service is excellent, every question I had was answered and even better my expectations have been exceeded. We spend less time posting and more time renting </p>
</div>
</div>
<div class="testimonial-detail">
<div class="testimonial-content">
<h6><NAME>.</h6>
<p>I had a few studios to rent and I couldn’t believe the number of leads they generated. I’m extremely satisfied with the service. All my studios were rented.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clients">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>A few of our Partners</h2>
<div class="clients-list">
<div class="client-slider">
<div class="client-slide-m">
<img src="img/kijiji-logo.png" alt="">
</div>
<div class="client-slide-m">
<img src="img/craigslist-logo.png" alt="">
</div>
<div class="client-slide-m">
<img src="img/facebook.png" alt="">
</div>
<div class="client-slide-m">
<img src="img/McGill_Wordmark.png" alt="">
</div>
<div class="client-slide-m">
<img src="img/Concordia_University_logo.png" alt="">
</div>
<div class="client-slide-m">
<img src="img/Kangalou-Couleur-RGB.png" alt="">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="promo-button" id="contact_us">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="promo-btn-m">
<a href="#contact-popup" data-toggle="modal" data-target="">
<?= Yii::t('app', 'Contact Us') ?>
</a>
</div>
</div>
</div>
</div>
</div>
<div id="contact-popup" class="modal fade" role="dialog" aria-labelledby="myModalLabel" tabindex="-1">
<div class="contact-pop-m">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="contact_form">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3><?= Yii::t('app', 'Contact Us') ?></h3>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, "name")->textInput(["placeholder" => Yii::t('app', 'Name')])->label(false) ?>
<?= $form->field($model, "email")->textInput(["placeholder" => Yii::t('app', 'Email')])->label(false) ?>
<?= $form->field($model, "subject")->textInput(["placeholder" => Yii::t('app', 'Subject')])->label(false) ?>
<?= $form->field($model, "body")->textarea(["placeholder" => Yii::t('app', 'Message')])->label(false) ?>
<div class="g-recaptcha" data-sitekey="<KEY>"></div>
<div class="helper-block success_e">
<?php if(isset($errorMsg)){ ?>
<script>
setTimeout(function () {
$('#contact-popup').modal('show');
}, 1000);
</script>
<?php echo $errorMsg; } ?>
</div>
<?= \yii\helpers\Html::submitButton(Yii::t('app', 'Send'),['class'=>'btn'])?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep><header>
<div class="menu navbar-fixed-top">
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-3">
<div class="logo">
<a class="navbar-brand" href="http://aufposting.com/">
<img src="<?= Yii::$app->homeUrl.'img/Auf Posting Logo.jpg' ?>" class="img_responsive" width="180px">
</a>
<a href="http://www.aufposting.com"><img src="/frontend/web/img/logo2.png" class="banner-img"> </a>
</div>
</div>
<div class="col-md-9 col-sm-9">
<nav role="navigation" class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li>
<a class="page-scroll" href="http://aufposting.com/#success">
<?= Yii::t('app', 'Marketing Services') ?>
</a>
</li>
<li>
<a class="page-scroll" href="http://aufposting.com/#contact_us">
<?= Yii::t('app', 'Contact Us') ?>
</a>
</li>
<li>
<a class="page-scroll" href="<?=Yii::$app->homeUrl?>blog">
<?= Yii::t('app', 'Blog') ?>
</a>
</li>
<li>
<a class="page-scroll" href="<?=Yii::$app->homeUrl?>listing-section">
<?= Yii::t('app', 'Listing Section') ?>
</a>
</li>
<li>
<a class="page-scroll" href="<?=Yii::$app->homeUrl?>main/our-services">
<?= Yii::t('app', 'Our Services') ?>
</a>
</li>
<li>
<a href="<?=Yii::$app->homeUrl.'main/sign-up'?>">
<?= Yii::t('app', 'Sign Up') ?>
</a>
</li>
<li class="helper_class"></li>
<li class="dropdown">
<a href="" id="languages_dropdown" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<?php if(isset($_COOKIE['lang'])): ?>
<img src="<?= Yii::$app->homeUrl ?>img/flags/<?= $_COOKIE['lang'] ?>.png" alt="<?= $_COOKIE['lang'] ?>_flag" width="30px" height="30px" data-lang="<?= $_COOKIE['lang'] ?>">
<?php else: ?>
<img src="<?= Yii::$app->homeUrl ?>img/flags/en-US.png" alt="en_flag" width="30px" height="30px" data-lang="en-US">
<?php endif; ?>
</a>
<ul class="dropdown-menu dropdown-menu-right languages">
<li>
<img src="<?= Yii::$app->homeUrl ?>img/flags/en-US.png" alt="en_flag" width="30px" height="30px" data-lang="en-US">
</li>
<li>
<img src="<?= Yii::$app->homeUrl ?>img/flags/fr-FR.png" alt="fr_flag" width="30px" height="30px" data-lang="fr-FR">
</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</header><file_sep>//https://www.kijiji.ca/t-user-registration.html
//http://www.kijiji.ca/?uar=true
//http://www.kijiji.ca/h-ville-de-montreal/1700281
//http://www.kijiji.ca/h-ville-de-montreal/1700281?ua=true
//https://www.kijiji.ca/p-select-category.html?categoryId=37&siteLocale=en_CA
//https://www.kijiji.ca/p-post-ad.html?categoryId=214
//https://www.kijiji.ca/p-preview-ad.html
//http://www.kijiji.ca/v-view-details.html?adId=1239485118&posted=true&adActivated=true
/* global chrome */
jQuery(document).ready(function ($) {
/*******THIS SITE ONLY FOR Montreal city ******/
chrome.storage.local.get('ads', function (data) {
if (data.ads.city != 'Montreal') {
nextSite(false);
}
});
var url = String(window.location.href).replace(/\/$/, '');
if(url.indexOf('registration.html') + 1){
registration();
}else if(url.indexOf('www.kijiji.ca/?uar=true') + 1){
selectLocation();
}else if(url.indexOf('h-ville-de-montreal/1700281') + 1 && url.indexOf('?ua=true') + 1 == false){
getMail('<EMAIL>', function () {
var pattern = /[\"\'](https?:\/\/.*?activation\.html[^\"\']+)/im;
var forClick = pattern.exec($('#gh-mail-respons').html())[1].replace(/&/g, '&').replace(/®/g, '®');
// console.log(forClick);
window.location.href = forClick;
}, 3000);
}else if(url.indexOf('h-ville-de-montreal/1700281?ua=true') + 1){
window.location.href = '//www.kijiji.ca/p-select-category.html?categoryId=37&siteLocale=en_CA';
}else if(url.indexOf('?categoryId=') + 1){
if($('[data-cat-id=211]').length > 0){
selectBedroom();
}else if($('[name$=adType]').length > 0){
setTimeout(function () {
adPost();
}, 3000);
}
}else if(url == 'https://www.kijiji.ca/p-preview-ad.html'){
$('#PreviewAdForm').find('[type=submit]').click();
}else if(url.indexOf('Activated=true') + 1){
nextSite(true);
}else {
nextSite(false);
}
function registration() {
chrome.storage.local.get('ads', function (data) {
/**/
$('[name=email]').click();
$('[name=email]').val(data.ads.email);
$('[name=email]').parent()[0].dispatchEvent(new Event('change'));
/**/
$('[name=password]').click();
$('[name=password]').val(data.ads.pass);
$('[name=password]').parent()[0].dispatchEvent(new Event('change'));
/**/
$('[name=passwordConfirmation]').click();
$('[name=passwordConfirmation]').val(data.ads.pass);
$('[name=passwordConfirmation]').parent()[0].dispatchEvent(new Event('change'));
/**/
$('[name=nickname]').click();
$('[name=nickname]').val(data.ads.login);
$('[name=nickname]').parent()[0].dispatchEvent(new Event('change'));
/**/
$('[name=marketingOptedIn]').prop('checked', false);
$('[name=sendFeatureNotificationEmail]').prop('checked', true);
console.log($('#RegistrationForm').find('[type=submit]'));
setTimeout(function () {
$('#RegistrationForm').find('[type=submit]').click();
$('#RegistrationForm').find('[type=submit]')[0].dispatchEvent(new Event('click'));
}, 5000);
})
}
function selectBedroom() {
chrome.storage.local.get('ads', function (data) {
var bedroom = data.ads.bedroom;
if (data.ads.house_type == 'Studio') {
$('[data-cat-id=211]').click();
$('[data-cat-id=211]')[0].dispatchEvent(new Event('click'));
} else if (bedroom == 1) {
$('[data-cat-id=212]').click();
$('[data-cat-id=212]')[0].dispatchEvent(new Event('click'));
} else if (bedroom == 2) {
$('[data-cat-id=214]').click();
$('[data-cat-id=214]')[0].dispatchEvent(new Event('click'));
} else if (bedroom == 3) {
$('[data-cat-id=215]').click();
$('[data-cat-id=215]')[0].dispatchEvent(new Event('click'));
} else {
$('[data-cat-id=216]').click();
$('[data-cat-id=216]')[0].dispatchEvent(new Event('click'));
}
});
}
function selectLocation() {
chrome.storage.local.get('ads', function (data) {
$('#FormLocationPicker').find('a').each(function () {
let region = $(this).text().replace(/é/ig, 'e').replace(/è/ig, 'e');
if(region.search(data.ads.region ) + 1){
/**/ $(this)[0].click();
setTimeout(function () {
$('.level-2').find('a').each(function () {
let city = $(this).text().replace(/é/ig, 'e').replace(/è/ig, 'e');
if(city.search('Montreal') + 1){
$(this)[0].click();
setTimeout(function () {
if($('.level-3').html() != ''){
$('.level-3').find('a').each(function () {
if($(this).text().search('City') + 1){
$(this)[0].click();
setTimeout(function () {
$('#LocUpdate')[0].click();
}, 3000);
console.log($(this).text())
}
})
}
}, 3000)
}
})
},3000)
}
})
});
}
function adPost() {
$('[data-qa-id=package-0-bottom-select]').click(function () {
chrome.storage.local.get('ads', function (data) {
console.log(data.ads);
/**/ $('[name$=adType][value=OFFER]').click();
/**/ $('[name$=priceType][value=FIXED]').click();
/**/ $('[name$=priceAmount]').val(data.ads.rent);
$('[name$=priceAmount]')[0].dispatchEvent(new Event('change'));
/**/ $('[id=forrentbyhousing_s][value=ownr]').prop('checked', true);
$('[id=forrentbyhousing_s][value=ownr]')[0].dispatchEvent(new Event('click'));
/**/ selector($('#numberbathrooms_s'), data.ads.bathroom + ' bathroom');
/**/if (find(data.ads.apartment_amenities, 'Furniture') + 1) {
$('#furnished_s[value=1]').click();
} else {
$('#furnished_s[value=0]').click();
}
/**/if (data.ads.pets == 1) {
$('#petsallowed_s[value=1]').click();
} else {
$('#petsallowed_s[value=0]').click();
}
/**/$('#postad-title').val(data.ads.title);
$('#postad-title')[0].dispatchEvent(new Event('change'));
/**/$('#pstad-descrptn').val(data.ads.content);
$('#pstad-descrptn')[0].dispatchEvent(new Event('change'));
/**/$('#addressStreetNumber').val(data.ads.address);
$('#addressStreetNumber')[0].dispatchEvent(new Event('change'));
/**/$('#addressStreetName').val(data.ads.street);
$('#addressStreetName')[0].dispatchEvent(new Event('change'));
/**/$('#AddressCity').val(data.ads.city);
$('#AddressCity')[0].dispatchEvent(new Event('change'));
/**/selector($('#AddressProv'), data.ads.region_iso);
/**/$('#addressPostalCode').val(data.ads.postal_code);
$('#addressPostalCode')[0].dispatchEvent(new Event('change'));
selector($('[name=locationLevel0]'), 'City of Montréal');
/**/$('#PhoneNumber').val(data.ads.phone);
$('#PhoneNumber')[0].dispatchEvent(new Event('change'));
uploadeImage();
});
});
$('[data-qa-id=package-0-bottom-select]').click();
}
function uploadeImage() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
data.append('name', images[i].name);
data.append('file', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.kijiji.ca/p-upload-image.html', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var respons = JSON.parse(xhr.responseText);
$('[id=ImageUpload]').append(`<input type="hidden" name="images" value="${respons.normalUrl}" >`);
var li = $($('#UploadedImages').find('li')[i]);
li.removeClass('pic-placeholder');
li.addClass('thumbnail');
li.find('.image-area').css({'background': 'url(' + respons.normalUrl + ') center center no-repeat'});
if (++i < images.length && i <= 10) {
_uploadeimage(i);
} else {
window.setTimeout(function () {
$('#PostAdPreview').click();
$('#PostAdPreview')[0].dispatchEvent(new Event('click'));
}, 5000);
}
}
};
xhr.send(data);
}
});
}
});
<file_sep><?php
namespace backend\controllers;
use backend\models\LocationControl;
use common\models\Location;
use Yii;
use common\models\SubmitData;
use backend\models\SubmitDataControl;
use yii\filters\AccessControl;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
/**
* SubmitDataController implements the CRUD actions for SubmitData model.
*/
class SubmitDataController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
/**
* Lists all SubmitData models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new SubmitDataControl();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single SubmitData model.
* @param string $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
public function actionGetCity()
{
$getRequest = Yii::$app->request->get();
if (isset($getRequest['name'])) {
$regionName = $getRequest['name'];
$regionId = LocationControl::getRegionId($regionName);
$model = LocationControl::getCity($regionId);
if (count($model) > 0) {
foreach ($model as $val) {
$name = $val['name'];
echo "<option value='$name'>" . $val['name'] . "</option>";
}
} else {
echo "<option hidden>" . Yii::t('app', '-- No Such City --') . "</option>";
}
}
}
/**
* Creates a new SubmitData model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new SubmitData();
$postRequest = Yii::$app->request->post();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$apartment_ids = $postRequest['SubmitData']['apartment_ids'];
$lengthApartment_ids = count($apartment_ids);
$apartment_idsVal = '';
$package_id = '';
foreach ($apartment_ids as $key => $val) {
if ($key != $lengthApartment_ids - 1) {
$apartment_idsVal .= $val . ',';
} else {
$apartment_idsVal .= $val;
}
}
$model->apartment_ids = $apartment_idsVal;
$contact_time = $postRequest['SubmitData']['contact_time'];
$contact_timeVal = '';
$lengthContact_time = count($contact_time);
$package_id_arr = $model->package_id;
foreach ($contact_time as $key => $val) {
if ($key != $lengthContact_time - 1) {
$contact_timeVal .= $val . ',';
} else {
$contact_timeVal .= $val;
}
}
foreach($package_id_arr as $i => $j){
if($i != (count($package_id_arr) - 1)){
$package_id .= $j . ',';
}else{
$package_id .= $j;
}
}
$model->contact_time = $contact_timeVal;
$model->contact_person = 'person';
$model->package_id = $package_id;
$image = UploadedFile::getInstances($model, 'image');
$imgVal = '';
$model->image = $image;
if ($model->upload()) {
$url = explode('http:', explode('backend', $_SERVER["HTTP_REFERER"])[0])[1];
if($url == NULL){
$url = explode('https:', explode('backend', $_SERVER["HTTP_REFERER"])[0])[1];
}
$lengthImage = count($image);
foreach ($image as $key => $val) {
if ($key != $lengthImage - 1) {
$imgVal .= $url . 'frontend/web/img/upload/' . $val->name . ';';
} else {
$imgVal .= $url . 'frontend/web/img/upload/' . $val->name;
}
}
$model->image_url = $imgVal;
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}else{
return $this->goBack();
}
}else{
return $this->refresh();
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing SubmitData model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param string $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$postRequest = Yii::$app->request->post();
if ($model->load(Yii::$app->request->post())) {
$apartment_ids = $postRequest['SubmitData']['apartment_ids'];
$lengthApartment_ids = count($apartment_ids);
$apartment_idsVal = '';
$package_id = '';
foreach ($apartment_ids as $key => $val) {
if ($key != $lengthApartment_ids - 1) {
$apartment_idsVal .= $val . ',';
} else {
$apartment_idsVal .= $val;
}
}
$model->apartment_ids = $apartment_idsVal;
$contact_time = $postRequest['SubmitData']['contact_time'];
$contact_timeVal = '';
$lengthContact_time = count($contact_time);
$package_id_arr = $model->package_id;
foreach ($contact_time as $key => $val) {
if ($key != $lengthContact_time - 1) {
$contact_timeVal .= $val . ',';
} else {
$contact_timeVal .= $val;
}
}
foreach($package_id_arr as $i => $j){
if($i != (count($package_id_arr) - 1)){
$package_id .= $j . ',';
}else{
$package_id .= $j;
}
}
$model->contact_time = $contact_timeVal;
$model->contact_person = 'person';
$model->package_id = $package_id;
if($model->save()){
if($this->actionUpload($id)){
return $this->redirect(['view', 'id' => $model->id]);
}else{
return $this->redirect(['view', 'id' => $model->id]);
}
}else{
return $this->refresh();
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
public function actionUpload($id = '')
{
if($id != ''){
$model = $this->findModel($id);
}else{
$model = new SubmitData();
}
$image = UploadedFile::getInstances($model, 'image');
$model->image = $image;
if ($model->image_url == '' || $model->image_url == null) {
$imgVal = '';
} else {
if ($model->image != null) {
$imgVal = $model->image_url . ';';
} else {
$imgVal = $model->image_url;
}
}
if ($model->upload()) {
$url = explode('http:', explode('backend', $_SERVER["HTTP_REFERER"])[0])[1];
if($url == NULL){
$url = explode('https:', explode('backend', $_SERVER["HTTP_REFERER"])[0])[1];
}
$lengthImage = count($image);
foreach ($image as $key => $val) {
if ($key != $lengthImage - 1) {
$imgVal .= $url . 'frontend/web/img/upload/' . $val->name . ';';
} else {
$imgVal .= $url . 'frontend/web/img/upload/' . $val->name;
}
}
$model->image_url = $imgVal;
}
if($model->save(false)){
return true;
}else{
return false;
}
}
public function actionFileDelete($id)
{
$model = $this->findModel($id);
$img = explode('/',Yii::$app->request->post('key'));
$img = $img[count($img)-1];
$file = Yii::getAlias('@frontend') . '/web/img/upload/' . $img;
$imgPathData = '';
$arrayImgUrl = explode(';', $model->image_url);
$lengthArrayImgUrl = count($arrayImgUrl);
if ($arrayImgUrl != null) {
foreach ($arrayImgUrl as $key =>$val) {
if (Yii::$app->request->post('key') != $val) {
if ($key != $lengthArrayImgUrl-1){
$imgPathData .= $val.";";
}else{
$imgPathData .= $val;
}
}
}
}
$model->image_url = $imgPathData;
if(file_exists($file)){
if (unlink($file)){
$model->save(false);
}else{
return false;
}
}else{
return false;
}
return true;
}
/**
* Deletes an existing SubmitData model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param string $id
* @return mixed
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
if($model->image_url != NULL){
$images = explode(';', $model->image_url);
foreach ($images as $image){
$image = explode('/', $image);
$image = $image[count($image) - 1];
$image = Yii::getAlias('@frontend') . '/web/img/upload/' . $image;
if(file_exists($image)){
unlink($image);
}
}
}
$model->delete();
return $this->redirect(['index']);
}
/**
* Finds the SubmitData model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param string $id
* @return SubmitData the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = SubmitData::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
<file_sep>chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
var exec = /(https?:\/\/).*?(\w+\.\w+)$/ig.exec(request.msg);
var protocol = exec[1];
var domain = '.' + exec[2];
console.log(exec);
chrome.cookies.getAll({
domain: domain
}, function(cookies) {
console.log(cookies);
for (var i = 0; i < cookies.length; i++) {
chrome.cookies.remove({
url: protocol + cookies[i].domain + cookies[i].path,
name: cookies[i].name
});
}
});
});
<file_sep> <?php $apartment = isset($_COOKIE['lang']) ? (($_COOKIE['lang'] == 'fr-FR') ? 'translation_fr' : 'apartment') : 'apartment';
use yii\helpers\ArrayHelper;
$ApartmentAmenitiesData = ArrayHelper::map(\common\models\ApartmentAmenities::find()->asArray()->all(), 'id', $apartment);
$house_type = \common\models\HouseType::find()->asArray()->all();
$house_type = array_column($house_type, 'house', 'id');
?>
<?php $this->beginPage() ?>
<?php $this->beginBody() ?>
<h2 style="text-align: center;">Thank you.Your payment was successfully made.</h2>
<h3 style="text-align: center;"><span style="text-transform: uppercase;"><?= $model->name . ' ' . $model->l_name ?></span> , This is your registration data.</h3>
<table frame="box" rules="all" cellpadding="15" style="margin:auto;box-shadow: -2px -2px 4px grey, 4px 4px 4px grey;line-height:1.6;width:100%;">
<tr>
<th>Name</th>
<td><?= $model->name ?></td>
</tr>
<tr>
<th>Last Name</th>
<td><?= $model->l_name ?></td>
</tr>
<tr>
<th>Email</th>
<td><?= $model->email ?></td>
</tr>
<tr>
<th>Phone</th>
<td><?= $model->phone ?></td>
</tr>
<tr>
<th>Gender</th>
<td><?= $model->gender ?></td>
</tr>
<tr>
<th>City</th>
<td><?= $model->city ?></td>
</tr>
<tr>
<th>Region</th>
<td><?= $model->region ?></td>
</tr>
<tr>
<th>Street</th>
<td><?= $model->street ?></td>
</tr>
<tr>
<th>Zone</th>
<td><?= $model->zone?></td>
</tr>
<tr>
<th>Address</th>
<td><?= $model->address ?></td>
</tr>
<tr>
<th>Postal Code</th>
<td><?= $model->postal_code ?></td>
</tr>
<tr>
<th>Rent (price of rent)</th>
<td><?= $model->rent ?></td>
</tr>
<tr>
<th>Property type</th>
<td><?= $house_type[$model->house_type_id] ?></td>
</tr>
<tr>
<th>Bedroom</th>
<td><?= $model->bedroom ?></td>
</tr>
<tr>
<th>Bathroom</th>
<td><?= $model->bathroom ?></td>
</tr>
<tr>
<th>Size of apartment</th>
<td><?= $model->apt_size ?></td>
</tr>
<tr>
<th>Lease Length</th>
<td><?= $model->lease_length ?> Months</td>
</tr>
<tr>
<th>Rent (price of rent)</th>
<td><?= $model->rent ?> Months</td>
</tr>
<tr>
<th>Pet Friendly</th>
<td><?= ($model->pets==0)?'No':'Yes' ?></td>
</tr>
<tr>
<th>Parking Included</th>
<td>
<?php
if($model->parking_count==0){
echo "No parking Available";
} elseif($model->parking_count==1) {
echo "Yes";
} else {
echo "Available with additional fee";
}
?>
</td>
</tr>
<tr>
<th>Parking Price</th>
<td><?= $model->parking_price ?></td>
</tr>
<tr>
<th>Title</th>
<td><?= $model->title ?></td>
</tr>
<tr>
<th>Content</th>
<td><?= $model->content ?></td>
</tr>
<tr>
<th>Contact Time</th>
<td>
<?php if($model->contact_time=='a'){
echo "Afternoon ";
} elseif($model->contact_time=='e'){
echo "Evening";
} else {
echo "Morning";
} ?>
</td>
</tr>
<tr>
<th>Apartment Amenities</th>
<td>
<?php $ame = $model->apartment_ids;
$explodeAme = explode(',',$ame);
foreach($explodeAme as $expl){
$amte[] = $ApartmentAmenitiesData[$expl];
}
echo implode(', ',$amte);
?>
</td>
</tr>
<tr>
<th>Available Date</th>
<td><?= $model->available_date ?></td>
</tr>
<tr>
<th>Packages</th>
<td>
<?php
if($model->package_id==1){
echo "Price $50/Month";
} elseif($model->package_id==1){
echo "Price $150/Month";
} else {
echo "Price $225/Month";
}
?>
</td>
</tr>
<tr>
<th>Package Duration (Months)</th>
<td><?= $model->package_duration_id ?></td>
</tr>
<tr>
<th>Transaction ID</th>
<td><?= $token ?></td>
</tr>
<tr>
<th>Images</th>
<td>
<?php
if($model->image_url)
{
$images = $model->image_url;
$explodeImages = explode(';',$images);
foreach($explodeImages as $expl){
// $img[] ="<a target='_blank' href='http:".$expl."'>".$expl."</a>";
$img[] ="<a target='_blank' href='".$expl."'><img width='100' height='100' src='".$expl."'></a>";
}
echo implode('<br>',$img);
} else { ?>
No Image Uploaded
<?php }
?>
</td>
</tr>
</table>
<?php $this->endBody() ?>
<?php $this->endPage() ?><file_sep><?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel backend\models\SubmitDataControl */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Submit Datas');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="submit-data-index table-responsive">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('app', 'Create Submit Data'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'attribute' => 'published',
'value' => function($model){
if($model->published == 1){
return 'Published';
}else{
return 'Unpublished';
}
}
],
[
'attribute' => 'package_id',
'value' => function($model){
$all = \common\models\PaymentDetails::findAll(['id' => explode(',', $model->package_id)]);
$names = '';
foreach ($all as $key => $value) {
$names .= $value->name . ', ';
}
$names = rtrim($names, ', ');
return $names;
}
],
// 'package_duration_id',
// 'id',
'login',
'pass',
'rent',
// 'title:ntext',
// 'content:ntext',
// 'name',
// 'l_name',
// 'gender',
// 'phone',
// 'email:email',
// 'contact_time',
// 'city',
// 'postal_code',
// 'street',
// 'address',
// 'apartment_ids',
// 'apt_size',
// 'bedroom',
// 'bathroom',
// 'house_type_id',
// 'available_date',
// 'pets',
// 'parking_count',
// 'parking_price',
// 'image_url:ntext',
// 'contact_person',
// 'zone',
// 'lease_length',
// 'region',
// 'region_iso',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
<file_sep><?php
namespace common\models;
use Yii;
use yii\db\ActiveRecord;
/**
* This is the model class for table "submit_data".
*
* @property string $published
* @property string $id
* @property string $login
* @property string $pass
* @property double $rent
* @property string $title
* @property string $content
* @property string $name
* @property string $l_name
* @property string $gender
* @property string $phone
* @property string $email
* @property string $contact_time
* @property string $city
* @property string $postal_code
* @property string $street
* @property string $address
* @property string $apartment_ids
* @property string $apt_size
* @property string $bedroom
* @property string $bathroom
* @property integer $house_type_id
* @property string $available_date
* @property string $pets
* @property integer $parking_count
* @property integer $parking_price
* @property string $image
* @property string $contact_person
* @property string $zone
* @property integer $lease_length
* @property integer $floor_count
* @property string $region
* @property string $region_iso
* @property string $parking_included
* @property string $package_id
* @property string $package_duration_id
* @property integer $promo_code
*
* @property Payments[] $payments
*/
class SubmitData extends ActiveRecord
{
public $image;
public $parking_included;
public $promo_code;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'submit_data';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['published', 'content', 'gender', 'pets', 'contact_person', 'zone', 'region'], 'string'],
[['rent', 'title', 'content', 'name', 'l_name', 'gender', 'phone', 'email', 'city', 'postal_code', 'street', 'address', 'apartment_ids', 'apt_size', 'bedroom', 'bathroom', 'zone', 'lease_length', 'region', 'contact_time', 'parking_count', 'parking_included', 'package_id', 'package_duration_id'], 'required'],
[['floor_count'], 'number'],
[['rent'], 'number', 'min' => 15],
[['house_type_id', 'parking_count', 'parking_price', 'lease_length', 'apt_size', 'bedroom', 'bathroom', 'package_duration_id'], 'integer'],
[['available_date'], 'safe'],
[['login', 'pass', 'name', 'l_name', 'postal_code', 'street'], 'string', 'max' => 60],
[['email'], 'email'],
[['image'], 'safe'],
// [['image'], 'file', 'extensions'=>'jpg, gif, png', 'maxSize'=> 800000], //max 1 mb
// [['image'], 'image'],
[['promo_code'], 'safe'],
[['available_date'], 'validateDate', 'skipOnEmpty' => false, 'skipOnError' => false],
[['pass'], 'string', 'min' => 8],
['phone', 'match', 'pattern' => '/^[0-9]+$/', 'message' => Yii::t('app', 'Phone must be a number.')],
[['phone'], 'string', 'max' => 10],
['postal_code', 'match', 'pattern' => '/^[a-zA-Z0-9]+$/', 'message' => Yii::t('app', 'No symbols "_" or spaces are allowed.')],
// ['pass', 'match', 'pattern' => '/^[+A-Z]$/', 'message' => 'At least one character must be uppercase'],
// [['pass'], 'string', 'max' => 16],
[['content'], 'string', 'min' => 200],
[['city'], 'string', 'max' => 120],
[['address'], 'string', 'max' => 200],
[['title'], 'string', 'max' => 255],
[['region_iso'], 'string', 'max' => 2],
];
}
/* Date Validation*/
public function validateDate($attribute, $params) {
$date = date('Y-m-d');
if($this->$attribute == ''){
return $this->addError($attribute, Yii::t('app', 'Available Date cannot be blank.'));
}
if($this->$attribute < $date){
return $this->addError($attribute, Yii::t('app', 'Date Is Not Valid.'));
}
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'published' => Yii::t('app', 'Published'),
'id' => Yii::t('app', 'ID'),
'login' => Yii::t('app', 'Login'),
'rent' => Yii::t('app', 'Rent'),
'title' => Yii::t('app', 'Title'),
'content' => Yii::t('app', 'Content'),
'name' => Yii::t('app', 'Name'),
'l_name' => Yii::t('app', 'L Name'),
'gender' => Yii::t('app', 'Gender'),
'phone' => Yii::t('app', 'Phone'),
'email' => Yii::t('app', 'Email'),
'contact_time' => Yii::t('app', 'Contact Time'),
'city' => Yii::t('app', 'City'),
'postal_code' => Yii::t('app', 'Postal Code'),
'street' => Yii::t('app', 'Street'),
'address' => Yii::t('app', 'Address'),
'apartment_ids' => Yii::t('app', 'Apartment Ids'),
'apt_size' => Yii::t('app', 'Apt Size'),
'bedroom' => Yii::t('app', 'Bedroom'),
'bathroom' => Yii::t('app', 'Bathroom'),
'house_type_id' => Yii::t('app', 'House Type'),
'available_date' => Yii::t('app', 'Available Date'),
'pets' => Yii::t('app', 'Pets'),
'parking_count' => Yii::t('app', 'Parking Count'),
'parking_price' => Yii::t('app', 'Parking Price'),
'image' => Yii::t('app', 'Image'),
'contact_person' => Yii::t('app', 'Contact Person'),
'zone' => Yii::t('app', 'Zone'),
'lease_length' => Yii::t('app', 'Lease Length'),
'region' => Yii::t('app', 'Region'),
'region_iso' => Yii::t('app', 'Region Iso'),
'floor_count' => Yii::t('app', 'Floor Count'),
'parking_included' => Yii::t('app', 'Parking Included'),
'package_id' => Yii::t('app', 'Package'),
'package_duration_id' => Yii::t('app', 'Package Duration ID'),
'promo_code' => Yii::t('app', 'Promo Code'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPayments()
{
return $this->hasMany(Payments::className(), ['sd_id' => 'id']);
}
public function upload()
{
if ($this->image != NUll) {
foreach ($this->image as $file) {
$imgName = $file->name = Yii::$app->security->generateRandomString() . '.' . $file->extension;
$file->saveAs(Yii::$app->params['image'] . $imgName);
}
}
return true;
}
}
<file_sep><?php
namespace common\components;
use common\models\PackageDuration;
use common\models\PaymentDetails;
use Yii;
use yii\base\Component;
use PayPal\Api\Amount;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\Transaction;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\RedirectUrls;
class Paypal extends Component
{
public function makePayments($title, $package, $package_duration, $promo_code)
{
Yii::$app->paypal->init();
$apiContext = Yii::$app->paypal->getApiContext();
$payment_details = PaymentDetails::findAll(['id' => $package]);
$tmp_price = 0;
foreach ($payment_details as $index => $payment_detail) {
$tmp_price += $payment_detail->price;
}
$discount_from_package_duration = PackageDuration::findOne([
'id' => $package_duration
]);
$price = ($tmp_price * $discount_from_package_duration->duration) * $discount_from_package_duration->discount / 100;
$price = ($tmp_price * $discount_from_package_duration->duration) - $price;
$coupons = Yii::$app->getModule('coupons');
$price = $coupons->getPrice($promo_code, $price);
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$items = [];
$item = new Item();
$item->setName($title)
->setCurrency($payment_details[0]->currency)
->setQuantity(1)
->setPrice($price);
array_push($items,$item);
$itemList = new ItemList();
$itemList->setItems($items);
$details = new Details();
$details->setShipping($payment_details[0]->shipping)
->setTax($payment_details[0]->tax)
->setSubtotal($price);
$total = floatval($payment_details[0]->shipping) + floatval($payment_details[0]->tax) + $price;
$amount = new Amount();
$amount->setCurrency($payment_details[0]->currency)
->setTotal($total)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription($payment_details[0]->payment_description)
->setInvoiceNumber(uniqid());
if ( (! empty($_SERVER['REQUEST_SCHEME']) &&
$_SERVER['REQUEST_SCHEME'] == 'https') ||
(! empty($_SERVER['HTTPS']) &&
$_SERVER['HTTPS'] == 'on') ||
(! empty($_SERVER['SERVER_PORT']) &&
$_SERVER['SERVER_PORT'] == '443') ) {
$scheme = 'https';
} else {
$scheme = 'http';
}
$baseUrl = $scheme . '://' . Yii::$app->request->serverName . Yii::$app->homeUrl;
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl($baseUrl . "main/sign-up?success=true")->setCancelUrl($baseUrl . "main/sign-up?success=false");
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
try {
$payment->create($apiContext);
} catch (\Exception $ex) {
die($ex);
}
$approvalUrl = $payment->getApprovalLink();
return $approvalUrl;
}
}<file_sep><?php
session_start();
require_once("mail/class.phpmailer.php"); //library added in download source.
if (isset($_GET['method'])) {
if(isSet($_GET['method']) && $_GET['method'] == 'sendMail') {
try{
$array = array();
parse_str($_POST['datos'], $array);
$name_1 = $array['name_1'];
$last_name = $array['last_name'];
$phone = $array['phone'];
$email_2 = $array['email_2'];
$state = $array['state'];
$city = $array['city'];
$postalcode = $array['postalcode'];
$street = $array['street'];
$address = $array['address'];
$Tpropiedad = $array['Tpropiedad'];
$numBeds = $array['numBeds'];
$numBath = $array['numBath'];
$titleAd = $array['titleAd'];
$descriptionAd = $array['descriptionAd'];
$sizeOfApt = $array['sizeOfApt'];
$minLease = $array['minLease'];
$price = $array['rentPrice'];
$furnished = $array['furnished'];
$petsAllow = $array['petsAllow'];
$parkingInc = $array['parkingInc'];
// $creditcard_type_2 = $array['creditcard_type_2'];
// $creditcard_number_2 = $array['creditcard_number_2'];
// $creditcard_expdate_month_2 = $array['creditcard_expdate_month_2'];
// $creditcard_expdate_year_2 = $array['creditcard_expdate_year_2'];
// $creditcard_csc_2 = $array['creditcard_csc_2'];
$email_message = "<br>Reservation:<br><br>";
$email_message .= "Name: " . $name_1 . "<br>";
$email_message .= "Last Name: " . $last_name . "<br>";
$email_message .= "Phone: " . $phone . "<br>";
$email_message .= "Email: " . $email_2 . "<br>";
$email_message .= "State: " . $state . "<br>";
$email_message .= "City: " . $city . "<br>";
$email_message .= "Postal Code: " . $postalcode . "<br>";
$email_message .= "Street: " . $street . "<br>";
$email_message .= "Address: " . $address . "<br>";
$email_message .= "Type Property: " . $Tpropiedad . "<br>";
$email_message .= "Size of apt: " . $sizeOfApt . "<br>";
$email_message .= "Number Bedroom: " . $numBeds . "<br>";
$email_message .= "Number Bathroom: " . $numBath . "<br>";
//Apartment Amenities
$email_message .= "<b>Apartment Amenities:</b><br>";
if(!empty($array['Apartmentamenities'])) {
$email_message .= "<b>";
foreach($array['Apartmentamenities'] as $check => $value) {
$email_message .= $value . "<br>"; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
$email_message .= "</b><br>";
}
//Property Amenities
$email_message .= "<b>Property Amenities:</b><br>";
if(!empty($array['amenities'])) {
$email_message .= "<b>";
foreach($array['amenities'] as $check => $value) {
$email_message .= $value . "<br>"; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
$email_message .= "</b><br>";
}
$email_message .= "Minimum Lease Term: " . $minLease . "<br>";
$email_message .= "Rent (price of rent): " . $price . "<br>";
$email_message .= "Furnished: " . $furnished . "<br>";
$email_message .= "Pets Allowed: " . $petsAllow . "<br>";
$email_message .= "Parking Included: " . $parkingInc . "<br>";
$email_message .= "Title of the Ad: " . $titleAd . "<br>";
$email_message .= "Description: " . $descriptionAd . "<br>";
// $email_message .= "Type Credit Card: " . $creditcard_type_2 . "<br>";
// $email_message .= "Credit Card: " . $creditcard_number_2 . "<br>";
//$email_message .= "Expiration Month: " . $creditcard_expdate_month_2 . "<br>";
//$email_message .= "Expiration Year: " . $creditcard_expdate_year_2 . "<br>";
//$email_message .= "Code Security: " . $creditcard_csc_2 . "<br>";
//$email_message .= "Coupon: " . $coupon_code_2 . "<br>";
$to = $email_2;
$from = '<EMAIL>';
$name = 'Order Reservation';
$from_name = '<EMAIL>';
$subject = 'Order Reservation';
$body = $email_message;
$is_gmail = false;
global $error;
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
$mail->SMTPAuth = true;
if($is_gmail)
{
$mail->SMTPSecure = 'ssl';
$mail->Host = 'cloud1032.hostgator.com';
$mail->Port = 465;
$mail->Username = '<EMAIL>';
$mail->Password = '<PASSWORD>';
}
else
{
$mail->Host = 'mail.aufposting.com';
$mail->Username = '<EMAIL>';
$mail->Password = 'BAnkoh2rBD#F';
}
$mail->IsHTML(true);
$mail->From="<EMAIL>";
$mail->FromName="Order Reservation";
$mail->Sender=$from; // indicates ReturnPath header
$mail->AddReplyTo($from, $from_name); // indicates ReplyTo headers
//$mail->AddCC('<EMAIL>');
$mail->AddBCC("<EMAIL>"); // Copia oculta
$mail->AddBCC("<EMAIL>"); // Copia oculta
//$mail->AddBCC("<EMAIL>");
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = "Thank you for your preference!"; // email_messageo sin html
$_q = $_REQUEST['_q'];
foreach (glob('uploads/' . $_q . "*.*") as $filename) {
$mail->AddAttachment($filename, str_replace('uploads/', '', $filename));
}
// if(!empty($_SESSION['files'])) {
// //var_dump($_SESSION['files']);
// foreach ($_SESSION['files'] as $row) {// //echo $row['path'] ." - ".$row['name'];
// $mail->AddAttachment($row['path'], $row['name']);
// }
// }else{
// echo "no hay nada";
// }
session_destroy();
$mail->AddAddress($to);
if(!$mail->Send())
{
$error = 'Mail error: '.$mail->ErrorInfo;
echo $error;
}
else
{
$error = 'You will be redirected to paypal payment page!';
//header("Location: reservation.php?mail=true");
echo $error;
}
}catch(Exception $e){
echo "catch: ".$e->getMessage();
}
}
}
?><file_sep><?php
namespace frontend\controllers;
use common\components\Paypal;
use common\models\Location;
use common\models\PackageDuration;
use common\models\Payments;
use common\models\SubmitData;
use frontend\models\ContactForm;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use PayPal\Exception\PayPalConnectionException;
use yii\helpers\Url;
use yii\web\Controller;
use Yii;
use yii\web\UploadedFile;
class MainController extends Controller
{
public $layout = 'aufpostingMain';
public function actions()
{
Yii::$app->language = isset($_COOKIE['lang']) ? $_COOKIE['lang'] : 'en-US';
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionGetCity($id)
{
$res = Location::find()
->where([
'parent_id' => Location::findOne(['name' => $id])->id,
])
->asArray()
->all();
if(count($res) > 0){
echo "<option hidden>" . Yii::t('app', 'Select City') . "</option>";
foreach ($res as $r){
$name = $r['name'];
echo "<option value='$name'>". $name ."</option>";
}
}else{
echo "<option hidden>" . Yii::t('app', 'No Such City') . "</option>";
}
}
public function actionGetDiscountSize($discount)
{
$discount = PackageDuration::find()
->where(['id' => $discount])
->one()
->discount;
echo $discount; die;
}
public function actionIndex()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post())) {
$url = "https://www.google.com/recaptcha/api/siteverify";
$privatekey = "<KEY>5kKc4uql30gAy3uEPeT";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) && $data->success == true){
if($model->sendEmail(Yii::$app->params['adminEmail'])){
return $this->render('success', ['success_contact' => 'success_send']);
}else{
return $this->render('success', ['success_contact' => 'error_send']);
}
}else{
$errorMsg = Yii::t('app', 'ReCaptcha field is required.');
return $this->render('index', [
'model' => $model,
'errorMsg' => $errorMsg
]);
}
} else {
return $this->render('index', ['model' => $model]);
}
}
public function actionSignUp()
{
$model = new SubmitData();
$session = Yii::$app->session;
$session->open();
if(Yii::$app->request->get('success') == 'true'){
if($this->pay()){
$success = true;
$model = isset($_SESSION['model']) ? $_SESSION['model'] : NULL;
$session->destroy();
if($model != NULL){
$coupons = Yii::$app->getModule('coupons');
$coupons->reduceCouponCount($model->promo_code);
}
return $this->render('success',[
'success' => $success,
'model' => $model,
]);
}
}elseif(Yii::$app->request->get('success') == 'false'){
$success = false;
return $this->render('success',[
'success' => $success
]);
}
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$apartment_ids = '';
$contact_time = '';
$package_id = '';
$region_iso = [
'Alberta' => 'AB',
'British Columbia' => 'BC',
'Manitoba' => 'MB',
'New Brunswick' => 'NB',
'Newfoundland & Labrador' => 'NL',
'Nova Scotia' => 'NS',
'Northwest Territories' => 'NT',
'Nunavut' => 'NU',
'Ontario' => 'ON',
'Prince Edward Island' => 'PE',
'Québec' => 'QC',
'Saskatchewan' => 'SK',
'Yukon Territory' => 'YT',
];
$package_id_arr = $model->package_id;
foreach($model->apartment_ids as $key => $value){
if($key != (count($model->apartment_ids) - 1)){
$apartment_ids .= $value . ',';
}else{
$apartment_ids .= $value;
}
}
foreach($model->contact_time as $k => $v){
if($k != (count($model->contact_time) - 1)){
$contact_time .= $v . ',';
}else{
$contact_time .= $v;
}
}
foreach($package_id_arr as $i => $j){
if($i != (count($package_id_arr) - 1)){
$package_id .= $j . ',';
}else{
$package_id .= $j;
}
}
$model->login = Yii::$app->security->generateRandomString();
$model->apartment_ids = $apartment_ids;
$model->contact_time = $contact_time;
$model->region_iso = $region_iso[$model->region];
$model->package_id = $package_id;
$image = UploadedFile::getInstances($model, 'image');
$imgVal = '';
$model->image = $image;
if ($model->upload()) {
$lengthImage = count($image);
foreach ($image as $key => $val) {
if ($key != $lengthImage - 1) {
$imgVal .= "http://" . Yii::$app->getRequest()->serverName . Url::base() . '/img/upload/' . $val->name . ';';
} else {
$imgVal .= "http://" . Yii::$app->getRequest()->serverName . Url::base() . '/img/upload/' . $val->name;
}
}
$model->image_url = $imgVal;
// exit;
//$session['model'] = $model;
//self::sendSuccessMessage($_SESSION['model'],'azad');
//exit;
if ($model->save()) {
$paypal = new Paypal();
$response = $paypal->makePayments($model->title, $package_id_arr, $model->package_duration_id, $model->promo_code);
$session['model'] = $model;
return $this->redirect($response);
}
}
} else {
return $this->render('sign-up', ['model' => $model]);
}
}
public function actionOurServices()
{
return $this->render('our-services');
}
public function actionSuccess()
{
return $this->render('success');
}
/* Make Payments With PayPal*/
private function pay()
{
$modelPayments = new Payments();
Yii::$app->paypal->init();
$apiContext = Yii::$app->paypal->getApiContext();
$paymentId = Yii::$app->request->get('paymentId');
$payerId = Yii::$app->request->get('PayerID');
$token = Yii::$app->request->get('token');
try {
$payment = Payment::get($paymentId, $apiContext);
$execute = new PaymentExecution();
$execute->setPayerId($payerId);
$result = $payment->execute($execute, $apiContext);
} catch (PayPalConnectionException $e) {
$errorMSG = json_decode($e->getData());
return $this->render('/main/error', [
'name' => $errorMSG->name,
'message' => $errorMSG->message,
]);
} catch (\Exception $ex) {
die($ex);
}
$modelPayments->sd_id = $_SESSION['model']->id;
$modelPayments->payer_id = $payerId;
$modelPayments->transaction_id = $paymentId;
$modelPayments->token = $token;
if($modelPayments->save()){
/* Send Succes Message */
self::sendSuccessMessage($_SESSION['model'],$token);
/* Send Succes Message to Admin */
self::sendSuccessMessageAdmin($_SESSION['model'],$token);
return true;
}else{
return false;
}
}
/* Send Success Message */
private static function sendSuccessMessage($model,$token)
{
return Yii::$app->mailer->compose([
'text' => 'success-payment',
'html'=> 'success-payment'
], [
'model' => $model,
'token' => $token,
])
->setTo($model->email)
->setFrom([Yii::$app->params['adminEmail'] => 'AUFPosting'])
->setSubject('NEW Order Received.')
->send();
}
private static function sendSuccessMessageAdmin($model,$token)
{
return Yii::$app->mailer->compose([
'text' => 'success-payment',
'html'=> 'success-payment'
], [
'model' => $model,
'token' => $token,
])
->setTo('<EMAIL>')
->setFrom([Yii::$app->params['adminEmail'] => 'AUFPosting'])
->setSubject('NEW Order Received.')
->send();
}
}<file_sep>//http://www.gabinohome.com/en/register
//http://www.gabinohome.com/en/verify?&email=<EMAIL>&ce=222466_a8d267618v4w6y0
//http://www.gabinohome.com/en/advert_add
//http://www.gabinohome.com/en/advert_add?stage=7&type=free
//todo passord changed
//todo this site not worked for all regions.....nextSite(false) called in location()
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url.indexOf('/www.gabinohome.com/en/register') +1) {
registration();
}else if(url.indexOf('/advert_add') +1 && url.indexOf('?stage=7&type=free') + 1 == false){
if (document.cookie.search('verify') + 1 == false) {
getMail('<EMAIL>', function () {
var pattern = /https?:\/\/.*?verify[^\"\']+/igm;
var forClick = pattern.exec($('#gh-mail-respons').html())[0].replace(/&/g, '&').replace(/®/g, '®');
console.log(forClick);
document.cookie = "verify=" + true;
window.location.href = forClick;
}, 3000, true);
}else {
addDetails();
}
}else if(url.indexOf('/verify?&email') + 1){
setTimeout(function () {
window.location.href = '//www.gabinohome.com/en/advert_add';
}, 3000)
}else if(url.indexOf('?stage=7&type=free') + 1){
chrome.storage.local.get('gabinohomePass', function (data) {
nextSite({'pass': data.usedmontrealPass});
});
}else {
nextSite(false);
}
function registration() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[name="user_register[email]"]').click();
$('[name="user_register[email]"]').val(data.ads.email);
$('[name="user_register[email]"]')[0].dispatchEvent(new Event('keydown'));
$('[name="user_register[email]"]')[0].dispatchEvent(new Event('keyup'));
var pass = data.ads.pass.substr(0, 10);
chrome.storage.local.set({'gabinohomePass': pass});
/**/ $('[name="user_register[password]"]').click();
$('[name="user_register[password]"]').val(pass);
$('[name="user_register[password]"]')[0].dispatchEvent(new Event('keydown'));
$('[name="user_register[password]"]')[0].dispatchEvent(new Event('keyup'));
setTimeout(function () {
$('#form_register').find('[type=submit]').click();
$('#form_register').find('[type=submit]')[0].dispatchEvent(new Event('click'));
setTimeout(function () {
window.location.reload();
}, 3000)
}, 2000)
});
}
function addDetails() {
chrome.storage.local.get('ads', function (data) {
var step1 = setInterval(function () {
if($('#private').length > 0){
clearInterval(step1);
contactDetails();
}
}, 2000);
var step2 = setInterval(function () {
if($('[name="add_offer[id_advert_type]"]').length > 0 && $('[name="add_offer[id_region]"]').length == 0){
clearInterval(step2);
advertType();
}
}, 2000);
var step3 = setInterval(function () {
if($('[name="add_offer[id_region]"]').length > 0 && $('[name="add_offer[title_en]"]').length ==0){
clearInterval(step3);
location();
}
}, 2000);
var step4 = setInterval(function () {
if( $('[name="add_offer[title_en]"]').length > 0){
clearInterval(step4);
addDescription();
}
}, 2000);
var step5 = setInterval(function () {
if($('[name="myfile[]"]').length > 0){
clearInterval(step5);
addPhoto();
}
}, 2000);
var step6 = setInterval(function () {
$('form').each(function () {
var action = String($(this).attr('action'));
if(String($(this).attr('action')).search('type=free') + 1){
clearInterval(step6);
/*******fINISH**********/
$(this).find('[type=submit]').click();
$(this).find('[type=submit]')[0].dispatchEvent(new Event('click'));
setTimeout(function () {
window.location.reload();
}, 3000);
}
})
}, 2000);
})
}
function contactDetails() {
chrome.storage.local.get('ads', function (data) {
/**/ $('#private').prop('checked', true);
$('#private')[0].dispatchEvent(new Event('click'));
/**/ $('[name="user_contact[name]"]').click();
$('[name="user_contact[name]"]').val(data.ads.name);
$('[name="user_contact[name]"]')[0].dispatchEvent(new Event('change'));
/**/ $('[name="user_contact[surname]"]').click();
$('[name="user_contact[surname]"]').val(data.ads.l_name);
$('[name="user_contact[surname]"]')[0].dispatchEvent(new Event('change'));
/*********CHOOSE COUNTRY AND PHONE EXTENSION*********/
selector($('[name="user_contact[id_country]"]'), 'Canada');
selector($('[name="user_contact[id_tel_1_prefix]"]'), 'Canada');
/**/ $('[name="user_contact[tel]"]').click();
$('[name="user_contact[tel]"]').val(data.ads.phone);
$('[name="user_contact[tel]"]')[0].dispatchEvent(new Event('change'));
setTimeout(function () {
$('[name=add_this]').find('[type=submit]').click();
$('[name=add_this]').find('[type=submit]')[0].dispatchEvent(new Event('click'));
location.reload();
}, 3000)
});
}
function advertType() {
chrome.storage.local.get('ads', function (data) {
switch (data.ads.house_type){
case 'Apartment':
/**/ $('[name="add_offer[id_advert_type]"][value="2"]').prop('checked', true);
$('[name="add_offer[id_advert_type]"][value="2"]')[0].dispatchEvent(new Event('click'));
break;
case 'House':
/**/ $('[name="add_offer[id_advert_type]"][value="14"]').prop('checked', true);
$('[name="add_offer[id_advert_type]"][value="14"]')[0].dispatchEvent(new Event('click'));
break;
case 'Studio':
/**/ $('[name="add_offer[id_advert_type]"][value="1"]').prop('checked', true);
$('[name="add_offer[id_advert_type]"][value="1"]')[0].dispatchEvent(new Event('click'));
break;
case 'Commercial':
/**/ $('[name="add_offer[id_advert_type]"][value="10"]').prop('checked', true);
$('[name="add_offer[id_advert_type]"][value="10"]')[0].dispatchEvent(new Event('click'));
break;
}
setTimeout(function () {
$('[name=add_this]').find('[type=submit]').click();
$('[name=add_this]').find('[type=submit]')[0].dispatchEvent(new Event('click'));
}, 3000)
});
}
function location() {
chrome.storage.local.get('ads', function (data) {
/******CHOOSE REGION******/
selector($('[name="add_offer[id_region]"]'), data.ads.region);
if($('[name="add_offer[id_region]"]').val() == ''){
console.warn('don\'t can find the region');
setTimeout(function () {
/*******GO TO NEXT SITE******/
nextSite(false);
}, 2000);
}else {
setTimeout(function () {
selector($('[name="add_offer[id_area]"]'), data.ads.city);
console.log(data.ads.city);
/******WHEN NOT FIND CITY******/
if($('[name*="[id_area]').val() == ''){
/**/ $('[name*="add_xtra[alt_area]"]').click();
$('[name*="add_xtra[alt_area]"]').val(data.ads.city);
$('[name*="add_xtra[alt_area]"]')[0].dispatchEvent(new Event('change'));
$('[name*="add_xtra[alt_area]"]')[0].dispatchEvent(new Event('keydown'));
$('[name*="add_xtra[alt_area]"]')[0].dispatchEvent(new Event('keyup'));
}
/**/ $('[name*=address_street_name]').click();
$('[name*=address_street_name]').val(data.ads.street);
$('[name*=address_street_name]')[0].dispatchEvent(new Event('change'));
/**/ $('[name="add_offer[address_street_number]"]').click();
$('[name="add_offer[address_street_number]"]').val(data.ads.address);
$('[name="add_offer[address_street_number]"]')[0].dispatchEvent(new Event('change'));
/**/ $('[name="add_offer[address_pc]"]').click();
$('[name="add_offer[address_pc]"]').val(data.ads.postal_code);
$('[name="add_offer[address_pc]"]')[0].dispatchEvent(new Event('change'));
setTimeout(function () {
$('[name=add_this]').find('[type=button]').click()
$('[name=add_this]').find('[type=button]')[0].dispatchEvent(new Event('click'));
$('#mod_ad_map').bind('DOMSubtreeModified', function () {
setTimeout(function () {
$('[name=add_this]').find('[type=submit]').click();
$('[name=add_this]').find('[type=submit]')[0].dispatchEvent(new Event('click'));
}, 5000)
});
}, 2000);
}, 2000)
}
})
}
function addDescription() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[name="add_offer[title_en]"]').click();
$('[name="add_offer[title_en]"]').val(data.ads.title);
$('[name="add_offer[title_en]"]')[0].dispatchEvent(new Event('change'));
/**/ $('[name="add_offer[comments_en]"]').click();
$('[name="add_offer[comments_en]"]').val(data.ads.content);
$('[name="add_offer[comments_en]"]')[0].dispatchEvent(new Event('change'));
/**/ $('[name="add_offer[price]"]').click();
$('[name="add_offer[price]"]').val(data.ads.rent);
$('[name="add_offer[price]"]')[0].dispatchEvent(new Event('change'));
/*********CHOOSE COURSE*******/
selector($('[name="add_offer[id_currency_type]"]'), 'American Dollars');
/*********CHOOSE TAX Included *******/
selector($('[name="add_offer[tax_included]"]'), 'Tax Included');
/**/ $('[name="add_offer[size]"]').click();
$('[name="add_offer[size]"]').val(data.ads.apt_size);
$('[name="add_offer[size]"]')[0].dispatchEvent(new Event('change'));
setTimeout(function () {
$('#form_add_advert').find('[type=submit]').click();
$('#form_add_advert').find('[type=submit]')[0].dispatchEvent(new Event('click'));
}, 3000)
})
}
function addPhoto() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
var uploadFolderPath = '';
$('script').each(function () {
if($(this).text().search('www/vhosts/gabinohome.com') +1){
uploadFolderPath = /"(.*?gabinohome\.com\/httpdocs[^\"\']+)/igm.exec($(this).text())[1];
}
});
data.append('myfile', images[i].file, images[i].name);
data.append('id_ad', $('[name=id_advert]').val());
data.append('uploadFolder', uploadFolderPath);
data.append('createThumbnail', false);
data.append('createThumbnail', false);
data.append('uploadedImageKeepOriginal', false);
data.append('uploadedImageMaxHeight', '800');
data.append('uploadedImageMaxWidth', '1024');
var xhr = new XMLHttpRequest();
xhr.open('post', '//www.gabinohome.com/includes/ajax/upload/upload.php', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var response = JSON.parse(xhr.responseText);
if (++i < images.length) {
_uploadeimage(i);
}else{
setTimeout(function () {
/*******GO TO CONFIRM*******/
$('[name=add_this]').find('[type=submit]').click();
$('[name=add_this]').find('[type=submit]')[0].dispatchEvent(new Event('click'));
}, 3000)
}
}
};
xhr.send(data);
}
});
}
});
<file_sep><?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model common\models\Payments */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Payments'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="payments-view table-responsive">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
[
'attribute' => 'sd_id',
'format' => 'raw',
'value' => Html::a(Yii::t('app', 'View Submit Data'), \yii\helpers\Url::to(['/submit-data/view?id=' . $model->sd_id]), [
'class' => 'btn btn-info btn-sm'
])
],
'payer_id',
'token',
'transaction_id',
'created_at:datetime',
'updated_at:datetime',
],
]) ?>
</div>
<file_sep><?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model backend\models\SubmitDataControl */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="submit-data-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'published') ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'login') ?>
<?= $form->field($model, 'pass') ?>
<?= $form->field($model, 'rent') ?>
<?php // echo $form->field($model, 'title') ?>
<?php // echo $form->field($model, 'package_id') ?>
<?php // echo $form->field($model, 'package_duration_id') ?>
<?php // echo $form->field($model, 'content') ?>
<?php // echo $form->field($model, 'name') ?>
<?php // echo $form->field($model, 'l_name') ?>
<?php // echo $form->field($model, 'gender') ?>
<?php // echo $form->field($model, 'phone') ?>
<?php // echo $form->field($model, 'email') ?>
<?php // echo $form->field($model, 'contact_time') ?>
<?php // echo $form->field($model, 'city') ?>
<?php // echo $form->field($model, 'postal_code') ?>
<?php // echo $form->field($model, 'street') ?>
<?php // echo $form->field($model, 'address') ?>
<?php // echo $form->field($model, 'property_amenities_ids') ?>
<?php // echo $form->field($model, 'apartment_ids') ?>
<?php // echo $form->field($model, 'apt_size') ?>
<?php // echo $form->field($model, 'bedroom') ?>
<?php // echo $form->field($model, 'bathroom') ?>
<?php // echo $form->field($model, 'house_type_id') ?>
<?php // echo $form->field($model, 'available_date') ?>
<?php // echo $form->field($model, 'pets') ?>
<?php // echo $form->field($model, 'parking_count') ?>
<?php // echo $form->field($model, 'parking_price') ?>
<?php // echo $form->field($model, 'image_url') ?>
<?php // echo $form->field($model, 'contact_person') ?>
<?php // echo $form->field($model, 'zone') ?>
<?php // echo $form->field($model, 'lease_length') ?>
<?php // echo $form->field($model, 'region') ?>
<?php // echo $form->field($model, 'region_iso') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<file_sep>//http://www.classifiedclan.com/post/PostListing.aspx?countryId=25&stateId=2866&gId=2&dId=48
//http://www.classifiedclan.com/post/PostReview.aspx?countryid=25&stateid=2866&gid=2&did=48&postIdent=7ee070bb-5d25-4958-8e7f-3aa0ea37af01
//http://www.classifiedclan.com/post/PostConfirmation.aspx?postIdent=ed90353f-de04-41aa-8087-addc10959f0a
/* global chrome, captchaStatus*/
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'http://www.classifiedclan.com/post/PostListing.aspx?countryId=25&stateId=2866&gId=2&dId=48'
&& !($('#cphContent_lblStatus').length && $('#cphContent_lblStatus').html().indexOf('Duplicate posting') + 1)
) {
uploadeImage();
} else if (url.indexOf('&postIdent=') + 1) {
accept();
} else if (url.indexOf('/PostConfirmation') + 1) {
//TODO the site don't send Email for confirm
nextSite(false);
} else {
nextSite(false);
}
function uploadeImage() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
$.each($('input'), function () {
if ($(this).attr('type') != 'checkbox' || $(this).attr('type') != 'radio' || ($(this).attr('type') == 'checkbox' && !$(this).is(':checked')) || ($(this).attr('type') == 'radio' && !$(this).is(':checked')))
data.append($(this).attr('name'), $(this).val());
});
data.append('ctl00$cphContent$fileUploadImage', images[i].file, images[i].name);
var xhr = new XMLHttpRequest();
xhr.open('post', $('form').attr('action'), true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var innerBody = xhr.responseText.replace(/([\n\r]|.)+<body[^>]+>/, '').replace(/<\/body[^>]*>([\n\r]|.)+/, '');
$('body').html(innerBody);
if (++i < images.length) {
_uploadeimage(i);
} else {
$('body').html(innerBody);
insertData();
}
}
};
xhr.send(data);
}
});
}
function insertData() {
chrome.storage.local.get('ads', function (data) {
/**/ $('#cphContent_txtTitle').val(data.ads.title);
$('#cphContent_txtTitle').change();
/**/ $('#cphContent_txtDescription').val(data.ads.content);
$('#cphContent_txtDescription').change();
/**/ $('#cphContent_txtLocation').val(data.ads.address + ' ' + data.ads.street + ', ' + data.ads.city + ', ' + data.ads.region);
$('#cphContent_txtLocation').change();
// /**/ $('#cphContent_txtReference').click();
// $('#cphContent_txtReference');
/**/$('#cphContent_txtPrice').val(data.ads.rent);
$('#cphContent_txtPrice').change();
/**/$('#cphContent_txtSize').val(data.ads.apt_size);
$('#cphContent_txtSize').change();
/**/ $('#cphContent_txtMapAddressLine1').click();
$('#cphContent_txtMapAddressLine1').val(data.ads.address);
/**/ $('#cphContent_txtMapCity').click();
$('#cphContent_txtMapState').val(data.ads.city);
/**/ $('#cphContent_txtMapState').click();
$('#cphContent_txtMapCity').val(data.ads.region);
/**/ $('#cphContent_txtMapCountry').click();
$('#cphContent_txtMapCountry').val('Canada');
/**/ $('#cphContent_dlAttributes_chkAttribute_0').click();
/**/ if (data.ads.pets == '1') {
$('#cphContent_dlAttributes_chkAttribute_1').click();
$('#cphContent_dlAttributes_chkAttribute_2').click();
}
/**/ $('#cphContent_dlPermissions_chkPermission_0').click();
/**/ $('#cphContent_rdVisivility3').click();
/**/ $('#cphContent_txtEmail').click();
$('#cphContent_txtEmail').val(data.ads.email);
/**/ $('#cphContent_txtEmailConfirm').click();
$('#cphContent_txtEmailConfirm').val(data.ads.email);
/*-->*/ $('#cphContent_btnSubmit').click();
});
}
function accept() {
/**/ $('#cphContent_chkAcceptTerms').click();
$('#cphContent_txtVarification');
captcha($('#cphContent_imgVarification').parent('.floatLeftCell'), $('#cphContent_txtVarification'), {numeric: 2, min_len: 3, max_len: 4}, function () {
$('#cphContent_btnSubmit').click();
});
}
});
<file_sep>//http://www.myadmonster.com/free-ads/postfreead.php
//http://www.myadmonster.com/free-ads/prepost.php
//http://www.myadmonster.com/free-ads/post.php
//http://www.myadmonster.com/free-ads/post2.php
//http://www.myadmonster.com/postgo.php?ac=5&id=17012003514163&zx=2Cna1D&ex=Ut1SC6gVfHeIisZD7WzJmE52hnXk8a&xi=jNgwE1R6
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'http://www.myadmonster.com/free-ads/postfreead.php') {
/*-->*/$('[id=postanon]').find('[type=submit]').click();
} else if (url == 'http://www.myadmonster.com/free-ads/prepost.php') {
/*-->*/$('form').find('[type=submit]').click();
}else if(url == 'http://www.myadmonster.com/free-ads/post.php'){
addInfo();
}else if(url == 'http://www.myadmonster.com/free-ads/post2.php'){
getMail('<EMAIL>', function () {
var pattern = /(www\.+[^<>"']+)/igm;
var forClick = pattern.exec($('#gh-mail-respons').html())[1].replace(/&/g, '&').replace(/®/g, '®');
window.location.href = '//'+ forClick;
}, 3000, true);
}else if(url.indexOf('/postgo.php') +1 ){
nextSite(true);
}else {
nextSite(false);
}
function addInfo() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[id=idemail]').click();
$('[id=idemail]').val(data.ads.email);
/**/ $('[id=idusername]').click();
$('[id=idusername]').val(data.ads.login);
/**/ $('[id=idphone]').click();
$('[id=idphone]').val(data.ads.phone);
/**/ $('[id=category]').click();
$('[id=category]').val('Real Estate Rental');
/**/ $('[id=country]').click();
$('[id=country]').val('Canada');
/**/ $('[id=idstate]').click();
$('[id=idstate]').val(data.ads.region);
/**/ $('[id=idcity]').click();
$('[id=idcity]').val(data.ads.city);
/**/ $('[id=idzip]').click();
$('[id=idzip]').val(data.ads.postal_code);
/**/ $('[name=duration]').click();
$('[name=duration]').val('28');
/**/ $('[name=adtype]').click();
$('[name=adtype]').val('Trade');
/**/ $('[id=idprice]').click();
$('[id=idprice]').val(data.ads.rent);
/**/ $('[id=idadtitle]').click();
$('[id=idadtitle]').val(data.ads.title);
/**/ $('[id=idcontent]').click();
$('[id=idcontent]').val(data.ads.content);
var captchaCode = $('[id=thingy]').html();
/**/ $('[id=capthingy]').click();
$('[id=capthingy]').val(captchaCode);
/*-->*/$('form').find('[type=submit]').click();
});
}
});
<file_sep>//https://offcampuslistings.ca/my-account.html?confirmationCourriel=1&l=en
//https://offcampuslistings.ca/my-account.html?succesFormInscription=true
//https://offcampuslistings.ca/main.cfm?l=en&p=05_200
//https://offcampuslistings.ca/main.cfm?l=en&p=05_220
//https://offcampuslistings.ca/main.cfm?l=en&p=05_221&succesFormAnnonce=true&id1=
//https://offcampuslistings.ca/main.cfm?l=en&p=05_222&succesFormAnnoncePaiement=true&id1=
//https://offcampuslistings.ca/main.cfm?l=en&p=05_223&succesFormAnnonceFacturation=true&id1=
//TODO peymant system
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'https://offcampuslistings.ca/my-account.html') {
registration();
}else if(url.indexOf('succesFormInscription')+1){
//TODO email click
getMail('<EMAIL>', function () {
var pattern = /<p>[\n\r\t\s]*(https?:\/\/[^<]+)/igm;
var forClick = pattern.exec($('#gh-mail-respons').html())[1].replace('&', '&');
window.location.href = forClick;
}, 300, true);
}
else if (url.indexOf('confirmationCourriel')+1) {
login();
}else if(url.indexOf('p=05_200')+1){
window.location.href = 'https://offcampuslistings.ca/main.cfm?l=en&p=05_220';
}else if(url.indexOf('p=05_220')+1 ){
location();
}else if(url.indexOf('p=05_221')+1){
$('[id=btn_paiement]').click();
}else if(url.indexOf('p=05_222')+1){
paymentInfo();
} else if(url.indexOf('p=05_223')+1){
/*-->*/$('form').find('[type=submit]').click();
}
// else {
// if (url == '') {
// //TODO UPDATE
//
// }
// nextSite();
// }
function registration() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[id=Prenom]').click();
$('[id=Prenom]').val(data.ads.name);
/**/ $('[id=Nom]').click();
$('[id=Nom]').val(data.ads.l_name);
/**/ $('[id=Courriel]').click();
$('[id=Courriel]').val(data.ads.email);
/**/ $('[id=MotPasse]').click();
$('[id=MotPasse]').val(data.ads.pass);
/**/ $('[id=ConfirmeMotPasse]').click();
$('[name=ConfirmeMotPasse]').val(data.ads.pass);
/*-->*/$('[id=ConfirmeMotPasse]').parents('form').find('[type=submit]').click();
});
}
function login() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[id=username]').click();
$('[id=username]').val(data.ads.email);
/**/ $('[id=MotPasse2]').click();
$('[id=MotPasse2]').val(data.ads.pass);
/*-->*/$('form').find('[type=submit]').click();
});
}
function location() {
chrome.storage.local.get('ads', function (data) {
//TODO select_option-i mej bazain harmar house_type menak apartment@ ka
/**/ $('[id=type]').click();
switch (data.ads.house_type) {
case "Apartment":
$("[id=type]").val('1');
break;
case "House":
// $("[id=type]").val('');
break;
case "Studio":
// $("[id=type]").val('');
break;
case "Commercial":
// $("[id=type]").val('');
break;
}
if(data.ads.contact_person == "person"){
$('[id=IdentiteResponsable_Prop]').click();
}else {
$('[id=IdentiteResponsable_Autre]').click();
}
/**/ $('[id=resp_Nom]').click();
$('[id=resp_Nom]').val(data.ads.name);
/**/ $('[id=resp_Tel]').click();
$('[id=resp_Tel]').val(data.ads.phone);
/**/ $('[id=resp_Courriel]').click();
$('[id=resp_Courriel]').val(data.ads.email);
/**/ $('[id=Adresse]').click();
$('[id=Adresse]').val(data.ads.address);
/**/ $('[id=CP]').click();
$('[id=CP]').val(data.ads.postal_code);
/**/ $('[id=CoinRue]').click();
$('[id=CoinRue]').val(data.ads.street);
/**/ $('[id=zone]').click();
switch (data.ads.zone){
case "Milton-Parc":
$('[id=zone]').val("1");
break;
case "West of Campus":
$('[id=zone]').val("2");
break;
case "Around MAC campus":
$('[id=zone]').val("3");
break;
case "Concordia Area":
$('[id=zone]').val("4");
break;
case "Lower Plateau":
$('[id=zone]').val("5");
break;
case "UQAM/The Village":
$('[id=zone]').val("6");
break;
case "Hampstead":
$('[id=zone]').val("7");
break;
case "Cote-des-Neiges":
$('[id=zone]').val("8");
break;
case "Université de Montréal Area":
$('[id=zone]').val("9");
break;
case "Plateau":
$('[id=zone]').val("10");
break;
case "Mile-End":
$('[id=zone]').val("11");
break;
case "N.D.G.":
$('[id=zone]').val("12");
break;
case "Outremont":
$('[id=zone]').val("13");
break;
case "Old Montréal":
$('[id=zone]').val("14");
break;
case "Rosemont":
$('[id=zone]').val("15");
break;
case "<NAME>/St-Henri":
$('[id=zone]').val("16");
break;
case "Verdun/St-Charles/LaSalle":
$('[id=zone]').val("17");
break;
case "Westmount":
$('[id=zone]').val("18");
break;
case "Parc Extension":
$('[id=zone]').val("19");
break;
case "Areas outside the zone map":
$('[id=zone]').val("20");
break;
case "Town Mont Royal":
$('[id=zone]').val("21");
break;
default:
$('[id=zone]').val("1");
}
/**/ $('[id=taille]').click();
$('[id=taille]').val(data.ads.bedroom);
/**/ $('[id=datepicker]').click();
$('[id=datepicker]').val(data.ads.available_date);
/**/ $('[id=Duree]').click();
$('[id=Duree]').val(data.ads.lease_length);
/**/ $('[id=FlexibleOui]').click();
/**/ $('[id=loyer]').click();
$('[id=loyer]').val(data.ads.rent);
for(var key in data.ads.apartment_amenities){
switch (data.ads.apartment_amenities[key]){
case "Fridge":
$('[id=frigoOui]').click();
break;
case "Stove":
$('[id=FourOui]').click();
break;
case "Heating":
$('[id=ChauffageOui]').click();
break;
case "Hot Water":
$('[id=EauOui]').click();
break;
case "Electricity":
$('[id=ElectriciteOui]').click();
break;
case "Furniture":
$('[id=MeubleOui]').click();
break;
case "Washer/Dryer":
$('[id=LavSechOui]').click();
break;
case "Laundry":
$('[id=BuandrieOui]').click();
break;
case "Hook-ups":
$('[id=EntreLavSechOui]').click();
break;
}
}
/**/ $('[id=information_en]').click();
$('[id=information_en]').val(data.ads.content);
/*-->*/$('form').find('[id=btn_login]').click();
});
}
function paymentInfo() {
///CHOOSE REGION
selectRegion();
chrome.storage.local.get('ads', function (data) {
/**/$('[name=Prenom]').click();
$('[name=Prenom]').val(data.ads.name);
/**/$('[name=Nom]').click();
$('[name=Nom]').val(data.ads.l_name);
/**/$('[name=City]').click();
$('[name=City]').val(data.ads.city);
/**/ $('[id=PostalCode]').click();
$('[id=PostalCode]').val(data.ads.postal_code);
/**/ $('[id=Telephone]').click();
$('[id=Telephone]').val(data.ads.phone);
/**/ $('[id=PostalCode]').click();
$('[id=PostalCode]').val(data.ads.postal_code);
/**/ $('[id=Email]').click();
$('[id=Email]').val(data.ads.email);
/*-->*/$('form').find('[type=submit]').click();
});
}
function selectRegion() {
chrome.storage.local.get('ads', function (data) {
/**/$('[id=Country]').click();
switch (data.ads.region){
case "Alberta":
$('[id=Country]').val('52');
break;
case "British Columbia":
$('[id=Country]').val('53');
break;
case "Manitoba":
$('[id=Country]').val('55');
break;
case "New Brunswick":
$('[id=Country]').val('56');
break;
case "Newfoundland":
$('[id=Country]').val('62');
break;
case "Northwest Territories":
$('[id=Country]').val('63');
break;
case "Nova Scotia":
$('[id=Country]').val('57');
break;
case "Nunavut":
$('[id=Country]').val('58');
break;
case "Ontario":
$('[id=Country]').val('59');
break;
case "Prince Edward Island":
$('[id=Country]').val('54');
break;
case "Quebec":
$('[id=Country]').val('60');
break;
case "Saskatchewan":
$('[id=Country]').val('61');
break;
case "Yukon":
$('[id=Country]').val('64');
break;
case "British Columbia":
$('[id=Country]').val('53');
break;
}
});
}
});
<file_sep><?php
namespace backend\modules\coupons;
use backend\modules\coupons\models\Coupons as couponsModel;
/**
* coupons module definition class
*/
class Coupons extends \yii\base\Module
{
/**
* @inheritdoc
*/
public $controllerNamespace = 'backend\modules\coupons\controllers';
/**
* @inheritdoc
*/
public function init()
{
parent::init();
}
/**
* @property string $coupon_code
* @property integer $price
*
* @return $new_price or $price
*/
public function getPrice($coupon_code, $price)
{
if(isset($coupon_code) && isset($price)) {
$model = couponsModel::findOne([
'coupon_code' => $coupon_code,
'status' => 'active',
]);
if(!empty($model)){
$check_date = date('Y-m-d H:i:s');
if($model->expire_at >= $check_date || $model->expire_at==NULL){
if($model->available_coupons_count > 0){
if($model->discount_type == 'percent'){
$new_price = $price * $model->discount_count / 100;
$new_price = $price - $new_price;
return $new_price;
}else{
$new_price = $price - $model->discount_count;
return $new_price;
}
}else{
return floatval($price);
}
}else{
return floatval($price);
}
}else{
return floatval($price);
}
}else{
return false;
}
}
/**
* @property string $coupon_code
*
* @return true or false
*/
public function reduceCouponCount($coupon_code)
{
$model = couponsModel::findOne([
'coupon_code' => $coupon_code,
'status' => 'active',
]);
if(!empty($model)){
if($model->available_coupons_count > 0){
$model->available_coupons_count = $model->available_coupons_count - 1;
$model->save();
return true;
}else{
return false;
}
}else{
return false;
}
}
}
<file_sep><?php
use yii\widgets;
$this->title = Yii::t('app', 'Blog');
$this->registerMetaTag(['name' => 'keywords', 'content' => 'Blog']);
$this->registerMetaTag(['name' => 'description', 'content' => 'Blog']);
$this->params['breadcrumbs'][] = $this->title;
?>
<section class="paddingT padding-services">
<?php if (!empty($blogContent)): ?>
<div class="container">
<?php foreach ($blogContent as $item): ?>
<div class="row">
<div class="col-xs-12">
<h3>
<a href="<?= Yii::$app->homeUrl ?>blog/<?= $item['slug']; ?>"
class="text-capitalize"><?= $item['title']; ?></a>
</h3>
<p>
<?= $item['short_text']; ?>
</p>
</div>
</div>
<?php endforeach; ?>
<div class="row">
<div class="col-xs-12 text-center">
<?= widgets\LinkPager::widget(['pagination' => $pagination]); ?>
</div>
</div>
</div>
<?php endif; ?>
</section><file_sep><?php
/**
* Created by PhpStorm.
* User: User
* Date: 12/27/2016
* Time: 2:25 PM
*/
namespace backend\controllers;
use backend\models\SitesControl;
use backend\models\SubmitDataControl;
use common\models\DataLog;
use common\models\PremiumUpdateStage;
use yii\base\Controller;
use common\models\SubmitData;
use common\models\Sites;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
class AdsController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionGetData() {
$is_top = \Yii::$app->request->get('is_top');
if($is_top){
$sites = SitesControl::getTopSites();
}else{
$sites = SitesControl::getSites();
}
$getSubmitData = SubmitDataControl::getSubmitData();
return $this->render('get-data', [
'sites' => $sites,
'getSubmitData' => $getSubmitData
]);
}
public function actionGetPremiumData(){
$premiumSubmitData = SubmitDataControl::getPremiumSubmitData();
return $this->render('get-premium-data', [
'premiumSubmitData' => $premiumSubmitData
]);
}
public function actionGetPremiumUpdateStage(){
$premiumUpdateStage = PremiumUpdateStage::find()->asArray()->one();
die(json_encode($premiumUpdateStage));
}
public function actionMail() {
return $this->render('mail');
}
public function actionLog() {
$data_log = new DataLog();
$postRequest = \Yii::$app->request->get();
$data_id = $postRequest['data_id'];
$site = $postRequest['site'];
$login = isset($postRequest['login']) ? $postRequest['login'] : NULL;
$email = isset($postRequest['email']) ? $postRequest['email'] : NULL;
$pass = isset($postRequest['login']) ? $postRequest['login'] : NULL;
$status = $postRequest['status'];
$db_data = SubmitData::find()->select('login, pass, email')->where(['id' => $data_id])->asArray()->one();
$site_id = Sites::find()->select('id')->where("url LIKE '%$site%'")->asArray()->one();
if ($status == '1') {
if (!$login) {
$login = $db_data['login'];
}
if (!$email) {
$email = $db_data['email'];
}
if (!$pass) {
$pass = $db_data['pass'];
}
}
$data_log->submit_data_id = $data_id;
$data_log->email = $email;
$data_log->login = $login;
$data_log->pass = $pass;
$data_log->site_id = $site_id;
$data_log->status = "$status";
// $data_log->save();
// \Yii::$app->db->createCommand("
//INSERT INTO `data_log`(`submit_data_id`, `site_id`, `email`, `login`, `pass`, `status`) VALUES
//($data_id, $site_id, $email, $login, $pass, $status)")->execute();
return $this->render('log');
}
}
<file_sep>//http://www.rent24.ca/?view=post&cityid=84&lang=en&catid=9
//http://www.rent24.ca/?view=post&cityid=84&lang=en&catid=9&subcatid=4
//http://www.rent24.ca/index.php?view=post&cityid=84&lang=en&catid=9&subcatid=4&adid=0&imgid=0&countryid=0&areaid=0&pos=0&picid=0&page=0&foptid=0&eoptid=0&pricemin=0&pricemax=0&
//http://www.rent24.ca/?view=activate&type=ad&adid=4692&codemd5=5d02e5eb349721d520c424d16b5d8d20&cityid=84
//http://www.rent24.ca/84/posts/9/4/4695.html
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'http://www.rent24.ca/?view=post&cityid=84&lang=en&catid=9') {
selectSubcategory();
}else if (url.indexOf('&subcatid') + 1 && !(url.indexOf('/index.php?view=post') + 1) ) {
setTimeout(function () {
addPost();
}, 2000);
}else if (url.indexOf('?view=activate') + 1 && $('#content').length > 0) {
$('#content').find('a').each(function () {
if($(this).attr('href').search('posts') +1){
window.location.href = $(this).attr('href');
}
});
}else if(url.indexOf('posts') + 1){
nextSite(true);
}else {
nextSite(false);
}
function selectSubcategory() {
chrome.storage.local.get('ads', function (data) {
switch (data.ads.house_type) {
case 'House':
case 'Apartment':
$('.postcats').find('li a').each(function () {
if ($(this).text().toLowerCase() == data.ads.house_type.toLowerCase()) {
$(this)[0].click();
}
});
break;
default:
$('.postcats').find('li a').each(function () {
if ($(this).text().toLowerCase() == 'other') {
$(this)[0].click();
}
});
}
/**/
$('[id=textTitle]').click();
$('[id=textTitle]').val(data.ads.title);
});
}
function addPost() {
chrome.storage.local.get('ads', function (data) {
addCaptcha();
/**/
$('[name=adtitle]').click();
$('[name=adtitle]').val(data.ads.title);
$("[name=adtitle]")[0].dispatchEvent(new Event('change'));
/**/
$('[name=area]').click();
$('[name=area]').val(data.ads.street + ' ' + data.ads.address);
$("[name=area]")[0].dispatchEvent(new Event('change'));
/**/
$('[name=addesc]').click();
$('[name=addesc]').val(data.ads.content);
$("[name=addesc]")[0].dispatchEvent(new Event('change'));
/**/
$('[name=price]').click();
$('[name=price]').val(data.ads.rent);
$("[name=price]")[0].dispatchEvent(new Event('change'));
/******CHOOSE SELECT OPTIONS******/
if (data.ads.bedroom < 10) {
selector($('[name="x[1]"]'), data.ads.bedroom);
} else {
selector($('[name="x[1]"]'), '10+');
}
if (data.ads.bathroom < 10) {
selector($('[name="x[2]"]'), data.ads.bathroom);
} else {
selector($('[name="x[2]"]'), '10+');
}
if (data.ads.parking_count < 10) {
selector($('[name="x[3]"]'), data.ads.parking_count);
} else {
selector($('[name="x[3]"]'), '10+');
}
for (let key in data.ads.apartment_amenities) {
switch (data.ads.apartment_amenities[key]) {
case 'Fireplace':
selector($('[name="x[5]"]'), '1');
break;
case 'A/C':
selector($('[name="x[6]"]'), 'Yes');
break;
case 'Pool':
selector($('[name="x[7]"]'), 'Yes');
break;
case 'Furniture':
selector($('[name="x[8]"]'), 'Yes');
break;
case 'Utilities Included':
selector($('[name="x[10]"]'), 'Included');
break;
}
}
if (data.ads.pets == '1') {
selector($('[name="x[9]"]'), 'Yes');
}
$('[name=email]').click();
$('[name=email]').val(data.ads.email);
$("[name=email]")[0].dispatchEvent(new Event('change'));
$('[name=showemail][value="1"]').prop('checked', true);
$('[name=agree]').prop('checked', true);
});
}
function addCaptcha() {
captcha($('[name=captcha]').parent().find('img'), $('[name=captcha]'), {phrase: 0, regsense: 1}, function () {
addPhoto();
});
}
function addPhoto() {
getImages(function (images) {
var limit = images.length <= 5 ? images.length : 5;
var formData = new FormData();
$.each($('[name=frmPost]').find('input'), function () {
if (($(this).attr('type') != 'checkbox' && $(this).attr('type') != 'radio' && $(this).attr('type') != 'file') || ($(this).attr('type') == 'checkbox' && $(this).is(':checked')) || ($(this).attr('type') == 'radio' && $(this).is(':checked')))
formData.append($(this).attr('name'), $(this).val());
});
$.each($('[name=frmPost]').find('textarea'), function () {
formData.append($(this).attr('name'), $(this).val());
});
$.each($('[name=frmPost]').find('select'), function () {
formData.append($(this).attr('name'), $(this).val());
});
for (i = 0; i < limit; i++) {
formData.append('pic[]', images[i].file, images[i].name)
}
var xhr = new XMLHttpRequest();
xhr.open('post', $('[name=frmPost]').attr('action'), true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
getMail('<EMAIL>', function () {
var pattern = /https?:\/\/w{0,3}\.rent24\.ca\/\?view=activate[^\n\r\t\s]+/igm;
var forClick = pattern.exec($('#gh-mail-respons').html())[0].replace(/&/g, '&').replace(/®/g, '®');
window.location.href = forClick;
}, 300, true);
}
};
xhr.send(formData);
});
}
});
<file_sep><?php
use yii\bootstrap\ActiveForm;
?>
<div class="entry-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="home_top_section">
<h1>
<?= Yii::t('app', 'Accelerated Marketing for Residential and Commercial Real Estate') ?>
</h1>
</div>
</div>
</div>
<div class="topslidersection">
<div class="row">
<div class="col-md-6">
<div class="padding-section">
<iframe src="https://player.vimeo.com/video/192368255?title=0&byline=0&portrait=0" width="100%" height="358" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
<div class="col-md-6">
<div class="top-slider-content padding-right-section">
<h2>
<?= Yii::t('app', 'Extend the reach of your marketing effortlessly!') ?>
</h2>
<div class="size">
<p class="MsoNormal" style="box-sizing: border-box; margin: 0px 0px 10px;">
<?= Yii::t('app', 'With just one click, AUF Posting will:') ?>
</p>
<ul style="box-sizing: border-box; margin-top: 10px; margin-bottom: 10px; padding-left: 23px;">
<li style="box-sizing: border-box; list-style: none outside none; margin-bottom: 10px;">
<?= Yii::t('app', 'Automatically publish your rental listing to our syndicated network of OVER 40 websites (and counting)') ?>
</li>
<li style="box-sizing: border-box; list-style: none outside none; margin-bottom: 10px;">
<?= Yii::t('app', 'Reach over 500 thousand monthly targeted visitors across the web.') ?>
</li>
<li style="box-sizing: border-box; list-style: none outside none; margin-bottom: 10px;">
<?= Yii::t('app', 'Help you fill your vacancies with ease.') ?>
</li>
</ul>
</div>
</div>
<br>
<div class="col-xs-12">
<div class="col-xs-12 col-sm-6" style="padding-top: 20px; padding-bottom: 20px;">
<span class="promo-btn-m">
<a href="<?= Yii::$app->homeUrl ?>main/sign-up">
<?= Yii::t('app', 'Get Started') ?>
</a>
</span>
</div>
<div class="col-xs-12 col-sm-6">
<a href="<?= Yii::$app->homeUrl ?>main/sign-up">
<img src="<?= Yii::$app->homeUrl?>img/icons-01.png" width="200px">
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="success" id="success">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>
<?= Yii::t('app', 'AUF Posting focuses solely on your success') ?>
</h2>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="success-detail">
<div class="success-detail-img">
<img src="<?= Yii::$app->homeUrl?>img/boarding.png" alt="">
</div>
<div class="success-content">
<h2>
<?= Yii::t('app', 'Effortless Onboarding') ?>
</h2>
<p class="MsoNormal">
<?= Yii::t('app', 'A few simple clicks to provide basic information will get all of your leasing opportunities ready to go; making it easy for you to start generating interest immediately.Getting your rental listing rented has never been so easy.') ?>
</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="success-detail">
<div class="success-detail-img">
<img src="<?= Yii::$app->homeUrl?>img/marketing3.png" alt="">
</div>
<div class="success-content">
<h2>
<?= Yii::t('app', 'Marketing<br>Expertise') ?>
</h2>
<p class="MsoNormal">
<?= Yii::t('app', 'Whether you need professional photography, customized content or would like to discuss the right tools and strategies to generate the most interest for your leasing opportunities; our experts are ready to help you.') ?>
</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="success-detail">
<div class="success-detail-img">
<img src="<?= Yii::$app->homeUrl?>img/megaphone_icon (2).jpg" alt="">
</div>
<div class="success-content">
<h2>
<?= Yii::t('app', 'Customer<br>Service') ?>
</h2>
<p class="MsoNormal">
<?= Yii::t('app', 'Our goal is to ensure that you get the full potential of the AUF Posting Platform. Our support team will answer any questions that you may have.') ?>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clients">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>
<?= Yii::t('app', 'A few of our Partners') ?>
</h2>
<div class="clients-list">
<img class="hidden-sm hidden-xs" src="<?= Yii::$app->homeUrl ?>img/section.jpg" alt="partners" width="100%">
<br>
<div id="myCarousel" class="carousel slide visible-sm visible-xs" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="item active">
<p class="text-center" style="padding: 50px 5px;">
<img src="<?= Yii::$app->homeUrl?>img/kijiji-logo.png" alt="kijiji" width="300px" height="100px">
</p>
</div>
<div class="item">
<p class="text-center" style="padding: 50px 5px;">
<img src="<?= Yii::$app->homeUrl?>img/craigslist-logo.png" alt="craigslist" width="300px" height="100px">
</p>
</div>
<div class="item">
<p class="text-center" style="padding: 50px 5px;">
<img src="<?= Yii::$app->homeUrl?>img/facebook.png" alt="facebook" width="300px" height="100px">
</p>
</div>
<div class="item">
<p class="text-center" style="padding: 50px 5px;">
<img src="<?= Yii::$app->homeUrl?>img/McGill_Wordmark.png" alt="McGill_Wordmark" width="300px" height="100px">
</p>
</div>
<div class="item">
<p class="text-center" style="padding: 50px 5px;">
<img src="<?= Yii::$app->homeUrl?>img/Concordia_University_logo.png" alt="Concordia_University" width="300px" height="100px">
</p>
</div>
<div class="item">
<p class="text-center" style="padding: 50px 5px;">
<img src="<?= Yii::$app->homeUrl?>img/Kangalou-Couleur-RGB.png" alt="Kangalou-Couleur" width="300px" height="100px">
</p>
</div>
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<br>
</div>
</div>
</div>
</div>
</div>
<div class="promo-button" id="contact_us">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="promo-btn-m">
<a href="#contact-popup" data-toggle="modal" data-target="">
<?= Yii::t('app', 'Contact Us') ?>
</a>
</div>
</div>
</div>
</div>
</div>
<div id="contact-popup" class="modal fade" role="dialog" aria-labelledby="myModalLabel" tabindex="-1">
<div class="contact-pop-m">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="contact_form">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3><?= Yii::t('app', 'Contact Us') ?></h3>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, "name")->textInput(["placeholder" => Yii::t('app', 'Name')])->label(false) ?>
<?= $form->field($model, "email")->textInput(["placeholder" => Yii::t('app', 'Email')])->label(false) ?>
<?= $form->field($model, "subject")->textInput(["placeholder" => Yii::t('app', 'Subject')])->label(false) ?>
<?= $form->field($model, "body")->textarea(["placeholder" => Yii::t('app', 'Message')])->label(false) ?>
<div class="g-recaptcha" data-sitekey="6Ld33BsUAAAAAHf-q3ng7oqaxsvI1F96YsQeNkeM"></div>
<div class="helper-block success_e">
<?php if(isset($errorMsg)){ ?>
<script>
setTimeout(function () {
$('#contact-popup').modal('show');
}, 1000);
</script>
<?php echo $errorMsg; } ?>
</div>
<?= \yii\helpers\Html::submitButton(Yii::t('app', 'Send'),['class'=>'btn'])?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
</div>
</div><file_sep><?php
$query = new \yii\db\Query();
$query->select([
'user.username',
])
->from('user')
->where(['id' => Yii::$app->user->identity->id])
->one();
$command = $query->createCommand();
$data = $command->queryAll();
?>
<aside class="main-sidebar">
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<img src="<?= Yii::$app->homeUrl . 'images/default.png' ?>" class="img-circle" alt="Admin_Image"/>
</div>
<div class="pull-left info">
<p>
<?= Yii::t('app','Admin') ?>
</p>
<p>
<i class="fa fa-circle text-success"></i>
<?= Yii::t('app','Online') ?>
</p>
</div>
</div>
<?= dmstr\widgets\Menu::widget(
[
'options' => ['class' => 'sidebar-menu'],
'items' => [
['label' => Yii::t('app','Visit Site'), 'icon' => 'fa fa-link', 'url' => ['../../frontend/web/']],
['label' => Yii::t('app','Dashboard'), 'icon' => 'fa fa-dashboard', 'url' => ['/site/']],
['label' => Yii::t('app','Coupons'), 'icon' => 'fa fa-id-card-o', 'url' => ['/coupons/index'], 'active' => Yii::$app->controller->id == 'coupons'],
['label' => Yii::t('app','Payments'), 'icon' => 'fa fa-paypal', 'url' => ['/payments/index'], 'active' => Yii::$app->controller->id == 'payments'],
['label' => Yii::t('app','Payment Details'), 'icon' => 'fa fa-money', 'url' => ['/payment-details/index'], 'active' => Yii::$app->controller->id == 'payment-details'],
['label' => Yii::t('app','Package Duration'), 'icon' => 'fa fa-clock-o', 'url' => ['/package-duration/index'], 'active' => Yii::$app->controller->id == 'package-duration'],
['label' => Yii::t('app','Blog'), 'icon' => 'fa fa-rss', 'url' => ['/blog/index'], 'active' => Yii::$app->controller->id == 'blog'],
['label' => Yii::t('app','Listing Section'), 'icon' => 'fa fa-puzzle-piece', 'url' => ['/listing-section/index'], 'active' => Yii::$app->controller->id == 'listing-section'],
['label' => Yii::t('app','Submit Data'), 'icon' => 'fa fa-database', 'url' => ['/submit-data/index'], 'active' => Yii::$app->controller->id == 'submit-data'],
['label' => Yii::t('app','Apartment Amenities'), 'icon' => 'fa fa-building', 'url' => ['/apartment-amenities/index'], 'active' => Yii::$app->controller->id == 'apartment-amenities'],
['label' => Yii::t('app','Data Log'), 'icon' => 'fa fa-table', 'url' => ['/data-log/index'], 'active' => Yii::$app->controller->id == 'data-log'],
['label' => Yii::t('app','House Type'), 'icon' => 'fa fa-home', 'url' => ['/house-type/index'], 'active' => Yii::$app->controller->id == 'house-type'],
['label' => Yii::t('app','Location'), 'icon' => 'fa fa-map-marker', 'url' => ['/location/index'], 'active' => Yii::$app->controller->id == 'location'],
['label' => Yii::t('app','Sites'), 'icon' => 'fa fa-sitemap', 'url' => ['/sites/index'], 'active' => Yii::$app->controller->id == 'sites'],
['label' => Yii::t('app','Update Stage'), 'icon' => 'fa fa-clock-o', 'url' => ['/premium-update-stage/index'], 'active' => Yii::$app->controller->id == 'premium-update-stage'],
],
]
) ?>
</section>
</aside>
<file_sep>//https://elistr.com/index.php?a=cart&action=new&main_type=classified
//http://elistr.com/index.php?a=cart&action=process&main_type=classified&step=classified%3Acategory&b=232
//http://elistr.com/index.php?a=cart&action=process&main_type=classified&step=classified%3Acategory&b=232&c=terminal
//https://elistr.com/index.php?a=cart&action=process&main_type=classified&step=classified%3Acategory&b=232&c=terminal&uploaded
//http://elistr.com/index.php?a=cart&action=process&main_type=classified&step=combined
//http://elistr.com/index.php?a=cart&action=process&main_type=classified&step=classified%3Aanonymous
//http://elistr.com/index.php?a=cart&action=process&main_type=classified&step=other_details
/* global chrome */
jQuery(document).ready(function ($) {
var url = String(window.location.href).replace(/\/$/, '');
if (url == 'https://elistr.com/index.php?a=cart&action=new&main_type=classified') {
deleteAllCookies();
window.location.href = '//elistr.com/index.php?a=cart&action=process&main_type=classified&step=classified%3Acategory&b=232&c=terminal';
}else if (url.indexOf('&step=classified%3Acategory&b=232&c=terminal') + 1 && url.indexOf('&uploaded') + 1 == false) {
addPhoto();
}else if(url.indexOf('&step=classified%3Acategory&b=232&c=terminal') + 1 && url.indexOf('&uploaded') + 1){
addInfo();
}else if (url.indexOf('&step=combined') + 1) {
termsOfUse();
}else if (url.indexOf('&step=classified%3Aanonymous') + 1) {
/*********FINISH**********/
/*-->*/$('form').find('[type=submit]').click();
}else if (url.indexOf('&step=other_details') + 1) {
nextSite(true);
}else {
nextSite(false);
}
function addInfo() {
chrome.storage.local.get('ads', function (data) {
/**/ $('[id=classified_length]').click();
$('[id=classified_length]').val("30");
/**/ $('[id=classified_title]').click();
$('[id=classified_title]').val(data.ads.title);
/**/ $('[id=main_description]').click();
$('[id=main_description]').val(data.ads.content);
/**/ $('[id=price]').click();
$('[id=price]').val(data.ads.rent);
/**/ $('[id=currency_type]').click();
$('[id=currency_type]').val('12');
/**/ $('[id=email_option]').click();
$('[id=email_option]').val(data.ads.email);
/**/ $('[name^=geoRegion_location]').click();
$('[name^=geoRegion_location]').val('3');
/**/ $('[id=mapping_location]').click();
$('[id=mapping_location]').val(data.ads.city);
/*-->*/$('[id=combined_form]').find('[type=submit]').click();
});
}
function termsOfUse() {
chrome.storage.local.get('ads', function (data) {
/**/ $("[type=checkbox][value='1']").click();
/*-->*/$('form').find('[type=submit]').click();
});
}
function addPhoto() {
getImages(function (images) {
_uploadeimage(0);
function _uploadeimage(i = 0) {
var data = new FormData();
data.append('name', images[i].name);
data.append('filename', images[i].name);
data.append('file', images[i].file, 'blob', images[i].file);
var xhr = new XMLHttpRequest();
xhr.open('post', '//elistr.com/AJAX.php?controller=UploadImage&action=upload&adminId=0&userId=0&ua=Mozilla%2F5.0+%28Windows+NT+10.0%3B+WOW64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F57.0.2940.0+Safari%2F537.36', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var response = JSON.parse(xhr.responseText);
if (++i < images.length) {
_uploadeimage(i);
}else{
window.location.href = url+'&uploaded';
}
}
};
xhr.send(data);
}
});
}
});
<file_sep><?php
namespace common\models;
use Yii;
/**
* This is the model class for table "data_log".
*
* @property string $id
* @property string $submit_data_id
* @property string $email
* @property string $login
* @property string $pass
* @property string $site_id
* @property string $status
*/
class DataLog extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'data_log';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['submit_data_id', 'site_id'], 'required'],
[['submit_data_id', 'site_id'], 'integer'],
[['status'], 'string'],
[['email'], 'string', 'max' => 100],
[['login', 'pass'], 'string', 'max' => 60],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'submit_data_id' => Yii::t('app', 'Submit Data ID'),
'email' => Yii::t('app', 'Email'),
'login' => Yii::t('app', 'Login'),
'pass' => Yii::t('app', '<PASSWORD>'),
'site_id' => Yii::t('app', 'Site ID'),
'status' => Yii::t('app', 'Status'),
];
}
}
<file_sep><?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'image' => [
'class' => 'yii\image\ImageDriver',
'driver' => 'GD', //GD or Imagick
],
'paypal'=> [
'class' => 'kongoon\yii2\paypal\Paypal',
'clientId' => '<KEY>',
'clientSecret' => '<KEY>',
'isProduction' => true,
// This is config file for the PayPal system
'config' => [
'http.ConnectionTimeOut' => 30,
'http.Retry' => 1,
'mode' => \kongoon\yii2\paypal\Paypal::MODE_LIVE, // sandbox | live
'log.LogEnabled' => YII_DEBUG ? 1 : 0,
'log.FileName' => '@runtime/logs/paypal.log',
'log.LogLevel' => \kongoon\yii2\paypal\Paypal::LOG_LEVEL_FINE, // FINE | INFO | WARN | ERROR
]
],
],
];
<file_sep><?php
/**
$mbox = imap_open('{mail.ghost-services.com:143/novalidate-cert}INBOX', '<EMAIL>', 'FvO{k-_%~ruZ');
echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{imap.ghost-services.com:143}", "*");
if ($folders == false) {
echo "Call failed<br />\n";
} else {
foreach ($folders as $val) {
echo $val . "<br />\n";
}
}
echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);
if ($headers == false) {
echo "Call failed<br />\n";
} else {
foreach ($headers as $val) {
echo $val . "<br />\n";
}
}
imap_close($mbox);
exit;
*/
set_time_limit(0);
class Mail {
private $from;
private $time_ago;
private $imap;
private $email;
private $pass;
public function __construct() {
$this->from = isset($_REQUEST['from']) ? $_REQUEST['from'] : die('!!! Error');
$this->email = isset($_REQUEST['email']) ? $_REQUEST['email'] : die('!!! Error');
$this->pass = isset($_REQUEST['pass']) ? $_REQUEST['pass'] : die('!!! Error');
$this->time_ago = isset($_REQUEST['time_ago']) && (int) $_REQUEST['time_ago'] > 0 ? (int) $_REQUEST['time_ago'] : 300;
$this->getImapData($this->email, $this->pass);
}
private function getImapData($email, $pass) {
$email_arr = explode('@', $email);
$user_name = $email_arr[0];
$domen = $email_arr[1];
switch ($domen) {
case 'gmail.com': $mailbox = "{imap.gmail.com:993/imap/ssl/novalidate-cert}";
break;
case 'mail.ru': $mailbox = "{imap.mail.ru:143/imap}INBOX";
break;
case 'hotmail.com': case 'outlook.com': $mailbox = "{imap-mail.outlook.com:993/imap/ssl}";
break;
case 'ghost-services.com': $mailbox = "{mail.ghost-services.com:143/novalidate-cert}INBOX";
break;
default : die('!!! Not Supported Email');
}
$this->imap = imap_open($mailbox, $email, $pass);
if ($this->imap) {
$this->gatMail(60); //TODO change time to 300
} else {
die('!!! Error');
}
}
private function gatMail($limit) {
$i = 0;
$data = '';
$date = date('d-M-Y G\:i', time() - $this->time_ago);
$mail_ids = imap_search($this->imap, 'FROM ' . $this->from . ' SINCE "' . $date . '"');
if ($mail_ids) {
foreach ($mail_ids as $mail_id) {
$mail = isset($_REQUEST['utf8']) ? utf8_encode(imap_body($this->imap, $mail_id)) : imap_qprint(imap_body($this->imap, $mail_id));
$data .= '<span data-id="' . $i++ . '">' . $mail . '</span>' . PHP_EOL;
}
die($data);
} elseif ($limit > 0) {
sleep(2);
$this->gatMail(--$limit);
} else {
die('!!! Empty');
}
}
}
new Mail();
<file_sep><?php
return [
'adminEmail' => '<EMAIL>',
'image' => Yii::getAlias('@frontend') . '/web/img/upload/',
];
<file_sep><?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use frontend\assets\AppAsset;
use common\widgets\Alert;
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
<script type='text/javascript' src='https://ssl.p.jwpcdn.com/6/6/jwplayer.js'></script>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => 'My Company',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'About', 'url' => ['/site/about']],
['label' => 'Contact', 'url' => ['/site/contact']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Signup', 'url' => ['/site/signup']];
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
} else {
$menuItems[] = '<li>'
. Html::beginForm(['/site/logout'], 'post')
. Html::submitButton(
'Logout (' . Yii::$app->user->identity->username . ')',
['class' => 'btn btn-link logout']
)
. Html::endForm()
. '</li>';
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
]);
NavBar::end();
?>
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= Alert::widget() ?>
<?= $content ?>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">© My Company <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
<!----menu-slider------>
<script src="js/slick-min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/slick.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.testimonial-slider').slick({
centerMode: true,
centerPadding: '0px',
slidesToShow: 1,
autoplay: true,
arrows: true,
dots:false,
responsive: [
{
breakpoint: 1024,
settings: {
arrows: false,
centerMode: true,
centerPadding: '0px',
slidesToShow: 1
}
},
{
breakpoint: 800,
settings: {
arrows: false,
centerMode: true,
centerPadding: '0px',
slidesToShow: 1
}
}
]
});
$('.client-slider').slick({
centerMode: true,
centerPadding: '0px',
slidesToShow: 3,
autoplay: true,
arrows: false,
dots:false,
responsive: [
{
breakpoint: 1024,
settings: {
arrows: false,
centerMode: true,
centerPadding: '0px',
slidesToShow: 3
}
},
{
breakpoint: 800,
settings: {
arrows: false,
centerMode: true,
centerPadding: '0px',
slidesToShow: 1
}
}
]
});
});
</script>
<script type="text/javascript">
jwplayer("player").setup({
playlist: [{
sources: [{
file: "frontend/web/video/video.mp4"
}]
}],
width: 500,
height:350,
autostart: 'true',
stretching: "fill",
});
jwplayer().onComplete(function() {
var el = document.createElement("div");
var el2 = document.createElement("div");
var el3 = document.createElement("div");
var el4 = document.createElement("div");
var txt = document.createElement('a');
if (jwplayer().getRenderingMode() == "html5"){
var theBody = document.getElementById(player.id);
} else {
var theBody = document.getElementById(player.id+"_wrapper");
}
var playerWidthPX2 = theBody.style.width;
var playerWidthPX = parseFloat(playerWidthPX2);
var playerHeightPX2 = theBody.style.height;
var playerHeightPX = parseFloat(playerHeightPX2);
el3.setAttribute('id', 'bg');
el3.style.height = playerHeightPX + "px";
el3.style.width = playerWidthPX2;
el3.style.background = "#333333";
el3.style.opacity = "0.70";
el3.style.position = "absolute";
el3.style.backgroundImage="url('')";
el.setAttribute('src', '');
if (jwplayer().getRenderingMode() == "html5"){
} else {
el3.style.top = playerHeightPX-playerHeightPX+"px";
}
el3.style.zIndex = "999";
el3.width = playerWidthPX;
el3.height = playerHeightPX;
el2.setAttribute('id', 'bg2');
el2.style.height = playerHeightPX + "px";
el2.style.width = playerWidthPX2;
el2.style.position = "absolute";
el2.style.zIndex = "999";
el2.width = playerWidthPX;
el2.height = playerHeightPX;
theBody.appendChild(el3);
theBody.appendChild(el2);
el2.style.textAlign = "center";
el2.style.left = ((playerWidthPX*2)/6) -"5" + "px";
el2.style.top = ((playerHeightPX*3)/6) -"30" + "px";
el.setAttribute('id', 'hyperlink');
el.style.height = "30px";
el.style.width = "30px";
el2.width = "30";
el2.height = "30";
el.style.position = "relative";
el.setAttribute('frameBorder', '0');
el.style.top = "11px";
el.style.left = "202px";
el.style.textAlign = "center";
el.style.marginBottom = "-16px";
el.style.marginRight = "8px";
var message = '';
txt.innerHTML = message;
txt.href = ""
txt.target = "_blank";
txt.style.textDecoration = "none";
txt.style.outline = "0";
txt.style.MozUserSelect = 'none';
txt.style.KhtmlUserSelect = 'none';
txt.style.WebkitUserSelect = 'none';
txt.style.OUserSelect = 'none';
txt.style.UserSelect = 'none';
txt.style.fontSize = "18px";
txt.style.fontWeight = "600";
txt.style.color = "#fff"
txt.style.backgroundColor = "#008080"
txt.style.textAlign = "center"
txt.style.padding = "8px 20px"
txt.style.position = "absolute";
txt.style.marginLeft = "auto";
txt.style.marginTop = "4px";
txt.style.fontFamily = "arial,_sans";
txt.setAttribute('id', 'txt');
el4.setAttribute('id', 'replay');
el4.style.height = "20px";
el4.style.width = "20px";
el4.height = "20";
el4.width = "20";
el4.style.position = "absolute";
el4.style.top = "-" + playerHeightPX/2 + "px";
el4.style.marginTop = "50px";
el4.style.left = playerWidthPX/2 + "px";
el4.style.marginLeft = "50px";
el4.style.backgroundImage="url('replay.png')";
el4.setAttribute('src', 'replay.png');
el2.appendChild(txt);
el2.appendChild(el);
el2.appendChild(el4);
el.style.backgroundImage="url('hyperlink.png')";
el.setAttribute('src', 'hyperlink.png');
el.style.cursor = "pointer";
el.style.display = "table";
el2.style.display = "table";
el3.style.display = "table";
el4.style.display = "table";
txt.style.display = "table";
el.onmouseup = function(){
window.open("frontend/web/video/video.mp4");
}
el4.style.cursor = "pointer";
el4.onmouseup = function(){
el.style.display = "none";
el2.style.display = "none";
el3.style.display = "none";
el4.style.display = "none";
txt.style.display = "none";
jwplayer().play();
}
});
</script>
| 3232aab39d29e70b055cf3d886f687176a4c1c66 | [
"JavaScript",
"Markdown",
"PHP",
"INI"
]
| 86 | JavaScript | aufposting/webpage | 8afffa8c0965927539edc2bb03276f8665549138 | 4d551b81898aeac251154bc95f1004c4c5b0aa12 |
refs/heads/master | <repo_name>youpong/cflat<file_sep>/src/main/java/cflat/ast/UnaryOpNode.java
package cflat.ast;
import cflat.type.Type;
// TODO: implement
/**
* unary operator "+", "-", "!", "~"
*/
public class UnaryOpNode extends ExprNode {
protected String operator;
protected ExprNode expr;
public UnaryOpNode(String op, ExprNode expr) {
this.operator = op;
this.expr = expr;
}
public String operator() {
return operator;
}
public Type type() {
return expr.type();
}
public ExprNode expr() {
return expr;
}
public Location location() {
return expr.location();
}
public void _dump(Dumper d) {
d.printMember("operator", operator);
d.printMember("expr", expr);
}
public <S, E> E accept(ASTVisitor<S, E> visitor) {
return visitor.visit(this);
}
}
<file_sep>/str/test_str_decode.c
/*
* unit test for str_decode()
*/
#include <stdio.h>
#include <string.h>
#include "lex.yy.h"
#include "main.h"
#include "util.h"
static void test_routine(int num, char *src, int de_len, char* de_str) {
char *dst;
dst = str_decode(src);
expect(num, de_len, strlen(dst));
expect_str(num, de_str, dst);
}
void test_str_decode() {
test_routine(__LINE__, "", 0, "");
test_routine(__LINE__, "a", 1, "a");
test_routine(__LINE__, "ab", 2, "ab");
test_routine(__LINE__, "\\", 1, "\134");
test_routine(__LINE__, "\\\"", 1, "\042");
test_routine(__LINE__, "\\n", 1, "\012");
test_routine(__LINE__, "\\t", 1, "\011");
test_routine(__LINE__, "\\127", 1, "W");
}
<file_sep>/as/13_1/README.md
# FILES
* Makefile: This file.
* hello.s: chapter 13.1 original hello.s (for x86)
* Hello.c: equivalent in c source to assembly hello.s
* hello64.asm: gas AT&T syntax for x86-64
* hello64_intel.asm: gas Intel syntax for x86-64
* hello_cflat.asm: assembly which cflat compiles hello.cb
# How to build
```
$ make hello
...
file hello.o
hello.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), with debug_info, not stripped
...
```
# How to debug
To debug type like bellow.
```
$ gdb ./hello
```
# How to output assembly in various Arch, style
produce assembly code in various arch, style from Hello.c, sample C source.
```
$ make all_assembly
```
produce
* Hello64_intel.s: intel style for x86-64
* Hello64_att.s att style for x86-64
* Hello32_intel.s intel style for x86
* Hello32_att.s att style for x86
# URLs
PIE
* https://stackoverflow.com/questions/52344336/gas-asm-pie-x86-64-access-variable-with-lea-instruction
<file_sep>/sample/lvar.cb
// -*- mode: c; -*-
int main(void) {
int lvar = 42;
return lvar;
}
<file_sep>/src/main/java/cflat/sysdep/amd64/Register.java
package cflat.sysdep.amd64;
import cflat.asm.SymbolTable;
import cflat.asm.Type;
// TODO: implement
public class Register extends cflat.asm.Register {
Type type;
RegisterClass _class;
public Register(RegisterClass _class, Type type) {
// TODO Auto-generated constructor stub
this._class = _class;
this.type = type;
}
@Override
public String toSource(SymbolTable table) {
// TODO Auto-generated method stub
return null;
}
@Override
public String dump() {
// TODO Auto-generated method stub
return null;
}
public Register forType(Type naturalType) {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>/sample/cbc
#!/bin/bash
base_dir=${0%%/*}
java -jar ${base_dir}/../target/cbc-0.1-SNAPSHOT.jar "$@"
#for i in "$@"; do
#echo $i
#done<file_sep>/src/main/java/cflat/ir/Op.java
package cflat.ir;
/**
* 中間表現の演算子
*/
public enum Op {
/** 加算(+) */
ADD,
/** 減算(-) */
SUB,
/** 乗算(*) */
MUL,
/** 符号付き除算(/) */
S_DIV,
/** 符号なし除算(/) */
U_DIV,
/** 符号付き剰余(%) */
S_MOD,
/** 符号なし剰余(%) */
U_MOD,
/** ビット単位の論理積(&) */
BIT_AND,
/** ビット単位の論理和(|) */
BIT_OR,
/** ビット単位の排他的論理和(^) */
BIT_XOR,
/** 左シフト (符号なしシフト <<) */
BIT_LSHIFT,
/** 右シフト (符号なしシフト >>) */
BIT_RSHIFT,
/** 算術右シフト (符号付きシフト >>) */
ARITH_RSHIFT,
/** 比較 (==) */
EQ,
/** 比較 (!=) */
NEQ,
/** 符号付き数値の比較 (>) */
S_GT,
/** 符号付き数値の比較 (>=) */
S_GTEQ,
/** 符号付き数値の比較 (<) */
S_LT,
/** 符号付き数値の比較 (<=) */
S_LTEQ,
/** 符号なし数値の比較 (>) */
U_GT,
/** 符号なし数値の比較 (>=) */
U_GTEQ,
/** 符号なし数値の比較 (<) */
U_LT,
/** 符号なし数値の比較 (<=) */
U_LTEQ,
/** 符号反転 (-) */
UMINUS,
/** ビット単位の否定 (~) */
BIT_NOT,
/** 論理否定 (!) */
NOT,
/** 符号付き数値のキャスト */
S_CAST,
/** 符号なし数値のキャスト */
U_CAST;
static public Op internBinary(String op, boolean isSigned) {
if (op.equals("+")) {
return Op.ADD;
} else if (op.equals("-")) {
return Op.SUB;
} else if (op.equals("*")) {
return Op.MUL;
} else if (op.equals("/")) {
return isSigned ? Op.S_DIV : Op.U_DIV;
} else if (op.equals("%")) {
return isSigned ? Op.S_MOD : Op.U_MOD;
} else if (op.equals("&")) {
return Op.BIT_AND;
} else if (op.equals("|")) {
return Op.BIT_OR;
} else if (op.equals("^")) {
return Op.BIT_XOR;
} else if (op.equals("<<")) {
return Op.BIT_LSHIFT;
} else if (op.equals(">>")) {
return isSigned ? Op.ARITH_RSHIFT : Op.BIT_RSHIFT;
} else if (op.equals("==")) {
return Op.EQ;
} else if (op.equals("!=")) {
return Op.NEQ;
} else if (op.equals("<")) {
return isSigned ? Op.S_LT : Op.U_LT;
} else if (op.equals("<=")) {
return isSigned ? Op.S_LTEQ : Op.U_LTEQ;
} else if (op.equals(">")) {
return isSigned ? Op.S_GT : Op.U_GT;
} else if (op.equals(">=")) {
return isSigned ? Op.S_GTEQ : Op.U_GTEQ;
} else {
throw new Error("unknown binary op: " + op);
}
}
static public Op internUnary(String op) {
if (op.equals("+")) {
throw new Error("unary+ should not be in IR");
} else if (op.equals("-")) {
return Op.UMINUS;
} else if (op.equals("~")) {
return Op.BIT_NOT;
} else if (op.equals("!")) {
return Op.NOT;
} else {
throw new Error("unkonw unary op: " + op);
}
}
}
<file_sep>/src/main/java/cflat/ast/PrefixOpNode.java
package cflat.ast;
/**
* Prefix operator "++", "--"
*/
public class PrefixOpNode extends UnaryArithmeticOpNode {
public PrefixOpNode(String op, ExprNode expr) {
super(op, expr);
}
public <S, E> E accept(ASTVisitor<S, E> visitor) {
return visitor.visit(this);
}
}
<file_sep>/str/str_decode.c
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
char *str_decode(char *literal) {
char *p, *q;
char *dst;
dst = (char *)malloc(sizeof(char) * (strlen(literal) + 1));
p = literal;
q = dst;
while(*p != '\0') {
if( *p != '\\' ) {
*q++ = *p++;
continue;
}
/* 以降は '\' でつづく文字列を処理する */
p++;
if(*p == '\0') {
*q++ = '\\';
break;
}
/* \127 */
if ('0' <= *(p + 0) && '7' >= *(p + 0) &&
'0' <= *(p + 1) && '7' >= *(p + 1) &&
'0' <= *(p + 2) && '7' >= *(p + 2) ) {
*q = 0;
for(int i = 0; i < 3; i++) {
*q = *q * 8 + *(p + i) - '0';
}
q++;
p += 3;
continue;
}
/* \, " - literally
n, t - trans
others -
*/
switch(*p) {
case '\\':
*q++ = '\\';
p++;
break;
case '"':
*q++ = '\"';
p++;
break;
case 'n':
*q++ = '\n';
p++;
break;
case 't':
*q++ = '\t';
p++;
break;
default:
*q++ = *p++;
break;
}
}
*q = '\0';
return dst;
}
<file_sep>/as/13_1/Makefile
CFLAGS = -Os
ASFLAGS = -g
.PHONY: all clean
all: hello hello_cflat hello64 hello64_intel
all_assembly: Hello64_intel.s Hello64_att.s Hello32_intel.s Hello32_att.s
clean:
rm -f Hello a.out *.o \
hello hello_cflat hello64 hello64_intel \
Hello64_intel.s Hello64_att.s Hello32_intel.s Hello32_att.s
# hello
hello: hello.o
$(CC) -m32 -o $@ $^
hello.o: hello.s
$(AS) $(ASFLAGS) --32 -o $@ $^
file $@
# hello_cflat
hello_cflat: hello_cflat.o
$(CC) -m32 -o $@ $^
hello_cflat.o: hello_cflat.asm
$(AS) $(ASFLAGS) --32 -o $@ $^
# hello64
hello64.o: hello64.asm
$(AS) $(ASFLAGS) -o $@ $^
file $@
# hello64_intel
hello64_intel.o: hello64_intel.asm
$(AS) $(ASFLAGS) -o $@ $^
file $@
# Hello.s
Hello64_intel.s: Hello.c
$(CC) $(CFLAGS) -m64 -masm=intel -S -o $@ $^
Hello64_att.s: Hello.c
$(CC) $(CFLAGS) -m64 -masm=att -S -o $@ $^
Hello32_intel.s: Hello.c
$(CC) $(CFLAGS) -m32 -masm=intel -S -o $@ $^
Hello32_att.s: Hello.c
$(CC) $(CFLAGS) -m32 -masm=att -S -o $@ $^
<file_sep>/src/main/java/cflat/ir/Assign.java
package cflat.ir;
import cflat.ast.Location;
// TODO: test
/**
* 代入
*/
public class Assign extends Stmt {
/** 代入の左辺 */
protected Expr lhs;
/** 代入の右辺 */
protected Expr rhs;
public Assign(Location loc, Expr lhs, Expr rhs) {
super(loc);
this.lhs = lhs;
this.rhs = rhs;
}
public Expr lhs() {
return lhs;
}
public Expr rhs() {
return rhs;
}
public <S, E> S accept(IRVisitor<S, E> visitor) {
return visitor.visit(this);
}
protected void _dump(Dumper d) {
d.printMember("lhs", lhs);
d.printMember("rhs", rhs);
}
}
<file_sep>/str/main.c
#include "lex.yy.h"
#include "main.h"
int main(int argc, char **argv) {
int ret;
if(argc == 2 && !strcmp(argv[1], "--test")) {
test_str_decode();
test_lex();
printf("===================\n"
" All tests passed. \n"
"===================\n");
return 0;
}
while ((ret = yylex()) != 0) {
switch(ret) {
case TOKEN_STRING:
printf("TOKEN_STRING(%s:%s)\n", yytext, str_decode(yytext));
break;
case TOKEN_CHAR:
printf("TOKEN_CHAR(%s:%s)\n", yytext, str_decode(yytext));
break;
}
}
return 0;
}
<file_sep>/src/main/java/cflat/sysdep/amd64/CodeGenerator.java
package cflat.sysdep.amd64;
import cflat.asm.DirectMemoryReference;
import cflat.asm.ImmediateValue;
import cflat.asm.IndirectMemoryReference;
import cflat.asm.Label;
import cflat.asm.MemoryReference;
import cflat.asm.Operand;
import cflat.asm.Symbol;
import cflat.asm.SymbolTable;
import cflat.asm.Type;
import cflat.entity.DefinedFunction;
import cflat.entity.Entity;
import cflat.ir.Addr;
import cflat.ir.Assign;
import cflat.ir.Bin;
import cflat.ir.CJump;
import cflat.ir.Call;
import cflat.ir.Expr;
import cflat.ir.ExprStmt;
import cflat.ir.IR;
import cflat.ir.IRVisitor;
import cflat.ir.Int;
import cflat.ir.Jump;
import cflat.ir.LabelStmt;
import cflat.ir.Mem;
import cflat.ir.Op;
import cflat.ir.Return;
import cflat.ir.Stmt;
import cflat.ir.Str;
import cflat.ir.Switch;
import cflat.ir.Uni;
import cflat.ir.Var;
import cflat.sysdep.amd64.AssemblyCode;
import cflat.sysdep.CodeGeneratorOptions;
import cflat.sysdep.amd64.ELFConstants;
import cflat.sysdep.amd64.Register;
import cflat.utils.ErrorHandler;
import cflat.utils.ListUtils;
public class CodeGenerator
implements
cflat.sysdep.CodeGenerator,
IRVisitor<Void, Void>,
ELFConstants {
final CodeGeneratorOptions options;
final Type naturalType;
final ErrorHandler errorHandler;
private AssemblyCode as;
private Label epilogue;
public CodeGenerator(CodeGeneratorOptions opts, Type naturalType,
ErrorHandler h) {
this.options = opts;
this.naturalType = naturalType;
this.errorHandler = h;
}
private ImmediateValue imm(long num) {
return new ImmediateValue(num);
}
private ImmediateValue imm(Symbol sym) {
return new ImmediateValue(sym);
}
// TODO: Direct or Indirect?
private DirectMemoryReference mem(Symbol sym) {
return new DirectMemoryReference(sym);
}
private IndirectMemoryReference mem(Register reg) {
return new IndirectMemoryReference(0, reg);
}
private IndirectMemoryReference mem(long offset, Register reg) {
return new IndirectMemoryReference(offset, reg);
}
private IndirectMemoryReference mem(Symbol offset, Register reg) {
return new IndirectMemoryReference(offset, reg);
}
@Override
public AssemblyCode generate(IR ir) {
locateSymbols(ir);
return generateAssemblyCode(ir);
}
static final String LABEL_SYMBOL_BASE = ".L";
private void locateSymbols(IR ir) {
// TODO Auto-generated method stub
}
private AssemblyCode generateAssemblyCode(IR ir) {
// TODO Auto-generated method stub
return null;
}
private AssemblyCode compileStmts(DefinedFunction func) {
as = newAssemblyCode();
epilogue = new Label();
for (Stmt s : func.ir()) {
compileStmt(s);
}
as.label(epilogue);
return as;
}
// same
private void compileStmt(Stmt stmt) {
if (options.isVerboseAsm()) {
if (stmt.location() != null) {
as.comment(stmt.location().numberedLine());
}
}
stmt.accept(this);
}
// same
private AssemblyCode newAssemblyCode() {
return new AssemblyCode(naturalType, STACK_WORD_SIZE,
new SymbolTable(LABEL_SYMBOL_BASE), options.isVerboseAsm());
}
//
// Compile Function
//
// 64 bit
private static final long STACK_WORD_SIZE = 8;
@Override
public Void visit(ExprStmt s) {
// TODO Auto-generated method stub
return null;
}
@Override
public Void visit(Assign node) {
if (node.lhs().isAddr() && node.lhs().memref() != null) {
compile(node.rhs());
store(ax(node.lhs().type()), node.lhs().memref());
} else if (node.rhs().isConstant()) {
compile(node.lhs());
as.mov(ax(), cx());
loadConstant(node.rhs(), ax());
store(ax(node.lhs().type()), mem(cx()));
} else {
compile(node.rhs());
as.virtualPush(ax());
compile(node.lhs());
as.mov(ax(), cx());
as.virtualPop(ax());
store(ax(node.lhs().type()), mem(cx()));
}
return null;
}
private void store(Register reg, MemoryReference mem) {
as.mov(reg, mem);
}
@Override
public Void visit(CJump node) {
compile(node.cond());
Type t = node.cond().type();
as.test(ax(t), ax(t));
as.jnz(node.thenLabel());
as.jmp(node.elseLabel());
return null;
}
@Override
public Void visit(Jump node) {
as.jmp(node.label());
return null;
}
@Override
public Void visit(Switch s) {
// TODO Auto-generated method stub
return null;
}
@Override
public Void visit(LabelStmt node) {
as.label(node.label());
return null;
}
@Override
public Void visit(Return node) {
if (node.expr() != null) {
compile(node.expr());
}
as.jmp(epilogue);
return null;
}
@Override
public Void visit(Uni node) {
// check difference
Type src = node.expr().type();
Type dest = node.type();
compile(node.expr());
switch (node.op()) {
case UMINUS :
as.neg(ax(src));
break;
case BIT_NOT :
as.not(ax(src));
break;
case NOT :
as.test(ax(src), ax(src));
as.sete(al());
as.movzx(al(), ax(dest));
break;
case S_CAST :
as.movsx(ax(src), ax(dest));
break;
case U_CAST :
as.movzx(ax(src), ax(dest));
break;
default :
throw new Error("unknown unary operator: " + node.op());
}
return null;
}
private void compile(Expr expr) {
// TODO Auto-generated method stub
}
@Override
public Void visit(Bin node) {
// TODO Auto-generated method stub
Op op = node.op();
Type t = node.type();
if (node.right().isConstant() && !doesRequireRegisterOperand(op)) {
compile(node.left());
compileBinaryOp(op, ax(t), node.right().asmValue());
} else if (node.right().isConstant()) {
compile(node.left());
loadConstant(node.right(), cx());
compileBinaryOp(op, ax(t), cx(t));
} else if (node.right().isVar()) {
compile(node.left());
loadVariable((Var) node.right(), cx(t));
compileBinaryOp(op, ax(t), cx(t));
} else if (node.right().isAddr()) {
compile(node.left());
loadAddress(node.right().getEntityForce(), cx(t));
compileBinaryOp(op, ax(t), cx(t));
} else if (node.left().isConstant() || node.left().isVar()
|| node.left().isAddr()) {
compile(node.right());
as.mov(ax(), cx());
compile(node.left());
compileBinaryOp(op, ax(t), cx(t));
} else {
compile(node.right());
as.virtualPush(ax());
compile(node.left());
as.virtualPop(cx());
compileBinaryOp(op, ax(t), cx(t));
}
return null;
}
private void loadVariable(Var var, Register dest) {
// TODO Auto-generated method stub
if (var.memref() == null) {
Register a = dest.forType(naturalType);
as.mov(var.address(), a);
load(mem(a), dest.forType(var.type()));
} else {
load(var.memref(), dest.forType(var.type()));
}
}
private void load(MemoryReference mem, Register reg) {
as.mov(mem, reg);
}
private void loadAddress(Entity var, Register dest) {
if (var.address() != null) {
as.mov(var.address(), dest);
} else {
as.lea(var.memref(), dest);
}
}
private void compileBinaryOp(Op op, Register left, Operand right) {
// TODO Auto-generated method stub
switch (op) {
case ADD :
as.add(right, left);
break;
case SUB :
as.sub(right, left);
break;
case MUL :
as.imul(right, left);
break;
case S_DIV :
case S_MOD :
as.cltd();
as.idiv(cx(left.type));
if (op == Op.S_MOD) {
as.mov(dx(), left);
}
break;
case BIT_AND :
as.and(right, left);
break;
case BIT_OR :
as.or(right, left);
break;
case BIT_XOR :
as.xor(right, left);
break;
case BIT_LSHIFT :
as.sal(cl(), left);
break;
case BIT_RSHIFT :
as.shr(cl(), left);
break;
case ARITH_RSHIFT :
as.sar(cl(), left);
break;
default :
as.cmp(right, ax(left.type));
switch (op) {
case EQ :
as.sete(al());
break;
case NEQ :
as.setne(al());
break;
case S_GT :
as.setg(al());
break;
case S_GTEQ :
as.setge(al());
break;
case S_LT :
as.setl(al());
break;
case S_LTEQ :
as.setle(al());
break;
case U_GT :
as.seta(al());
break;
case U_GTEQ :
as.setae(al());
break;
case U_LT :
as.setb(al());
break;
case U_LTEQ :
as.setbe(al());
break;
default :
throw new Error("unknown binary operator: " + op);
}
as.movzx(al(), left);
}
}
private boolean doesRequireRegisterOperand(Op op) {
// TODO Auto-generated method stub
return false;
}
@Override
public Void visit(Call node) {
// TODO change amd64
for (Expr arg : ListUtils.reverse(node.args())) {
compile(arg);
as.push(ax());
}
if (node.isStaticCall()) {
as.call(node.function().callingSymbol());
} else {
compile(node.expr());
as.callAbsolute(ax());
}
// >4 bytes arguments are not supported.
rewindStack(as, stackSizeFromWordNum(node.numArgs()));
return null;
}
private void rewindStack(AssemblyCode as2, Object stackSizeFromWordNum) {
// TODO Auto-generated method stub
}
private Object stackSizeFromWordNum(long numArgs) {
// TODO Auto-generated method stub
return null;
}
/**
* leal 4(%ebp), %eax
*/
@Override
public Void visit(Addr node) {
loadAddress(node.entity(), ax());
return null;
}
@Override
public Void visit(Mem node) {
compile(node.expr());
load(mem(ax()), ax(node.type()));
return null;
}
/**
* movl 4(%ebp), %eax
*/
@Override
public Void visit(Var node) {
loadVariable(node, ax());
return null;
}
@Override
public Void visit(Int node) {
as.mov(imm(node.value()), ax());
return null;
}
@Override
public Void visit(Str node) {
// TODO 64bit test
loadConstant(node, ax());
return null;
}
private void loadConstant(Expr node, Register reg) {
// TODO 64 bit test
if (node.asmValue() != null) {
as.mov(node.asmValue(), reg);
} else if (node.memref() != null) {
as.lea(node.memref(), reg);
} else {
throw new Error("must not happen: constant has no asm value");
}
}
private Register ax() {
return ax(naturalType);
}
private Register al() {
return ax(Type.INT8);
}
private Register ax(Type t) {
return new Register(RegisterClass.AX, t);
}
private Register cx() {
return cx(naturalType);
}
private Register cl() {
return cx(Type.INT8);
}
private Register cx(Type t) {
return new Register(RegisterClass.CX, t);
}
private Register dx() {
return dx(naturalType);
}
private Register dx(Type t) {
return new Register(RegisterClass.DX, t);
}
}
<file_sep>/as/14_2/f.c
/*
* 14.2 のオリジナルソース
* 改行の位置を変更
*/
int f(int x, int y) {
int i, j;
i = x;
j = i * y;
return j;
}
int main(int argc, char **argv) {
int i = 77;
i = f(i, 8);
i %= 5;
return i;
}
<file_sep>/src/main/java/cflat/entity/Variable.java
package cflat.entity;
import cflat.ast.TypeNode;
abstract public class Variable extends Entity {
public Variable(boolean priv, TypeNode type, String name) {
super(priv, type, name);
}
}
<file_sep>/sample/42.cb
// -*- mode: c; -*-
int main(void) {
return 42;
}
<file_sep>/src/main/java/cflat/sysdep/CodeGenerator.java
package cflat.sysdep;
public interface CodeGenerator {
AssemblyCode generate(cflat.ir.IR ir);
}
<file_sep>/src/main/java/cflat/ir/Bin.java
package cflat.ir;
import cflat.asm.Type;
// TODO: test
/**
* 二項演算 (l OP r)
*/
public class Bin extends Expr {
/** 演算の種類 */
protected Op op;
/** 左の式 */
protected Expr left;
/** 右の式 */
protected Expr right;
/**
* 二項演算の中間表現
*
* @param type
* この式の型
* @param op
* 二項演算の種類
* @param left
* 二項演算の左の式(x + y の x)
* @param right
* 二項演算の右の式(x + y の y)
*/
public Bin(Type type, Op op, Expr left, Expr right) {
super(type);
this.op = op;
this.left = left;
this.right = right;
}
public Expr left() {
return left;
}
public Expr right() {
return right;
}
public Op op() {
return op;
}
public <S, E> E accept(IRVisitor<S, E> visitor) {
return visitor.visit(this);
}
protected void _dump(Dumper d) {
d.printMember("op", "" + op);
d.printMember("left", left);
d.printMember("right", right);
}
}
<file_sep>/plygrnd/Makefile
WORK_FILES = Adder.java AdderConstants.java AdderTokenManager.java \
Parser.java ParserConstants.java ParserTokenManager.java \
ParseException.java SimpleCharStream.java \
Token.java TokenMgrError.java
TARGET = Adder.class
JAVAC = javac
JAVACC = javacc
.PHONY: all clean
.SUFFIXES: .class .java .jj
all: $(TARGET)
clean:
rm -f *.class $(WORK_FILES)
.java.class:
$(JAVAC) $<
.jj.java:
$(JAVACC) $<
<file_sep>/src/main/java/cflat/ast/FuncallNode.java
package cflat.ast;
import cflat.exception.SemanticError;
import cflat.type.FunctionType;
import cflat.type.Type;
import java.util.*;
/**
* Function call
*/
public class FuncallNode extends ExprNode {
protected ExprNode expr;
protected List<ExprNode> args;
public FuncallNode(ExprNode expr, List<ExprNode> args) {
this.expr = expr;
this.args = args;
}
public ExprNode expr() {
return expr;
}
// TODO: implement
/**
* Returns a type of return value of the function which is refered by expr. This
* method expects expr.type().isCallable() is true.
*/
public Type type() {
try {
return functionType().returnType();
} catch (ClassCastException err) {
throw new SemanticError(err.getMessage());
}
}
/**
* Returns a type of function which is refered by expr. This method expects
* expr.type().isCallable() is true.
*/
public FunctionType functionType() {
return expr.type().getPointerType().baseType().getFunctionType();
}
/*
public long numArgs() {
return args.size();
}
*/
public List<ExprNode> args() {
return args;
}
// called from TypeChecker
/*
public void replaceArgs(List<ExprNode> args) {
this.args = args;
}
*/
public Location location() {
return expr.location();
}
protected void _dump(Dumper d) {
d.printMember("expr", expr);
d.printNodeList("args", args);
}
public <S, E> E accept(ASTVisitor<S, E> visitor) {
return visitor.visit(this);
}
}
<file_sep>/src/main/java/cflat/asm/OperandPattern.java
package cflat.asm;
// TODO: test
public interface OperandPattern {
public boolean match(Operand operand);
}
<file_sep>/README.md
# Test
```
$ mvn test
```
# Package
```
$ mvn package
```
# Document
```
$ mvn javadoc:javadoc
```
# Usage
JAR file
```
$ java -jar target/cbc-XXX.jar [options] [files...]
options
--help show help message
```
Class files
```
$ java -classpath target/classes cflat.compiler.Compiler [options] [files...]
```
# How to use debugger
```
$ jdb -classpath target/classes -sourcepath src/main/java:src/test/java cflat.compiler.Compiler [options] [files...]
```
<file_sep>/src/main/java/cflat/sysdep/AssemblyCode.java
package cflat.sysdep;
import java.io.PrintStream;
/**
* manage list of Assembly instance
*/
public interface AssemblyCode {
String toSource();
void dump();
void dump(PrintStream s);
}
<file_sep>/src/main/java/cflat/entity/Scope.java
package cflat.entity;
import cflat.exception.SemanticException;
import java.util.*;
// TODO: implement
/**
* スコープを表現する抽象クラス
*/
abstract public class Scope {
protected List<LocalScope> children;
public Scope() {
children = new ArrayList<LocalScope>();
}
protected void addChild(LocalScope s) {
children.add(s);
}
abstract public Entity get(String name) throws SemanticException;
}
<file_sep>/as/14_2/Makefile
# 14.2 のサンプル assembly code を assemble する。
#
# f.c: original c source code
AS = as
ASFLAGS = -g
CC = gcc
CFLAGS = -O0 -fcf-protection=none -fno-pie
# below doesn't work
#CFLAGS = -O0 -fcf-protection=none -pie
#CFLAGS = -O0 -fcf-protection=none -fpie
#CFLAGS = -O0 -fcf-protection=none -no-pie
.PHONY: all clean
all: f
clean:
rm -f a.out *.o *.s f *.tmp
# f
f: f.o
$(CC) -m32 -o $@ $^
f.o: f.s
$(AS) $(ASFLAGS) --32 -o $@ $^
f.s: f.c
$(CC) $(CFLAGS) -S -m32 $^
cp $@ [email protected]
#sed -r -f filter.sed [email protected] >$@
sed -i -r -f filter.sed $@
<file_sep>/src/main/java/cflat/ast/TypedefNode.java
package cflat.ast;
import cflat.type.Type;
import cflat.type.TypeRef;
import cflat.type.UserTypeRef;
/**
* typedef
*/
public class TypedefNode extends TypeDefinition {
protected TypeNode real;
public TypedefNode(Location loc, TypeRef real, String name) {
super(loc, new UserTypeRef(name), name);
this.real = new TypeNode(real);
}
public TypeNode realTypeNode() {
return real;
}
/*
* public TypeRef realTypeRef() { return real.typeRef(); }
*/
// TODO: implement
public Type definitingType() {
return null;
}
protected void _dump(Dumper d) {
d.printMember("name", name);
d.printMember("typeNode", typeNode);
}
public <T> T accept(DeclarationVisitor<T> visitor) {
return visitor.visit(this);
}
}
<file_sep>/src/main/java/cflat/compiler/SourceFile.java
package cflat.compiler;
import java.io.File;
public class SourceFile implements LdArg {
static final String EXT_CFLAT_SOURCE = ".cb";
static final String EXT_ASSEMBLY_SOURCE = ".s";
static final String EXT_OBJECT_FILE = ".o";
// ...
// @formatter:off
static final String[] KNOWN_EXTENSIONS = {
EXT_CFLAT_SOURCE,
EXT_ASSEMBLY_SOURCE,
EXT_OBJECT_FILE
};
// @formatter:on
private final String originalName;
private String currentName;
SourceFile(String name) {
this.originalName = name;
this.currentName = name;
}
public boolean isSourceFile() {
return true;
}
public String toString() {
return currentName;
}
String path() {
return currentName;
}
/*
* String currentName() { return currentName; }
*/
void setCurrentName(String name) {
this.currentName = name;
}
boolean isKnownFileType() {
String ext = extName(originalName);
for (String e : KNOWN_EXTENSIONS) {
if (e.equals(ext))
return true;
}
return false;
}
// 57
boolean isCflatSource() {
return extName(currentName).equals(EXT_CFLAT_SOURCE);
}
boolean isAssemblySource() {
return extName(currentName).equals(EXT_ASSEMBLY_SOURCE);
}
// ...
// 81
public String asmFileName() {
return replaceExt(EXT_ASSEMBLY_SOURCE);
}
public String objFileName() {
return replaceExt(EXT_OBJECT_FILE);
}
String linkedFileName(String newExt) {
return replaceExt(newExt);
}
private String replaceExt(String ext) {
return new File(originalName).getName().replaceFirst("\\.[^.]*$", "") + ext;
}
private String extName(String path) {
int idx = path.lastIndexOf(".");
if (idx < 0)
return "";
return path.substring(idx);
}
}
<file_sep>/src/main/java/cflat/sysdep/amd64/RegisterClass.java
package cflat.sysdep.amd64;
enum RegisterClass {
// TODO: AMD64 has more register
AX, BX, CX, DX, SI, DI, SP, BP;
}
<file_sep>/src/main/java/cflat/ast/UnionNode.java
package cflat.ast;
import cflat.type.Type;
import cflat.type.TypeRef;
import java.util.*;
/**
* 共用体定義
*/
public class UnionNode extends CompositeTypeDefinition {
public UnionNode(Location loc, TypeRef ref, String name, List<Slot> membs) {
super(loc, ref, name, membs);
}
// TODO: implement
public Type definitingType() {
return null;
}
public <T> T accept(DeclarationVisitor<T> visitor) {
return visitor.visit(this);
}
}
<file_sep>/str/Makefile
TARGET = tokenizer
LIBS = -ll
LEX = flex
SRCS = main.c str_decode.c util.c test_str_decode.c test.c
OBJS = $(SRCS:.c=.o) lex.yy.o
.PHONY: all clean check
all: $(TARGET)
clean:
rm -f $(TARGET) $(OBJS) lex.yy.h lex.yy.c
check: $(TARGET)
./$(TARGET) --test
$(TARGET): $(OBJS)
$(CC) -o $@ $(OBJS) $(LIBS)
lex.yy.h lex.yy.c: lex.l
$(LEX) --header-file=lex.yy.h $<
main.c: lex.yy.h main.h
test_str_decode.c: lex.yy.h main.h util.h
lex.yy.c: util.h main.h
util.c: util.h
<file_sep>/src/main/java/cflat/sysdep/Linker.java
package cflat.sysdep;
import cflat.exception.IPCException;
import java.util.List;
public interface Linker {
void generateExecutable(List<String> args, String destPath, LinkerOptions opts)
throws IPCException;
void generateSharedLibrary(List<String> args, String destPath, LinkerOptions opts)
throws IPCException;
}
<file_sep>/src/main/java/cflat/ast/UnaryArithmeticOpNode.java
package cflat.ast;
// TODO: implement
public class UnaryArithmeticOpNode extends UnaryOpNode {
protected long amount;
public UnaryArithmeticOpNode(String op, ExprNode expr) {
super(op, expr);
amount = 1;
}
}
<file_sep>/src/main/java/cflat/compiler/Options.java
package cflat.compiler;
import cflat.exception.OptionParseError;
import cflat.parser.LibraryLoader;
import cflat.sysdep.Assembler;
import cflat.sysdep.AssemblerOptions;
import cflat.sysdep.CodeGenerator;
import cflat.sysdep.CodeGeneratorOptions;
import cflat.sysdep.Linker;
import cflat.sysdep.LinkerOptions;
import cflat.sysdep.Platform;
import cflat.sysdep.X86Linux;
import cflat.type.TypeTable;
import cflat.utils.ErrorHandler;
import java.io.*;
import java.util.*;
public class Options {
static Options parse(String[] args) {
Options opts = new Options();
opts.parseArgs(args);
return opts;
}
private CompilerMode mode;
private Platform platform = new X86Linux();
private String outputFileName;
private boolean verbose = false;
private LibraryLoader loader = new LibraryLoader();
private boolean debugParser = false;
private CodeGeneratorOptions genOptions = new CodeGeneratorOptions();
private AssemblerOptions asOptions = new AssemblerOptions();
private LinkerOptions ldOptions = new LinkerOptions();
private List<LdArg> ldArgs;
private List<SourceFile> sourceFiles;
CompilerMode mode() {
return mode;
}
boolean isAssembleRequired() {
return mode.requires(CompilerMode.Assemble);
}
boolean isLinkRequired() {
return mode.requires(CompilerMode.Link);
}
List<SourceFile> sourceFiles() {
return sourceFiles;
}
String asmFileNameOf(SourceFile src) {
if (outputFileName != null && mode == CompilerMode.Compile) {
return outputFileName;
}
return src.asmFileName();
}
String objFileNameOf(SourceFile src) {
if (outputFileName != null && mode == CompilerMode.Assemble) {
return outputFileName;
}
return src.objFileName();
}
String exeFileName() {
return linkedFileName("");
}
String soFileName() {
return linkedFileName(".so");
}
static private final String DEFAULT_LINKER_OUTPUT = "a.out";
private String linkedFileName(String newExt) {
if (outputFileName != null) {
return outputFileName;
}
if (sourceFiles.size() == 1) {
return sourceFiles.get(0).linkedFileName(newExt);
} else {
return DEFAULT_LINKER_OUTPUT;
}
}
/*
String outputFileName() {
return this.outputFileName;
}
*/
boolean isVerboseMode() {
return this.verbose;
}
boolean doesDebugParser() {
return this.debugParser;
}
LibraryLoader loader() {
return this.loader;
}
// TODO: test
TypeTable typeTable() {
return platform.typeTable();
}
CodeGenerator codeGenerator(ErrorHandler h) {
return platform.codeGenerator(genOptions, h);
}
Assembler assembler(ErrorHandler h) {
return platform.assembler(h);
}
AssemblerOptions asOptions() {
return asOptions;
}
Linker linker(ErrorHandler h) {
return platform.linker(h);
}
LinkerOptions ldOptions() {
return ldOptions;
}
List<String> ldArgs() {
List<String> result = new ArrayList<String>();
for (LdArg arg : ldArgs) {
result.add(arg.toString());
}
return result;
}
boolean isGeneratingSharedLibrary() {
return ldOptions.generatingSharedLibrary;
}
void parseArgs(String[] origArgs) {
ldArgs = new ArrayList<LdArg>();
ListIterator<String> args = Arrays.asList(origArgs).listIterator();
while (args.hasNext()) {
String arg = args.next();
if (arg.equals("--")) {
// "--" stops command line processing
break;
} else if (arg.startsWith("-")) {
if (CompilerMode.isModeOption(arg)) {
if (mode != null) {
parseError(mode.toOption() + " option and " + arg
+ " option is exclusive");
}
mode = CompilerMode.fromOption(arg);
} else if (arg.equals("--debug-parser")) {
debugParser = true;
} else if (arg.startsWith("-o")) {
outputFileName = getOptArg(arg, args);
} else if (arg.equals("-fverbose-asm")
|| arg.equals("--verbose-asm")) {
genOptions.generateVerboseAsm();
} else if (arg.equals("-v")) {
verbose = true;
asOptions.verbose = true;
ldOptions.verbose = true;
} else if (arg.equals("--help")) {
printUsage(System.out);
System.exit(0);
} else {
parseError("unknown option: " + arg);
}
} else {
ldArgs.add(new SourceFile(arg));
}
}
// args has more arguments when "--" is appeard.
while (args.hasNext()) {
ldArgs.add(new SourceFile(args.next()));
}
if (mode == null) {
mode = CompilerMode.Link;
}
sourceFiles = selectSourceFiles(ldArgs);
if (sourceFiles.isEmpty()) {
parseError("no input file");
}
for (SourceFile src : sourceFiles) {
if (!src.isKnownFileType()) {
parseError("unknown file type: " + src.path());
}
}
if (outputFileName != null && sourceFiles.size() > 1 && !isLinkRequired()) {
parseError("-o option requires only 1 input (except linking)");
}
}
private void parseError(String msg) {
throw new OptionParseError(msg);
}
/*
* private void addLdArg(String arg) { ldArgs.ad(new LdOption(arg)); }
*/
private List<SourceFile> selectSourceFiles(List<LdArg> args) {
List<SourceFile> result = new ArrayList<SourceFile>();
for (LdArg arg : args) {
if (arg.isSourceFile()) {
result.add((SourceFile) arg);
}
}
return result;
}
private String getOptArg(String opt, ListIterator<String> args) {
String path = opt.substring(2);
if (path.length() != 0) { // -Ipath
return path;
} else { // -I path
return nextArg(opt, args);
}
}
private String nextArg(String opt, ListIterator<String> args) {
if (!args.hasNext()) {
parseError("missing argument for " + opt);
}
return args.next();
}
// private List<String> parseCommaSeparatedOptions(String opt)
void printUsage(PrintStream out) {
// @formatter:off
String msg = "Usage: cbc [options] file...\n"
+ "Global Options:\n"
+ " --check-syntax Check syntax and quit.\n"
+ " --dump-tokens Dumps tokens and quit.\n"
+ " --dump-ast Dumps AST and quit.\n"
+ " --dump-semantic Dumps AST after semantic checks and quit.\n"
+ " --dump-ir Dumps IR and quit.\n"
+ " --dump-asm Dumps AssemblyCode and quit.\n"
+ " --print-asm Prints assemblu code and quit.\n"
+ " -S Generates an assembly file and quit.\n"
+ " -o PATH Places output in file PATH.\n"
+ " -v Turn on verbose mode.\n"
// + " --version Shows compiler version.\n"
+ " --help Prints this message and quit.\n"
+ "\n"
// + "Optimization Option:\n"
// + "Parser Optons:\n"
+ "Code Generator Options:\n"
+ " -fverbose-asm Generate assembly with verbose comments.\n"
// + "Assembler Optoins:\n"
// + "Linker Options:\n"
;
// @formatter:on
out.println(msg);
}
}
<file_sep>/str/main.h
// -*- mode: c; -*-
enum {
TOKEN_STRING = 256,
TOKEN_CHAR,
};
char *str_decode(char *);
void test_str_decode();
void test_lex();
<file_sep>/sample/if-else.cb
// -*- mode: c; -*-
int main(void) {
int var = 0;
if (var == 0) {
var = 42;
} else {
var = 41;
}
return var;
}
<file_sep>/src/main/java/cflat/asm/MemoryReference.java
package cflat.asm;
/**
* operand of Memory reference
*/
abstract public class MemoryReference extends Operand
implements
Comparable<MemoryReference> {
public boolean isMemoryReference() {
return true;
}
abstract public void fixOffset(long diff);
abstract protected int cmp(DirectMemoryReference mem);
abstract protected int cmp(IndirectMemoryReference mem);
}
<file_sep>/src/main/java/cflat/type/VoidType.java
package cflat.type;
public class VoidType extends Type {
public VoidType() {
}
public boolean isVoid() {
return true;
}
public long size() {
return 1;
}
//
public boolean isSameType(Type other) {
return other.isVoid();
}
public boolean isCompatible(Type other) {
return other.isVoid();
}
public boolean isCastableTo(Type other) {
return other.isVoid();
}
//
}
<file_sep>/src/main/java/cflat/sysdep/x86/Register.java
package cflat.sysdep.x86;
import cflat.asm.SymbolTable;
import cflat.asm.Type;
/**
* operand of register like %eax.
* concrete class of abstract class cflat.asm.Register.
*/
class Register extends cflat.asm.Register {
RegisterClass _class;
Type type;
Register(RegisterClass _class, Type type) {
this._class = _class;
this.type = type;
}
Register forType(Type t) {
return new Register(_class, t);
}
// cflat.asm.Register#isRegister() returns true;
// So needless to over write.
// public boolean isRegister() { return true; }
// ...
// 37
String baseName() {
return _class.toString().toLowerCase();
}
public String toSource(SymbolTable table) {
// GNU assembler dependent
return "%" + typeName();
}
private String typeName() {
switch (type) {
case INT8 :
return lowerByteRegister();
case INT16 :
return baseName();
case INT32 :
return "e" + baseName();
case INT64 :
return "r" + baseName();
default :
throw new Error("unknown register Type: " + type);
}
}
private String lowerByteRegister() {
switch (_class) {
case AX :
case BX :
case CX :
case DX :
return baseName().substring(0, 1) + "l";
default :
throw new Error("does not have lower-byte register: " + _class);
}
}
public String dump() {
return "(Register " + _class.toString() + " " + type.toString() + ")";
}
}
<file_sep>/str/test_data.c
/* test data for test_lex() */
"" // empty string
"\"\t\n\127\\" // back slash escape string
'a' // normal
'\127' // character code
<file_sep>/src/main/java/cflat/entity/DefinedVariable.java
package cflat.entity;
import cflat.ast.Dumper;
import cflat.ast.ExprNode;
import cflat.ast.TypeNode;
import cflat.ir.Expr;
import cflat.type.Type;
/**
* 変数定義
*/
public class DefinedVariable extends Variable {
protected ExprNode initializer;
protected Expr ir;
protected long sequence;
public DefinedVariable(boolean priv, TypeNode type, String name, ExprNode init) {
super(priv, type, name);
this.initializer = init;
this.sequence = -1;
}
static private long tmpSeq = 0;
static public DefinedVariable tmp(Type t) {
return new DefinedVariable(false, new TypeNode(t), "@tmp" + tmpSeq++, null);
}
public boolean isDefined() {
return true;
}
public void setSequence(long seq) {
this.sequence = seq;
}
public String symbolString() {
return (sequence < 0) ? name : (name + "." + sequence);
}
public boolean hasInitializer() {
return (initializer != null);
}
// public boolean isInitialized() {
public ExprNode initializer() {
return initializer;
}
public void setInitializer(ExprNode expr) {
this.initializer = expr;
}
public void setIR(Expr expr) {
this.ir = expr;
}
public Expr ir() {
return ir;
}
protected void _dump(Dumper d) {
d.printMember("name", name);
d.printMember("isPrivate", isPrivate);
d.printMember("typeNode", typeNode);
d.printMember("initializer", initializer);
}
public <T> T accept(EntityVisitor<T> visitor) {
return visitor.visit(this);
}
}
<file_sep>/as/13_2/Makefile
# syntax_gas.asm: GNU as(gas) syntax sample code
# syntax_nasm.asm: nasm syntax sample code
LDFLAGS = -g
.PHONY: all clean
all: syntax_gas syntax_nasm
clean:
rm -f a.out *.o syntax_gas syntax_nasm
syntax_gas.o: syntax_gas.asm
$(AS) -g -o $@ $^
syntax_nasm.o: syntax_nasm.asm
nasm -f elf64 -g -F dwarf $^
<file_sep>/as/Makefile
# bit_operator.c: bit operator sample
LDFLAGS = -g
.PHONY: all clean
all: bit_operator
clean:
rm -f a.out *.o bit_operator
<file_sep>/sample/func_ptr.cb
// -*- mode: c; -*-
int inc(int n) {
return n + 1;
}
int main(void) {
int (*funcp)();
funcp = inc;
return (*funcp)(41);
}
<file_sep>/as/bit_operator.c
#include <stdio.h>
void xor(void) {
int val = 0xC; // 0xC = 1100(2)
val ^= 0xA; // 0xA = 1010(2)
printf("0x%X\n", val); // 0110(2) = 0x6
val ^= val;
printf("0x%X\n", val); // 0000(2) = 0x0
}
void not(void) {
int val = 0x1; // 1(2)
val = ~val;
printf("0x%X\n", val); // 0xFFFFFFFE
}
int main(void) {
xor();
not();
return 0;
}
// 32 bit
// 16 bit + 16 bit
// 4bit 1111 => 8+4+2+1 => 15
//FFFFFFFF
<file_sep>/sample/Makefile
CC = ./cbc
AS = as
LINKER = cc
# どちらもイケる
#.SUFFIXES: .s .cb
#.SUFFIXES: .cb .s
.SUFFIXES: .cb
.PHONY: clean
all: 42 func gvar memb if if-else lvar func_ptr
clean:
rm -rf *.s *.o a.out \
42 func gvar memb if if-else lvar func_ptr
.cb.s:
$(CC) -S $<
.s.o:
$(AS) --32 -o $@ $<
.o:
$(LINKER) -m32 -o $@ $<
<file_sep>/src/main/java/cflat/sysdep/X86Linux.java
package cflat.sysdep;
import cflat.type.TypeTable;
import cflat.utils.ErrorHandler;
import cflat.asm.Type;
// TODO: test
public class X86Linux implements Platform {
public TypeTable typeTable() {
return TypeTable.ilp32();
}
public CodeGenerator codeGenerator(CodeGeneratorOptions opts, ErrorHandler h) {
return new cflat.sysdep.x86.CodeGenerator(opts, naturalType(), h);
}
private Type naturalType() {
return Type.INT32;
}
public Assembler assembler(ErrorHandler h) {
return new GNUAssembler(h);
}
public Linker linker(ErrorHandler h) {
return new GNULinker(h);
}
}
<file_sep>/str/test.c
#include <stdio.h>
#include <string.h>
#include "lex.yy.h"
#include "main.h"
#include "util.h"
void test_lex() {
yyin = fopen("test_data.c", "r");
expect(__LINE__, TOKEN_STRING, yylex());
expect_str(__LINE__, "", yytext);
expect(__LINE__, TOKEN_STRING, yylex());
expect_str(__LINE__, "\"\t\n\127\\", str_decode(yytext));
expect(__LINE__, TOKEN_CHAR, yylex());
expect_str(__LINE__, "a", str_decode(yytext));
expect(__LINE__, TOKEN_CHAR, yylex());
expect_str(__LINE__, "W", str_decode(yytext));
}
/*
errors
/*<<EOF>> - missing terminating
'' - empty character
'ab' - multi-character
"\n - missing terminating
"<<EOF>> - missing terminating
'\n - missing terminating
'<<EOF>> - missing terminating
*/
<file_sep>/src/main/java/cflat/compiler/TypeChecker.java
package cflat.compiler;
import cflat.ast.AST;
import cflat.ast.BinaryOpNode;
import cflat.ast.BlockNode;
import cflat.ast.CastNode;
import cflat.ast.ExprNode;
import cflat.ast.IntegerLiteralNode;
import cflat.ast.Location;
import cflat.ast.Node;
import cflat.ast.StmtNode;
import cflat.entity.DefinedFunction;
import cflat.entity.DefinedVariable;
import cflat.entity.Parameter;
import cflat.exception.SemanticException;
import cflat.type.IntegerType;
import cflat.type.Type;
import cflat.type.TypeTable;
import cflat.utils.ErrorHandler;
// TODO: implement
/**
* 静的型チェック
*/
public class TypeChecker extends Visitor {
private TypeTable typeTable;
private ErrorHandler errorHandler;
// TODO: test
public TypeChecker(TypeTable typeTable, ErrorHandler errorHandler) {
this.typeTable = typeTable;
this.errorHandler = errorHandler;
}
private void check(StmtNode node) {
visitStmt(node);
}
private void check(ExprNode node) {
visitExpr(node);
}
DefinedFunction currentFunction;
// TODO: implement
public void check(AST ast) throws SemanticException {
for (DefinedVariable var : ast.definedVariables()) {
checkVariable(var);
}
for (DefinedFunction f : ast.definedFunctions()) {
currentFunction = f;
checkReturnType(f);
checkParamTypes(f);
check(f.body());
}
if (errorHandler.errorOccured()) {
throw new SemanticException("compile failed");
}
}
//
private ExprNode implicitCast(Type targetType, ExprNode expr) {
if (expr.type().isSameType(targetType)) {
return expr;
} else if (expr.type().isCastableTo(targetType)) {
if (!expr.type().isCompatible(targetType)
&& !isSafeIntegerCast(expr, targetType)) {
warn(expr, "incompatible implicit cast from " + expr.type() + " to "
+ targetType);
}
return new CastNode(targetType, expr);
} else {
invalidCastError(expr, expr.type(), targetType);
return expr;
}
}
private Type integralPromotion(Type t) {
if (!t.isInteger()) {
throw new Error("integralPromotion for " + t);
}
Type intType = typeTable.signedInt();
if (t.size() < intType.size()) {
return intType;
} else {
return t;
}
}
//
private boolean isSafeIntegerCast(Node node, Type type) {
if (!type.isInteger())
return false;
IntegerType t = (IntegerType) type;
if (!(node instanceof IntegerLiteralNode))
return false;
IntegerLiteralNode n = (IntegerLiteralNode) node;
return t.isInDomain(n.value());
}
//
private void checkReturnType(DefinedFunction f) {
if (isInvalidReturnType(f.returnType())) {
error(f.location(), "return invalid type: " + f.returnType());
}
}
private void checkParamTypes(DefinedFunction f) {
for (Parameter param : f.parameters()) {
if (isInvalidParameterType(param.type())) {
error(param.location(), "invalid parameter type: " + param.type());
}
}
}
//
// Statements
//
// TODO: implement
public Void visit(BlockNode node) {
return null;
}
public void checkVariable(DefinedVariable var) {
if (isInvalidVariableType(var.type())) {
error(var.location(), "invalid variable type");
return;
}
if (var.hasInitializer()) {
if (isInvalidLHSType(var.type())) {
error(var.location(), "invalid LHS type: " + var.type());
return;
}
check(var.initializer());
var.setInitializer(implicitCast(var.type(), var.initializer()));
}
}
public Void visit(BinaryOpNode node) {
super.visit(node);
if (node.operator().equals("+") || node.operator().equals("-")) {
expectsSameIntegerOrPointerDiff(node);
} else if (node.operator().equals("*") || node.operator().equals("/")
|| node.operator().equals("%") || node.operator().equals("&")
|| node.operator().equals("|") || node.operator().equals("^")
|| node.operator().equals("<<") || node.operator().equals(">>")) {
expectsSameInteger(node);
} else if (node.operator().equals("==") || node.operator().equals("!=")
|| node.operator().equals("<") || node.operator().equals("<=")
|| node.operator().equals(">") || node.operator().equals(">=")) {
expectsComparableScalars(node);
} else {
throw new Error("unknown binary operator: " + node.operator());
}
return null;
}
private void expectsSameIntegerOrPointerDiff(BinaryOpNode node) {
if (node.left().isPointer() && node.right().isPointer()) {
if (node.operator().equals("+")) {
error(node, "invalid operation: operation: pointer + pointer");
return;
}
node.setType(typeTable.ptrDiffType());
} else if (node.left().isPointer()) {
mustBeInteger(node.right(), node.operator());
node.setRight(integralPromotedExpr(node.right()));
node.setType(node.left().type());
} else if (node.right().isPointer()) {
if (node.operator().equals("-")) {
error(node, "invalid operation: integer - pointer");
return;
}
mustBeInteger(node.left(), node.operator());
node.setLeft(integralPromotedExpr(node.left()));
node.setType(node.right().type());
} else {
expectsSameInteger(node);
}
}
private ExprNode integralPromotedExpr(ExprNode expr) {
Type t = integralPromotion(expr.type());
if (t.isSameType(expr.type())) {
return expr;
} else {
return new CastNode(t, expr);
}
}
private void expectsSameInteger(BinaryOpNode node) {
if (!mustBeInteger(node.left(), node.operator()))
return;
if (!mustBeInteger(node.right(), node.operator()))
return;
arithmeticImplicitCast(node);
}
private void expectsComparableScalars(BinaryOpNode node) {
if (!mustBeScalar(node.left(), node.operator()))
return;
if (!mustBeScalar(node.right(), node.operator()))
return;
if (node.left().type().isPointer()) {
ExprNode right = forcePointerType(node.left(), node.right());
node.setRight(right);
node.setType(node.left().type());
return;
}
if (node.right().type().isPointer()) {
ExprNode left = forcePointerType(node.right(), node.left());
node.setLeft(left);
node.setType(node.right().type());
return;
}
arithmeticImplicitCast(node);
}
private ExprNode forcePointerType(ExprNode master, ExprNode slave) {
if (master.type().isCompatible(slave.type())) {
// needs no cast
return slave;
} else {
warn(slave, "incompatible implicit cast from " + slave.type() + " to "
+ master.type());
return new CastNode(master.type(), slave);
}
}
private void arithmeticImplicitCast(BinaryOpNode node) {
Type r = integralPromotion(node.right().type());
Type l = integralPromotion(node.left().type());
Type target = usualArithmeticConversion(l, r);
if (!l.isSameType(target)) {
// insert cast on left expr
node.setLeft(new CastNode(target, node.left()));
}
if (!r.isSameType(target)) {
// insert cast on right expr
node.setRight(new CastNode(target, node.right()));
}
node.setType(target);
}
private Type usualArithmeticConversion(Type l, Type r) {
Type s_int = typeTable.signedInt();
Type u_int = typeTable.unsignedInt();
Type s_long = typeTable.signedLong();
Type u_long = typeTable.unsignedLong();
if ((l.isSameType(u_int) && r.isSameType(s_long))
|| (r.isSameType(u_int) && l.isSameType(s_long))) {
return u_long;
} else if (l.isSameType(u_long) && r.isSameType(u_long)) {
return u_long;
} else if (l.isSameType(s_long) && r.isSameType(s_long)) {
return s_long;
} else if (l.isSameType(u_int) && r.isSameType(u_int)) {
return u_int;
} else {
return s_int;
}
}
private boolean isInvalidReturnType(Type t) {
return t.isStruct() || t.isUnion() || t.isArray();
}
private boolean isInvalidParameterType(Type t) {
return t.isStruct() || t.isUnion() || t.isVoid() || t.isIncompleteArray();
}
private boolean isInvalidVariableType(Type t) {
return t.isVoid() || (t.isArray() && !t.isAllocatedArray());
}
private boolean isInvalidLHSType(Type t) {
// Array is OK if it is declared as a type of parameter.
return t.isStruct() || t.isUnion() || t.isVoid();
}
//
private boolean mustBeInteger(ExprNode expr, String op) {
if (!expr.type().isInteger()) {
wrongTypeError(expr, op);
return false;
}
return true;
}
private boolean mustBeScalar(ExprNode expr, String op) {
if (!expr.type().isScalar()) {
wrongTypeError(expr, op);
return false;
}
return true;
}
private void invalidCastError(Node n, Type l, Type r) {
error(n, "invalid cast from " + l + " to " + r);
}
private void wrongTypeError(ExprNode expr, String op) {
error(expr, "wrong operand type for " + op + ": " + expr.type());
}
private void warn(Node n, String msg) {
errorHandler.warn(n.location(), msg);
}
private void error(Node n, String msg) {
errorHandler.error(n.location(), msg);
}
private void error(Location loc, String msg) {
errorHandler.error(loc, msg);
}
}
| d09d8e37e6825884a03295f254ff251bb4de7793 | [
"Markdown",
"Makefile",
"Java",
"C",
"Shell"
]
| 48 | Java | youpong/cflat | d02ab4e397da651030fa00f8ccc759ff7264b5fd | 75f126050397680b490bc6b4d7379cfd96e0b35c |
refs/heads/main | <repo_name>PrinsFrank/php-geo-svg<file_sep>/tests/Unit/Coordinator/CoordinatorTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Coordinator;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Coordinator\Coordinator;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBox;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Projection\MercatorProjection;
use PrinsFrank\PhpGeoSVG\Projection\Projection;
use PrinsFrank\PhpGeoSVG\Scale\Scale;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Coordinator\Coordinator
*/
class CoordinatorTest extends TestCase
{
/**
* @covers ::__construct
* @covers ::getWidth
*/
public function testGetWidth(): void
{
$boundingBox = $this->createMock(BoundingBox::class);
$boundingBox->expects(static::once())->method('getWidth')->with()->willReturn(42.0);
static::assertSame(126.0, (new Coordinator(new MercatorProjection(), $boundingBox, new Scale(3)))->getWidth());
}
/**
* @covers ::__construct
* @covers ::getHeight
*/
public function testGetHeight(): void
{
$boundingBox = $this->createMock(BoundingBox::class);
$boundingBox->expects(static::once())->method('getHeight')->with()->willReturn(42.0);
static::assertSame(252.0, (new Coordinator(new MercatorProjection(), $boundingBox, new Scale(3)))->getHeight());
}
/**
* @covers ::__construct
* @covers ::getX
*/
public function testGetX(): void
{
$position = new Position(42.0, 84.0);
$projection = $this->createMock(Projection::class);
$boundingBox = $this->createMock(BoundingBox::class);
$boundingBox->expects(static::once())->method('boundX')->with($position, $projection)->willReturn(0.42);
static::assertSame(2.52, (new Coordinator($projection, $boundingBox, new Scale(3)))->getX($position));
}
/**
* @covers ::__construct
* @covers ::getY
*/
public function testGetY(): void
{
$position = new Position(84.0, 42.0);
$projection = $this->createMock(Projection::class);
$boundingBox = $this->createMock(BoundingBox::class);
$boundingBox->expects(static::once())->method('boundY')->with($position, $projection)->willReturn(0.42);
static::assertSame(2.52, (new Coordinator($projection, $boundingBox, new Scale(3)))->getY($position));
}
}
<file_sep>/src/Html/Elements/Element.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Elements;
use PrinsFrank\PhpGeoSVG\Html\Elements\Definition\ForeignElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\Text\TextContent;
abstract class Element
{
/** @var Element[] */
protected array $childElements = [];
/** @var array<string, string> */
protected array $attributes = [];
private ?TextContent $textContent = null;
public function addChildElement(Element $childElement): self
{
$this->childElements[] = $childElement;
return $this;
}
/**
* @return Element[]
*/
public function getChildElements(): array
{
return $this->childElements;
}
/**
* @return array<string, string>
*/
public function getAttributes(): array
{
return $this->attributes;
}
public function setAttribute(string $name, mixed $value): self
{
$this->attributes[$name] = (string) $value;
return $this;
}
public function setTextContent(?TextContent $textContent): self
{
$this->textContent = $textContent;
return $this;
}
public function getTextContent(): ?TextContent
{
return $this->textContent;
}
/**
* @see https://html.spec.whatwg.org/#self-closing-start-tag-state
*
* Foreign elements must either have a start tag and an end tag, or a start tag that is marked as self-closing,
* in which case they must not have an end tag.
*/
public function canSelfClose(): bool
{
if (false === $this instanceof ForeignElement) {
return false;
}
if ([] !== $this->childElements) {
return false;
}
if (null !== $this->textContent) {
return false;
}
return true;
}
abstract public function getTagName(): string;
}
<file_sep>/src/Html/Elements/TitleElement.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Elements;
class TitleElement extends Element
{
public function getTagName(): string
{
return 'title';
}
}
<file_sep>/src/Geometry/GeometryObject/MultiPoint.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\GeometryObject;
class MultiPoint extends GeometryObject
{
/** @var Point[] */
protected array $points = [];
public function addPoint(Point $point): self
{
$this->points[] = $point;
return $this;
}
/**
* @return Point[]
*/
public function getPoints(): array
{
return $this->points;
}
}
<file_sep>/tests/Feature/GeoSVGWithProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Feature;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollectionFactory;
use PrinsFrank\PhpGeoSVG\GeoSVG;
use PrinsFrank\PhpGeoSVG\Projection\BalthasartProjection;
use PrinsFrank\PhpGeoSVG\Projection\BehrmannProjection;
use PrinsFrank\PhpGeoSVG\Projection\EquiRectangularProjection;
use PrinsFrank\PhpGeoSVG\Projection\GallPetersProjection;
use PrinsFrank\PhpGeoSVG\Projection\HoboDyerProjection;
use PrinsFrank\PhpGeoSVG\Projection\LambertProjection;
use PrinsFrank\PhpGeoSVG\Projection\MercatorProjection;
use PrinsFrank\PhpGeoSVG\Projection\MillerProjection;
use PrinsFrank\PhpGeoSVG\Projection\SmythProjection;
use PrinsFrank\PhpGeoSVG\Projection\ToblersWorldInASquareProjection;
use PrinsFrank\PhpGeoSVG\Projection\TrystanEdwardsProjection;
use PrinsFrank\PhpGeoSVG\Scale\Scale;
/**
* @coversNothing
*/
class GeoSVGWithProjectionTest extends TestCase
{
public function testBalthasartProjection(): void
{
(new GeoSVG(new BalthasartProjection()))
->setScale(new Scale(1))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-balthasart.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-balthasart.svg', __DIR__ . '/actual/world-balthasart.svg');
}
public function testBehrmannProjection(): void
{
(new GeoSVG(new BehrmannProjection()))
->setScale(new Scale(1))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-behrmann.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-behrmann.svg', __DIR__ . '/actual/world-behrmann.svg');
}
public function testEquiRectangularProjection(): void
{
(new GeoSVG(new EquiRectangularProjection()))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-equirectangular.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-equirectangular.svg', __DIR__ . '/actual/world-equirectangular.svg');
}
public function testGallPetersProjection(): void
{
(new GeoSVG(new GallPetersProjection()))
->setScale(new Scale(1))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-gall-peters.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-gall-peters.svg', __DIR__ . '/actual/world-gall-peters.svg');
}
public function testHoboDyerProjection(): void
{
(new GeoSVG(new HoboDyerProjection()))
->setScale(new Scale(1))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-hobo-dyer.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-hobo-dyer.svg', __DIR__ . '/actual/world-hobo-dyer.svg');
}
public function testLambertProjection(): void
{
(new GeoSVG(new LambertProjection()))
->setScale(new Scale(1))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-lambert.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-lambert.svg', __DIR__ . '/actual/world-lambert.svg');
}
public function testMercatorProjection(): void
{
(new GeoSVG(new MercatorProjection()))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-mercator.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-mercator.svg', __DIR__ . '/actual/world-mercator.svg');
}
public function testMillerProjection(): void
{
(new GeoSVG(new MillerProjection()))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-miller.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-miller.svg', __DIR__ . '/actual/world-miller.svg');
}
public function testSmythProjection(): void
{
(new GeoSVG(new SmythProjection()))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-smyth.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-smyth.svg', __DIR__ . '/actual/world-smyth.svg');
}
public function testToblersWorldInASquareProjection(): void
{
(new GeoSVG(new ToblersWorldInASquareProjection()))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-toblers-world-in-a-square.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-toblers-world-in-a-square.svg', __DIR__ . '/actual/world-toblers-world-in-a-square.svg');
}
public function testTrystanEdwardsProjection(): void
{
(new GeoSVG(new TrystanEdwardsProjection()))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/ne_110m_admin_0_countries.geojson'),
__DIR__ . '/actual/world-trystan-edwards.svg'
);
static::assertFileEquals(__DIR__ . '/expected/world-trystan-edwards.svg', __DIR__ . '/actual/world-trystan-edwards.svg');
}
}
<file_sep>/src/Projection/Projection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Projection;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
interface Projection
{
public function getX(Position $position): float;
public function getY(Position $position): float;
public function getMaxX(): float;
public function getMaxY(): float;
public function getMaxLatitude(): float;
}
<file_sep>/src/Projection/EquiRectangularProjection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Projection;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
class EquiRectangularProjection implements Projection
{
public function getX(Position $position): float
{
return $position->longitude - Position::MIN_LONGITUDE;
}
public function getY(Position $position): float
{
return - $position->latitude - Position::MIN_LATITUDE;
}
public function getMaxX(): float
{
return Position::TOTAL_LONGITUDE;
}
public function getMaxY(): float
{
return Position::TOTAL_LATITUDE;
}
public function getMaxLatitude(): float
{
return 90;
}
}
<file_sep>/tests/Unit/Projection/MercatorProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Projection\MercatorProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\MercatorProjection
*/
class MercatorProjectionTest extends TestCase
{
/**
* @covers ::getX
*/
public function testGetX(): void
{
static::assertSame(0.0, (new MercatorProjection())->getX(new Position(-180.0, 0)));
static::assertSame(45.0, (new MercatorProjection())->getX(new Position(-90.0, 0)));
static::assertSame(90.0, (new MercatorProjection())->getX(new Position(0.0, 0)));
static::assertSame(135.0, (new MercatorProjection())->getX(new Position(90.0, 0)));
static::assertSame(180.0, (new MercatorProjection())->getX(new Position(180.0, 0)));
}
/**
* @covers ::getY
*/
public function testGetY(): void
{
static::assertEqualsWithDelta(0.3, (new MercatorProjection())->getY(new Position(0, 90)), 0.1);
static::assertEqualsWithDelta(64.7, (new MercatorProjection())->getY(new Position(0, 45)), 0.1);
static::assertEqualsWithDelta(90.0, (new MercatorProjection())->getY(new Position(0, 0)), 0.1);
static::assertEqualsWithDelta(115.2, (new MercatorProjection())->getY(new Position(0, -45)), 0.1);
static::assertEqualsWithDelta(179.6, (new MercatorProjection())->getY(new Position(0, -90)), 0.1);
}
/**
* @covers ::getMaxX
*/
public function testGetMaxX(): void
{
static::assertSame(180.0, (new MercatorProjection())->getMaxX());
}
/**
* @covers ::getMaxY
*/
public function testGetMaxY(): void
{
static::assertSame(180.0, (new MercatorProjection())->getMaxY());
}
/**
* @covers ::getMaxLatitude
*/
public function testGetMaxLatitude(): void
{
static::assertSame(85.0, (new MercatorProjection())->getMaxLatitude());
}
}
<file_sep>/src/Geometry/GeometryObject/Point.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\GeometryObject;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
class Point extends GeometryObject
{
public function __construct(protected Position $position)
{
}
public function getPosition(): Position
{
return $this->position;
}
}
<file_sep>/src/Html/Rendering/PathShapeRenderer.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Rendering;
use PrinsFrank\PhpGeoSVG\Coordinator\Coordinator;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
class PathShapeRenderer
{
public const MOVE_TO = 'M';
public const LINE_TO = 'L';
public const HORIZONTAL_LINE = 'H';
public const VERTICAL_LINE = 'V';
public const CLOSE_PATH = 'Z';
public const CUBIC_CURVE = 'C';
public const SHORT_CUBIC_CURVE = 'S';
public const QUADRATIC_CURVE = 'Q';
public const SHORT_QUADRATIC_CURVE = 'T';
public const ARC = 'A';
public static function renderLineStringPath(LineString $lineString, Coordinator $coordinator): string
{
$renderedLineString = '';
foreach ($lineString->getPositions() as $key => $position) {
if (0 === $key) {
$renderedLineString .= self::MOVE_TO;
} else {
$renderedLineString .= ' ' . self::LINE_TO;
}
$renderedLineString .= $coordinator->getX($position) . ' ' . $coordinator->getY($position);
}
return $renderedLineString;
}
}
<file_sep>/src/Html/Factory/ElementFactory.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Factory;
use PrinsFrank\PhpGeoSVG\Coordinator\Coordinator;
use PrinsFrank\PhpGeoSVG\Exception\NotImplementedException;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollection;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\GeometryObject;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiLineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPoint;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPolygon;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Point;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Polygon;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Html\Elements\CircleElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\Element;
use PrinsFrank\PhpGeoSVG\Html\Elements\GroupElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\PathElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\SvgElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\Text\TextContent;
use PrinsFrank\PhpGeoSVG\Html\Elements\TitleElement;
use PrinsFrank\PhpGeoSVG\Html\Rendering\PathShapeRenderer;
class ElementFactory
{
/**
* @throws NotImplementedException
*/
public static function buildForGeometryCollection(GeometryCollection $geometryCollection, Coordinator $coordinator): Element
{
$svgElement = (new SvgElement())
->setAttribute('width', $coordinator->getWidth())
->setAttribute('height', $coordinator->getHeight())
->setAttribute('viewbox', '0 0 ' . $coordinator->getWidth() . ' ' . $coordinator->getHeight());
foreach ($geometryCollection->getGeometryObjects() as $geometryObject) {
$svgElement->addChildElement(self::buildForGeometryObject($geometryObject, $coordinator));
}
return $svgElement;
}
/**
* @throws NotImplementedException
*/
public static function buildForGeometryObject(GeometryObject $geometryObject, Coordinator $coordinator): Element
{
$element = match (get_class($geometryObject)) {
LineString::class => self::buildForLineString($geometryObject, $coordinator),
MultiPoint::class => self::buildForMultiPoint($geometryObject, $coordinator),
MultiPolygon::class => self::buildForMultiPolygon($geometryObject, $coordinator),
MultiLineString::class => self::buildForMultiLineString($geometryObject, $coordinator),
Polygon::class => self::buildForPolygon($geometryObject, $coordinator),
Point::class => self::buildForPoint($geometryObject, $coordinator),
default => throw new NotImplementedException('GeometryObject with class "' . get_class($geometryObject) . '" can\'t be built yet.')
};
if (null !== $geometryObject->getTitle()) {
$element->addChildElement((new TitleElement())->setTextContent(new TextContent($geometryObject->getTitle())));
}
if (null !== $geometryObject->getFeatureClass()) {
$element->setAttribute('data-feature-class', $geometryObject->getFeatureClass());
}
return $element;
}
public static function buildForLineString(LineString $lineString, Coordinator $coordinator): PathElement
{
return (new PathElement())
->setAttribute('d', PathShapeRenderer::renderLineStringPath($lineString, $coordinator));
}
/**
* @throws NotImplementedException
*/
public static function buildForMultiPoint(MultiPoint $multiPoint, Coordinator $coordinator): GroupElement
{
$element = new GroupElement();
foreach ($multiPoint->getPoints() as $point) {
$element->addChildElement(self::buildForGeometryObject($point, $coordinator));
}
return $element;
}
/**
* @throws NotImplementedException
*/
public static function buildForMultiPolygon(MultiPolygon $multiPolygon, Coordinator $coordinator): GroupElement
{
$element = new GroupElement();
foreach ($multiPolygon->getPolygons() as $polygon) {
$element->addChildElement(self::buildForGeometryObject($polygon, $coordinator));
}
return $element;
}
/**
* @throws NotImplementedException
*/
public static function buildForMultiLineString(MultiLineString $multiLineString, Coordinator $coordinator): GroupElement
{
$element = new GroupElement();
foreach ($multiLineString->getLineStrings() as $lineString) {
$element->addChildElement(self::buildForGeometryObject($lineString, $coordinator));
}
return $element;
}
/**
* @throws NotImplementedException
*/
public static function buildForPolygon(Polygon $polygon, Coordinator $coordinator): Element
{
$element = new GroupElement();
$element->addChildElement(self::buildForGeometryObject($polygon->getExteriorRing(), $coordinator));
foreach ($polygon->getInteriorRings() as $interiorRing) {
$element->addChildElement(self::buildForGeometryObject($interiorRing, $coordinator));
}
return $element;
}
public static function buildForPoint(Point $point, Coordinator $coordinator): CircleElement
{
return self::buildForPosition($point->getPosition(), $coordinator);
}
public static function buildForPosition(Position $position, Coordinator $coordinator): CircleElement
{
$element = new CircleElement();
$element->setAttribute('cy', $coordinator->getY($position));
$element->setAttribute('cx', $coordinator->getX($position));
return $element;
}
}
<file_sep>/src/GeoSVG.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG;
use PrinsFrank\PhpGeoSVG\Coordinator\Coordinator;
use PrinsFrank\PhpGeoSVG\Exception\PhpGeoSVGException;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBox;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBoxPosition;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollection;
use PrinsFrank\PhpGeoSVG\Html\Factory\ElementFactory;
use PrinsFrank\PhpGeoSVG\Html\Rendering\ElementRenderer;
use PrinsFrank\PhpGeoSVG\Projection\EquiRectangularProjection;
use PrinsFrank\PhpGeoSVG\Projection\Projection;
use PrinsFrank\PhpGeoSVG\Scale\Scale;
class GeoSVG
{
public const VENDOR_NAME = 'prinsfrank';
public const PACKAGE_NAME = 'php-geo-svg';
public const PACKAGE_PATH = self::VENDOR_NAME . '/' . self::PACKAGE_NAME;
private ?Scale $scale = null;
public function __construct(private ?Projection $projection = null, private ?BoundingBox $boundingBox = null)
{
}
public function setProjection(?Projection $projection): self
{
$this->projection = $projection;
return $this;
}
public function getProjection(): Projection
{
if (null === $this->projection) {
$this->projection = new EquiRectangularProjection();
}
return $this->projection;
}
public function setBoundingBox(?BoundingBox $boundingBox): self
{
$this->boundingBox = $boundingBox;
return $this;
}
/**
* @throws null suppress hinting on the thrown exception as the default positions and bounding box are correct so catching these is not useful
*/
public function getBoundingBox(): BoundingBox
{
if (null === $this->boundingBox) {
$this->boundingBox = new BoundingBox(new BoundingBoxPosition(-180, -90), new BoundingBoxPosition(180, 90));
}
return $this->boundingBox;
}
public function setScale(?Scale $scale): self
{
$this->scale = $scale;
return $this;
}
public function getScale(): Scale
{
if (null === $this->scale) {
$this->scale = new Scale(1);
}
return $this->scale;
}
/**
* @throws PhpGeoSVGException
*/
public function render(GeometryCollection $geometryCollection): string
{
return ElementRenderer::renderElement(
ElementFactory::buildForGeometryCollection($geometryCollection, new Coordinator($this->getProjection(), $this->getBoundingBox(), $this->getScale()))
);
}
/**
* @throws PhpGeoSVGException
*/
public function toFile(GeometryCollection $geometryCollection, string $path): void
{
file_put_contents($path, $this->render($geometryCollection));
}
}
<file_sep>/docs/feature_test_output.md
# EquiRectangular
|expected|actual|
|:------:|:----:|
|||
|||
# Mercator
|expected|actual|
|:------:|:----:|
|||
|||
# Miller
|expected|actual|
|:------:|:----:|
|||
|||<file_sep>/tests/Unit/Projection/ToblersWorldInASquareProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Projection\ToblersWorldInASquareProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\ToblersWorldInASquareProjection
*/
class ToblersWorldInASquareProjectionTest extends TestCase
{
/**
* @covers ::getWidthToHeightAspectRatio
*/
public function testGetWidthToHeightAspectRatio(): void
{
static::assertSame(1.0, (new ToblersWorldInASquareProjection())->getWidthToHeightAspectRatio());
}
}
<file_sep>/src/Scale/Scale.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Scale;
class Scale
{
private float $factorY;
public function __construct(private float $factorX, ?float $factorY = null)
{
if (null === $factorY) {
$factorY = $factorX;
}
$this->factorY = $factorY;
}
public function getFactorX(): float
{
return $this->factorX;
}
public function getFactorY(): float
{
return $this->factorY;
}
}
<file_sep>/tests/Feature/GeoSVGWithProjectionAndBoundingBoxTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Feature;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBox;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBoxPosition;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollectionFactory;
use PrinsFrank\PhpGeoSVG\GeoSVG;
use PrinsFrank\PhpGeoSVG\Projection\EquiRectangularProjection;
use PrinsFrank\PhpGeoSVG\Projection\MercatorProjection;
use PrinsFrank\PhpGeoSVG\Projection\MillerProjection;
use PrinsFrank\PhpGeoSVG\Scale\Scale;
/**
* @coversNothing
*/
class GeoSVGWithProjectionAndBoundingBoxTest extends TestCase
{
public function testEquiRectangularProjection(): void
{
(new GeoSVG(new EquiRectangularProjection(), new BoundingBox(new BoundingBoxPosition(3.5, 50.8), new BoundingBoxPosition(7.2, 53.5))))
->setScale(new Scale(20))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(__DIR__ . '/geojson/netherlands.geojson'),
__DIR__ . '/actual/netherlands-equirectangular.svg'
);
static::assertFileEquals(__DIR__ . '/expected/netherlands-equirectangular.svg', __DIR__ . '/actual/netherlands-equirectangular.svg');
}
public function testMercatorProjection(): void
{
(new GeoSVG(new MercatorProjection(), new BoundingBox(new BoundingBoxPosition(3.5, 50.8), new BoundingBoxPosition(7.2, 53.5))))
->setScale(new Scale(20))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(__DIR__ . '/geojson/netherlands.geojson'),
__DIR__ . '/actual/netherlands-mercator.svg'
);
static::assertFileEquals(__DIR__ . '/expected/netherlands-mercator.svg', __DIR__ . '/actual/netherlands-mercator.svg');
}
public function testMillerProjection(): void
{
(new GeoSVG(new MillerProjection(), new BoundingBox(new BoundingBoxPosition(3.5, 50.8), new BoundingBoxPosition(7.2, 53.5))))
->setScale(new Scale(20))
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(__DIR__ . '/geojson/netherlands.geojson'),
__DIR__ . '/actual/netherlands-miller.svg'
);
static::assertFileEquals(__DIR__ . '/expected/netherlands-miller.svg', __DIR__ . '/actual/netherlands-miller.svg');
}
}
<file_sep>/.php-cs-fixer.dist.php
<?php
declare(strict_types=1);
return (new PhpCsFixer\Config())
->setRules([
'@PSR12' => true,
'declare_strict_types' => true,
'strict_param' => true,
'psr_autoloading' => true,
'visibility_required' => true,
'elseif' => true,
'no_superfluous_elseif' => true,
'no_useless_else' => true,
'yoda_style' => true,
'ordered_imports' => true,
'no_unused_imports' => true,
'single_line_after_imports' => true,
'php_unit_construct' => true,
'php_unit_test_case_static_method_calls' => true,
'php_unit_test_class_requires_covers' => true,
'align_multiline_comment' => true,
'no_superfluous_phpdoc_tags' => true,
'phpdoc_annotation_without_dot' => true,
'strict_comparison' => true,
'no_extra_blank_lines' => true,
'no_whitespace_in_blank_line' => true,
'single_blank_line_at_eof' => true,
'array_syntax' => ['syntax' => 'short'],
])
->setFinder(
(PhpCsFixer\Finder::create())
->exclude('vendor')
->in(__DIR__)
);
<file_sep>/tests/Unit/Projection/AbstractCylindricalEqualAreaProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Projection\AbstractCylindricalEqualAreaProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\AbstractCylindricalEqualAreaProjection
*/
class AbstractCylindricalEqualAreaProjectionTest extends TestCase
{
/**
* @covers ::getX
*/
public function testGetX(): void
{
$abstractCylindricalProjection = new class extends AbstractCylindricalEqualAreaProjection{
public function getWidthToHeightAspectRatio(): float
{
return 2;
}
};
static::assertSame(0.0, $abstractCylindricalProjection->getX(new Position(-180, 0)));
static::assertSame(90.0, $abstractCylindricalProjection->getX(new Position(-90, 0)));
static::assertSame(180.0, $abstractCylindricalProjection->getX(new Position(0, 0)));
static::assertSame(270.0, $abstractCylindricalProjection->getX(new Position(90, 0)));
static::assertSame(360.0, $abstractCylindricalProjection->getX(new Position(180, 0)));
$abstractCylindricalProjection = new class extends AbstractCylindricalEqualAreaProjection{
public function getWidthToHeightAspectRatio(): float
{
return 42;
}
};
static::assertSame(0.0, $abstractCylindricalProjection->getX(new Position(-180, 0)));
static::assertSame(1890.0, $abstractCylindricalProjection->getX(new Position(-90, 0)));
static::assertSame(3780.0, $abstractCylindricalProjection->getX(new Position(0, 0)));
static::assertSame(5670.0, $abstractCylindricalProjection->getX(new Position(90, 0)));
static::assertSame(7560.0, $abstractCylindricalProjection->getX(new Position(180, 0)));
}
/**
* @covers ::getY
*/
public function testGetY(): void
{
$abstractCylindricalProjection = new class extends AbstractCylindricalEqualAreaProjection{
public function getWidthToHeightAspectRatio(): float
{
return 2;
}
};
static::assertSame(0.0, $abstractCylindricalProjection->getY(new Position(0, 90)));
static::assertEqualsWithDelta(26.360, $abstractCylindricalProjection->getY(new Position(0, 45)), 0.001);
static::assertSame(90.0, $abstractCylindricalProjection->getY(new Position(0, 0)));
static::assertEqualsWithDelta(153.639, $abstractCylindricalProjection->getY(new Position(0, -45)), 0.001);
static::assertSame(180.0, $abstractCylindricalProjection->getY(new Position(0, -90)));
}
/**
* @covers ::getMaxX
*/
public function testGetMaxX(): void
{
$abstractCylindricalProjection = new class extends AbstractCylindricalEqualAreaProjection{
public function getWidthToHeightAspectRatio(): float
{
return 1;
}
};
static::assertSame(180.0, $abstractCylindricalProjection->getMaxX());
$abstractCylindricalProjection = new class extends AbstractCylindricalEqualAreaProjection{
public function getWidthToHeightAspectRatio(): float
{
return 42;
}
};
static::assertSame(7560.0, $abstractCylindricalProjection->getMaxX());
}
/**
* @covers ::getMaxY
*/
public function testGetMaxY(): void
{
$abstractCylindricalProjection = new class extends AbstractCylindricalEqualAreaProjection{
public function getWidthToHeightAspectRatio(): float
{
return 1;
}
};
static::assertSame(180.0, $abstractCylindricalProjection->getMaxY());
}
/**
* @covers ::getMaxLatitude
*/
public function testGetMaxLatitude(): void
{
$abstractCylindricalProjection = new class extends AbstractCylindricalEqualAreaProjection{
public function getWidthToHeightAspectRatio(): float
{
return 1;
}
};
static::assertSame(90.0, $abstractCylindricalProjection->getMaxLatitude());
}
}
<file_sep>/tests/Unit/Geometry/GeometryObject/MultiLineStringTest.php
<?php
declare(strict_types=1);
namespace Geometry\GeometryObject;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiLineString;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiLineString
*/
class MultiLineStringTest extends TestCase
{
/**
* @covers ::getLineStrings
* @covers ::addLineString
*/
public function testGetAddPositions(): void
{
$multiLineString = new MultiLineString();
static::assertSame([], $multiLineString->getLineStrings());
$lineString1 = new LineString();
$multiLineString->addLineString($lineString1);
static::assertSame([$lineString1], $multiLineString->getLineStrings());
$lineString2 = new LineString();
$multiLineString->addLineString($lineString2);
static::assertSame([$lineString1, $lineString2], $multiLineString->getLineStrings());
}
}
<file_sep>/src/Html/Elements/SvgElement.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Elements;
use PrinsFrank\PhpGeoSVG\Html\Elements\Definition\ForeignElement;
class SvgElement extends Element implements ForeignElement
{
public const XMLNS = 'http://www.w3.org/2000/svg';
public const VERSION = '1.1';
/** @var array<string, string> */
protected array $attributes = [
'xmlns' => self::XMLNS,
'version' => self::VERSION
];
public function getTagName(): string
{
return 'svg';
}
}
<file_sep>/tests/Unit/Geometry/GeometryObject/GeometryObjectTest.php
<?php
declare(strict_types=1);
namespace Geometry\GeometryObject;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\GeometryObject;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\GeometryObject
*/
class GeometryObjectTest extends TestCase
{
private GeometryObject $geometryObject;
protected function setUp(): void
{
parent::setUp();
$this->geometryObject = new class () extends GeometryObject {};
}
/**
* @covers ::getTitle
* @covers ::setTitle
*/
public function testTitle(): void
{
$geometryObject = $this->geometryObject;
static::assertNull($geometryObject->getTitle());
$geometryObject->setTitle('foo');
static::assertSame('foo', $geometryObject->getTitle());
$geometryObject->setTitle(null);
static::assertNull($geometryObject->getTitle());
}
/**
* @covers ::getFeatureClass
* @covers ::setFeatureClass
*/
public function testFeatureClass(): void
{
$geometryObject = $this->geometryObject;
static::assertNull($geometryObject->getFeatureClass());
$geometryObject->setFeatureClass('foo');
static::assertSame('foo', $geometryObject->getFeatureClass());
}
}
<file_sep>/tests/Unit/GeoSVGTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBox;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBoxPosition;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollection;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiLineString;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\GeoSVG;
use PrinsFrank\PhpGeoSVG\Projection\EquiRectangularProjection;
use PrinsFrank\PhpGeoSVG\Projection\MercatorProjection;
use PrinsFrank\PhpGeoSVG\Scale\Scale;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\GeoSVG
*/
class GeoSVGTest extends TestCase
{
/**
* @covers ::__construct
* @covers ::getProjection
*/
public function testGetProjectionDefaultsEquiRectangular(): void
{
static::assertInstanceOf(EquiRectangularProjection::class, (new GeoSVG())->getProjection());
}
/**
* @covers ::__construct
* @covers ::getProjection
*/
public function testGetProjectionReturnsProjectionProvidedUsingConstructor(): void
{
$projection = new MercatorProjection();
static::assertSame($projection, (new GeoSVG($projection))->getProjection());
}
/**
* @covers ::setProjection
* @covers ::getProjection
*/
public function testGetProjectionReturnsProjectionProvidedUsingSetProjectionMethod(): void
{
$projection = new MercatorProjection();
static::assertSame($projection, (new GeoSVG())->setProjection($projection)->getProjection());
}
/**
* @covers ::__construct
* @covers ::getBoundingBox
*/
public function testGetBoundingBoxReturnsDefaultOne(): void
{
static::assertEquals(
new BoundingBox(new BoundingBoxPosition(-180, -90), new BoundingBoxPosition(180, 90)),
(new GeoSVG())->getBoundingBox()
);
}
/**
* @covers ::__construct
* @covers ::getBoundingBox
*/
public function testGetBoundingBoxReturnsBoundingBoxProvidedUsingConstructor(): void
{
$boundingBox = new BoundingBox(new BoundingBoxPosition(1, 2), new BoundingBoxPosition(3, 4));
static::assertSame($boundingBox, (new GeoSVG(null, $boundingBox))->getBoundingBox());
}
/**
* @covers ::setBoundingBox
* @covers ::getBoundingBox
*/
public function testGetBoundingBoxReturnsBoundingBoxProvidedUsingSetBoundingBoxMethod(): void
{
$boundingBox = new BoundingBox(new BoundingBoxPosition(1, 2), new BoundingBoxPosition(3, 4));
static::assertSame($boundingBox, (new GeoSVG())->setBoundingBox($boundingBox)->getBoundingBox());
}
/**
* @covers ::getScale
* @covers ::setScale
*/
public function testScale(): void
{
$geoSVG = new GeoSVG();
static::assertEquals(new Scale(1), $geoSVG->getScale());
$scale = new Scale(10);
$geoSVG->setScale($scale);
static::assertSame($scale, $geoSVG->getScale());
}
/**
* @covers ::render
*/
public function testRender(): void
{
static::assertSame(
'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="720" height="360" viewbox="0 0 720 360">' . PHP_EOL .
' <g>' . PHP_EOL .
' <path d="M0 0"/>' . PHP_EOL .
' </g>' . PHP_EOL .
'</svg>' . PHP_EOL,
(new GeoSVG())->render(
(new GeometryCollection())
->addGeometryObject(
(new MultiLineString())
->addLineString(
(new LineString())
->addPosition(new Position(-180, 90))
)
)
)
);
}
/**
* @covers ::toFile
*/
public function testToFile(): void
{
(new GeoSVG())->toFile(
(new GeometryCollection())
->addGeometryObject(
(new MultiLineString())
->addLineString(
(new LineString())
->addPosition(new Position(-180, 90))
)
),
__DIR__ . '/geo_svg_test_actual.svg'
);
static::assertFileEquals(__DIR__ . '/geo_svg_test_expected.svg', __DIR__ . '/geo_svg_test_actual.svg');
}
}
<file_sep>/src/Html/Elements/Text/TextContent.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Elements\Text;
class TextContent
{
public function __construct(protected ?string $content = null)
{
}
public function setContent(?string $content): self
{
$this->content = $content;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
}
<file_sep>/tests/Unit/Projection/BalthasartProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Projection\BalthasartProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\BalthasartProjection
*/
class BalthasartProjectionTest extends TestCase
{
/**
* @covers ::getWidthToHeightAspectRatio
*/
public function testGetWidthToHeightAspectRatio(): void
{
static::assertSame(1.298, (new BalthasartProjection())->getWidthToHeightAspectRatio());
}
}
<file_sep>/tests/Unit/Geometry/Position/PositionTest.php
<?php
declare(strict_types=1);
namespace Geometry\Position;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Exception\InvalidPositionException;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\Position\Position
*/
class PositionTest extends TestCase
{
/**
* @covers ::__construct
*/
public function testThrowsExceptionWhenLongitudeTooHigh(): void
{
$this->expectException(InvalidPositionException::class);
$this->expectExceptionMessage('The longitude should be between -180 and 180, "181.01" provided.');
new Position(181.01, 0);
}
/**
* @covers ::__construct
*/
public function testThrowsExceptionWhenLongitudeTooLow(): void
{
$this->expectException(InvalidPositionException::class);
$this->expectExceptionMessage('The longitude should be between -180 and 180, "-181.01" provided.');
new Position(-181.01, 0);
}
/**
* @covers ::__construct
*/
public function testThrowsExceptionWhenLatitudeTooHigh(): void
{
$this->expectException(InvalidPositionException::class);
$this->expectExceptionMessage('The latitude should be between -90 and 90, "91.01" provided.');
new Position(0, 91.01);
}
/**
* @covers ::__construct
*/
public function testThrowsExceptionWhenLatitudeTooLow(): void
{
$this->expectException(InvalidPositionException::class);
$this->expectExceptionMessage('The latitude should be between -90 and 90, "-91.01" provided.');
new Position(0, -91.01);
}
/**
* @covers ::__construct
*/
public function testValidBoundingBoxPositions(): void
{
new Position(0, 0);
new Position(180, 90);
new Position(-180, 90);
new Position(180, -90);
new Position(-180, -90);
// There are no assertions as we only check if there is no exception thrown here
$this->addToAssertionCount(1);
}
/**
* @covers ::__construct
* @covers ::hasElevation
*/
public function testHasElevation(): void
{
static::assertFalse((new Position(0, 0))->hasElevation());
static::assertFalse((new Position(0, 0, null))->hasElevation());
static::assertFalse((new Position(0, 0, 0))->hasElevation());
static::assertFalse((new Position(0, 0, 0.0))->hasElevation());
static::assertTrue((new Position(0, 0, -42))->hasElevation());
static::assertTrue((new Position(0, 0, -42.0))->hasElevation());
static::assertTrue((new Position(0, 0, 42))->hasElevation());
static::assertTrue((new Position(0, 0, 42.0))->hasElevation());
}
}
<file_sep>/src/Exception/InvalidBoundingBoxPositionException.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Exception;
class InvalidBoundingBoxPositionException extends PhpGeoSVGException
{
}
<file_sep>/src/Html/Rendering/AttributeRenderer.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Rendering;
use PrinsFrank\PhpGeoSVG\Exception\InvalidArgumentException;
class AttributeRenderer
{
/**
* @param array<string, string> $attributes
* @throws InvalidArgumentException
*/
public static function renderAttributes(array $attributes): ?string
{
$attributesString = null;
foreach ($attributes as $attributeName => $attributeValue) {
if (false === is_string($attributeName)) {
throw new InvalidArgumentException('Attribute names have to be of type string, "' . gettype($attributeName) . '"(' . $attributeName . ') given.');
}
if (false === is_string($attributeValue)) {
throw new InvalidArgumentException('Attribute values have to be of type string, "' . gettype($attributeValue) . '"(' . $attributeValue . ') given.');
}
if (null !== $attributesString) {
$attributesString .= ' ';
}
$attributesString .= self::renderAttribute($attributeName, $attributeValue);
}
return $attributesString;
}
public static function renderAttribute(string $attributeName, string $attributeValue): string
{
return $attributeName . '="' . str_replace(['\'', '"'], ['\\\'', '\''], $attributeValue) . '"';
}
}
<file_sep>/src/Projection/SmythProjection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Projection;
class SmythProjection extends AbstractCylindricalEqualAreaProjection
{
public function getWidthToHeightAspectRatio(): float
{
return 2;
}
}
<file_sep>/src/Geometry/GeometryObject/GeometryObjectFactory.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\GeometryObject;
use PrinsFrank\PhpGeoSVG\Exception\InvalidPositionException;
use PrinsFrank\PhpGeoSVG\Exception\NotImplementedException;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
class GeometryObjectFactory
{
/**
* @throws NotImplementedException
* @throws InvalidPositionException
*/
public static function createForGeoJsonFeatureGeometry(array $featureGeometry): ?GeometryObject
{
return match ($featureGeometry['type']) {
'LineString' => self::createForLineStringCoordinates($featureGeometry['coordinates']),
'MultiLineString' => self::createForMultiLineStringCoordinates($featureGeometry['coordinates']),
'MultiPoint' => self::createForMultiPointCoordinates($featureGeometry['coordinates']),
'MultiPolygon' => self::createForMultiPolygonCoordinates($featureGeometry['coordinates']),
'Point' => self::createForPointCoordinates($featureGeometry['coordinates']),
'Polygon' => self::createForPolygonCoordinates($featureGeometry['coordinates']),
default => throw new NotImplementedException('Feature geometries of type "' . $featureGeometry['type'] . '" are currently not supported')
};
}
/**
* @throws InvalidPositionException
*/
public static function createForLineStringCoordinates(array $coordinates): LineString
{
$lineString = new LineString();
foreach ($coordinates as $coordinate) {
$lineString->addPosition(new Position($coordinate[0], $coordinate[1], $coordinate[2] ?? null));
}
return $lineString;
}
/**
* @throws InvalidPositionException
*/
public static function createForMultiLineStringCoordinates(array $coordinates): MultiLineString
{
$multiLineString = new MultiLineString();
foreach ($coordinates as $lineStringCoordinates) {
$multiLineString->addLineString(self::createForLineStringCoordinates($lineStringCoordinates));
}
return $multiLineString;
}
public static function createForMultiPointCoordinates(array $coordinates): MultiPoint
{
$multiPoint = new MultiPoint();
foreach ($coordinates as $coordinate) {
$multiPoint->addPoint(self::createForPointCoordinates($coordinate));
}
return $multiPoint;
}
/**
* @throws InvalidPositionException
*/
public static function createForMultiPolygonCoordinates(array $coordinates): MultiPolygon
{
$multiPolygon = new MultiPolygon();
foreach ($coordinates as $polygonCoordinates) {
$polygon = self::createForPolygonCoordinates($polygonCoordinates);
if (null === $polygon) {
continue;
}
$multiPolygon->addPolygon($polygon);
}
return $multiPolygon;
}
/**
* @throws InvalidPositionException
*/
public static function createForPointCoordinates(array $coordinates): Point
{
return new Point(new Position($coordinates[0], $coordinates[1], $coordinates[2] ?? null));
}
/**
* @throws InvalidPositionException
*/
public static function createForPolygonCoordinates(array $coordinates): ?Polygon
{
$exteriorCoordinates = array_shift($coordinates);
if (null === $exteriorCoordinates) {
return null;
}
$polygon = new Polygon(self::createForLineStringCoordinates($exteriorCoordinates));
foreach ($coordinates as $lineStringData) {
$polygon->addInteriorRing(self::createForLineStringCoordinates($lineStringData));
}
return $polygon;
}
}
<file_sep>/src/Exception/PhpGeoSVGException.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Exception;
use Exception;
abstract class PhpGeoSVGException extends Exception
{
}
<file_sep>/tests/Unit/Projection/MillerProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Projection\MillerProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\MillerProjection
*/
class MillerProjectionTest extends TestCase
{
/**
* @covers ::getY
*/
public function testGetY(): void
{
static::assertEqualsWithDelta(0.3, (new MillerProjection())->getY(new Position(0, 90)), 0.1);
static::assertEqualsWithDelta(51.8, (new MillerProjection())->getY(new Position(0, 45)), 0.1);
static::assertEqualsWithDelta(72.0, (new MillerProjection())->getY(new Position(0, 0)), 0.1);
static::assertEqualsWithDelta(92.1, (new MillerProjection())->getY(new Position(0, -45)), 0.1);
static::assertEqualsWithDelta(143.7, (new MillerProjection())->getY(new Position(0, -90)), 0.1);
}
/**
* @covers ::getMaxY
*/
public function testGetMaxY(): void
{
static::assertSame(144.0, (new MillerProjection())->getMaxY());
}
}
<file_sep>/src/Html/Elements/GroupElement.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Elements;
use PrinsFrank\PhpGeoSVG\Html\Elements\Definition\ForeignElement;
class GroupElement extends Element implements ForeignElement
{
public function getTagName(): string
{
return 'g';
}
}
<file_sep>/tests/Unit/Geometry/GeometryObject/PointTest.php
<?php
declare(strict_types=1);
namespace Geometry\GeometryObject;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Point;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Point
*/
class PointTest extends TestCase
{
/**
* @covers ::__construct
* @covers ::getPosition
*/
public function testPosition(): void
{
$position = new Position(0, 0);
$point = new Point($position);
static::assertSame($position, $point->getPosition());
}
}
<file_sep>/src/Geometry/GeometryCollection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\GeometryObject;
class GeometryCollection
{
/** @var GeometryObject[] */
protected array $geometryObjects = [];
public function addGeometryObject(GeometryObject $geometryObject): self
{
$this->geometryObjects[] = $geometryObject;
return $this;
}
/**
* @return GeometryObject[]
*/
public function getGeometryObjects(): array
{
return $this->geometryObjects;
}
}
<file_sep>/src/Exception/RecursionException.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Exception;
class RecursionException extends PhpGeoSVGException
{
}
<file_sep>/tests/Unit/Projection/BehrmannProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Projection\BehrmannProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\BehrmannProjection
*/
class BehrmannProjectionTest extends TestCase
{
/**
* @covers ::getWidthToHeightAspectRatio
*/
public function testGetWidthToHeightAspectRatio(): void
{
static::assertEqualsWithDelta(2.356, (new BehrmannProjection())->getWidthToHeightAspectRatio(), 0.001);
}
}
<file_sep>/tests/Unit/Geometry/GeometryObject/LineStringTest.php
<?php
declare(strict_types=1);
namespace Geometry\GeometryObject;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString
*/
class LineStringTest extends TestCase
{
/**
* @covers ::getPositions
* @covers ::addPosition
*/
public function testGetAddPositions(): void
{
$lineString = new LineString();
static::assertSame([], $lineString->getPositions());
$position1 = new Position(0, 0);
$lineString->addPosition($position1);
static::assertSame([$position1], $lineString->getPositions());
$position2 = new Position(0, 0);
$lineString->addPosition($position2);
static::assertSame([$position1, $position2], $lineString->getPositions());
}
}
<file_sep>/src/Geometry/Position/Position.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\Position;
use PrinsFrank\PhpGeoSVG\Exception\InvalidPositionException;
class Position
{
public const MIN_LONGITUDE = -180;
public const MAX_LONGITUDE = 180;
public const LONGITUDE_THRESHOLD = 1;
public const TOTAL_LONGITUDE = self::MAX_LONGITUDE - self::MIN_LONGITUDE;
public const MIN_LATITUDE = -90;
public const MAX_LATITUDE = 90;
public const LATITUDE_THRESHOLD = 1;
public const TOTAL_LATITUDE = self::MAX_LATITUDE - self::MIN_LATITUDE;
/**
* The coordinate reference system for all GeoJSON coordinates is a
* geographic coordinate reference system, using the World Geodetic
* System 1984 (WGS 84) [WGS84] datum, with longitude and latitude units
* of decimal degrees. This is equivalent to the coordinate reference
* system identified by the Open Geospatial Consortium (OGC) URN
* urn:ogc:def:crs:OGC::CRS84. An OPTIONAL third-position element SHALL
* be the height in meters above or below the WGS 84 reference
* ellipsoid. In the absence of elevation values, applications
* sensitive to height or depth SHOULD interpret positions as being at
* local ground or sea level
*
* @throws InvalidPositionException
*/
public function __construct(public float $longitude, public float $latitude, public ?float $elevation = null)
{
if ($this->longitude > (static::MAX_LONGITUDE + static::LONGITUDE_THRESHOLD) || $this->longitude < (static::MIN_LONGITUDE - static::LONGITUDE_THRESHOLD)) {
throw new InvalidPositionException('The longitude should be between ' . static::MIN_LONGITUDE . ' and ' . static::MAX_LONGITUDE . ', "' . $this->longitude . '" provided.');
}
if ($this->latitude > (static::MAX_LATITUDE + static::LATITUDE_THRESHOLD) || $this->latitude < (static::MIN_LATITUDE - static::LATITUDE_THRESHOLD)) {
throw new InvalidPositionException('The latitude should be between ' . static::MIN_LATITUDE . ' and ' . static::MAX_LATITUDE . ', "' . $this->latitude . '" provided.');
}
}
public function hasElevation(): bool
{
return null !== $this->elevation && 0.0 !== $this->elevation;
}
}
<file_sep>/tests/Unit/Projection/HoboDyerProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Projection\HoboDyerProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\HoboDyerProjection
*/
class HoboDyerProjectionTest extends TestCase
{
/**
* @covers ::getWidthToHeightAspectRatio
*/
public function testGetWidthToHeightAspectRatio(): void
{
static::assertSame(1.977, (new HoboDyerProjection())->getWidthToHeightAspectRatio());
}
}
<file_sep>/tests/Unit/Html/Elements/TitleElementTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Html\Elements;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Html\Elements\TitleElement;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Html\Elements\TitleElement
*/
class TitleElementTest extends TestCase
{
/**
* @covers ::getTagName
*/
public function testGetTagName(): void
{
static::assertSame('title', (new TitleElement())->getTagName());
}
}
<file_sep>/src/Projection/LambertProjection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Projection;
class LambertProjection extends AbstractCylindricalEqualAreaProjection
{
public function getWidthToHeightAspectRatio(): float
{
return M_PI;
}
}
<file_sep>/SECURITY.md
# Security Policy
PLEASE DON'T DISCLOSE SECURITY-RELATED ISSUES PUBLICLY, [SEE BELOW](#reporting-a-vulnerability).
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| 0.0.X | :white_check_mark: |
## Reporting a Vulnerability
If you discover a security vulnerability within this package, please send an email to <NAME> at <EMAIL>. All security vulnerabilities will be promptly addressed.
<file_sep>/README.md

# PHP Geo SVG

[](https://scrutinizer-ci.com/g/PrinsFrank/php-geo-svg/build-status/main)
[](https://scrutinizer-ci.com/g/PrinsFrank/php-geo-svg/?branch=main)
[](https://scrutinizer-ci.com/g/PrinsFrank/php-geo-svg/?branch=main)

**Generate and display maps without external services or compromising on privacy.**
## Why this package?
When searching for high quality SVG's for [my blog](https://prinsfrank.nl/countries), I ran into the issue that all SVG's where either too low quality, heavily polluted with unnecessary elements by the tool they were generated with, or in the wrong projection. This package provides the flexibility to generate maps manually or from geojson files, which are more readily available.
## Features
- Supports creation of SVGs from GeoJSON (directly from file, as a JSON string or from an array) and manual GeometryCollection.
- Output the svg directly to your user on request or output to a file.
- Render an entire world map or only part of it by using a bounding box.
- Easy support for projections. Currently supported: EquiRectangular, Mercator, Miller and several Equal area projections (Lambert, Behrmann, Smyth, Trystan, Hobo-Dyer, Gall-Peters, Balthasart and Tobler's world in a square) Please open a PR to add any extra ones.
- When you create or edit a GeometryCollection, a Fluent Interface is provided to allow for method chaining.
|Showcase|
|:----:|
|Countries - Equirectangular projection <div></div>|
|Netherlands - Mercator projection <div></div>|
## Table of Contents
- [Why this package?](#why-this-package)
- [Features](#features)
- [Table of Contents](#table-of-contents)
- [Setup](#setup)
- [The basics; creating an SVG](#the-basics-creating-an-svg)
- [From a GeoJSON file](#from-a-geojson-file)
- [From a GeoJSON string](#from-a-geojson-string)
- [From a GeoJSON array](#from-a-geojson-array)
- [From building your own GeometryCollection](#from-building-your-own-geometrycollection)
- [Different globe-to-plane transformations; Projections](#different-globe-to-plane-transformations-projections)
- [Displaying only parts of the world; Using bounding boxes](#displaying-only-parts-of-the-world-using-bounding-boxes)
## Setup
> Make sure you are running PHP 8.0 or higher to use this package
To start right away, run the following command in your composer project;
```composer require prinsfrank/php-geo-svg```
Or for development only;
```composer require prinsfrank/php-geo-svg --dev```
## The basics; creating an SVG
Let's say we want to create the following simple continent map:

There are multiple ways we can go about creating this map in svg using this package;
### From a GeoJSON file
To create an SVG from a GeoJson file, create a new 'GeometryCollection' by calling the 'createFromGeoJSONFilePath' method on the 'GeometryCollectionFactory' as follows;
<details>
<summary>Show code</summary>
With variables:
```
$geoSVG = new GeoSVG();
$geometryCollection = GeometryCollectionFactory::createFromGeoJSONFilePath('/path/to/file.geojson');
$geoSVG->toFile($geometryCollection, 'output/file.svg');
```
Fluent:
```
(new GeoSVG())
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(__DIR__ . '/path/to/file.geojson'),
'output/file.svg'
);
```
</details>
### From a GeoJSON string
To create an SVG from a GeoJson string, create a new 'GeometryCollection' by calling the 'createFromGeoJsonString' method on the 'GeometryCollectionFactory' as follows;
<details>
<summary>Show code</summary>
With variables:
```
$geoJsonString = '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-177,74],[-80,9],[-25,82]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-80,9],[-37,-7],[-70,-55]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-12,36],[30,37],[27,70],[-24,66]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-12,36],[30,37],[51,11],[22,-35],[-17,17]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[27,70],[30,37],[51,11],[131,-2],[171,67]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[115,-15],[153,-15],[148,-43],[114,-35]]]}}]}';
$geoSVG = new GeoSVG();
$geometryCollection = GeometryCollectionFactory::createFromGeoJsonString($geoJsonString);
$geoSVG->toFile($geometryCollection, 'output/file.svg');
```
Fluent:
```
$geoJsonString = '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-177,74],[-80,9],[-25,82]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-80,9],[-37,-7],[-70,-55]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-12,36],[30,37],[27,70],[-24,66]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-12,36],[30,37],[51,11],[22,-35],[-17,17]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[27,70],[30,37],[51,11],[131,-2],[171,67]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[115,-15],[153,-15],[148,-43],[114,-35]]]}}]}';
(new GeoSVG())
->toFile(
GeometryCollectionFactory::createFromGeoJsonString($geoJsonString),
'output/file.svg'
);
```
</details>
### From a GeoJSON array
To create an SVG from a GeoJson array, create a new 'GeometryCollection' by calling the 'createFromGeoJSONArray' method on the 'GeometryCollectionFactory' as follows;
<details>
<summary>Show code</summary>
With variables:
```
$geoJsonArray = ['type'=>'FeatureCollection','features'=>[['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[-177,74],[-80,9],[-25,82]]]]],['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[-80,9],[-37,-7],[-70,-55]]]]],['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[-12,36],[30,37],[27,70],[-24,66]]]]],['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[-12,36],[30,37],[51,11],[22,-35],[-17,17]]]]],['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[27,70],[30,37],[51,11],[131,-2],[171,67]]]]],['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[115,-15],[153,-15],[148,-43],[114,-35]]]]]]];
$geoSVG = new GeoSVG();
$geometryCollection = GeometryCollectionFactory::createFromGeoJsonArray($geoJsonArray);
$geoSVG->toFile($geometryCollection, 'output/file.svg');
```
Fluent:
```
$geoJsonArray = ['type'=>'FeatureCollection','features'=>[['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[-177,74],[-80,9],[-25,82]]]]],['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[-80,9],[-37,-7],[-70,-55]]]]],['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[-12,36],[30,37],[27,70],[-24,66]]]]],['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[-12,36],[30,37],[51,11],[22,-35],[-17,17]]]]],['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[27,70],[30,37],[51,11],[131,-2],[171,67]]]]],['type'=>'Feature','properties'=>['featurecla'=>'Continent'],'geometry'=>['type'=>'MultiLineString','coordinates'=>[[[115,-15],[153,-15],[148,-43],[114,-35]]]]]]];
(new GeoSVG())
->toFile(
GeometryCollectionFactory::createFromGeoJsonArray($geoJsonArray),
'output/file.svg'
);
```
</details>
### From building your own GeometryCollection
To build an SVG manually from a GeometryCollection, create the object and add any geometry you want:
<details>
<summary>Show code</summary>
With variables:
```
$geoSVG = new GeoSVG();
$geometryCollection = new GeometryCollection();
$continents = new MultiPolygon();
$geometryCollection->addGeometryObject($continents);
$outerBorderNorthAmerica = new LineString();
$outerBorderNorthAmerica->addPosition(new Position(-177, 74));
$outerBorderNorthAmerica->addPosition(new Position(-80, 9));
$outerBorderNorthAmerica->addPosition(new Position(-25, 82));
$outerBorderNorthAmerica->setFeatureClass('Continent');
$outerBorderNorthAmerica->setTitle('North America');
$polygonNorthAmerica = new Polygon($outerBorderNorthAmerica);
$continents->addPolygon($polygonNorthAmerica);
$outerBorderSouthAmerica = new LineString();
$outerBorderSouthAmerica->addPosition(new Position(-80, 9));
$outerBorderSouthAmerica->addPosition(new Position(-37, -7));
$outerBorderSouthAmerica->addPosition(new Position(-70, -55));
$outerBorderSouthAmerica->setFeatureClass('Continent');
$outerBorderSouthAmerica->setTitle('South America');
$polygonSouthAmerica = new Polygon($outerBorderSouthAmerica);
$continents->addPolygon($polygonSouthAmerica);
$outerBorderEurope = new LineString();
$outerBorderEurope->addPosition(new Position(-12, 36));
$outerBorderEurope->addPosition(new Position(30, 37));
$outerBorderEurope->addPosition(new Position(27, 70));
$outerBorderEurope->addPosition(new Position(-24, 66));
$outerBorderEurope->setFeatureClass('Continent');
$outerBorderEurope->setTitle('Europe');
$polygonEurope = new Polygon($outerBorderEurope);
$continents->addPolygon($polygonEurope);
$outerBorderAfrica = new LineString();
$outerBorderAfrica->addPosition(new Position(-12, 36));
$outerBorderAfrica->addPosition(new Position(30, 37));
$outerBorderAfrica->addPosition(new Position(51, 11));
$outerBorderAfrica->addPosition(new Position(22, -35));
$outerBorderAfrica->addPosition(new Position(-17, 17));
$outerBorderAfrica->setFeatureClass('Continent');
$outerBorderAfrica->setTitle('Africa');
$polygonAfrica = new Polygon($outerBorderAfrica);
$continents->addPolygon($polygonAfrica);
$outerBorderAsia = new LineString();
$outerBorderAsia->addPosition(new Position(27, 70));
$outerBorderAsia->addPosition(new Position(30, 37));
$outerBorderAsia->addPosition(new Position(51, 11));
$outerBorderAsia->addPosition(new Position(131, -2));
$outerBorderAsia->addPosition(new Position(171, 67));
$outerBorderAsia->setFeatureClass('Continent');
$outerBorderAsia->setTitle('Asia');
$polygonAsia = new Polygon($outerBorderAsia);
$continents->addPolygon($polygonAsia);
$outerBorderAustralia = new LineString();
$outerBorderAustralia->addPosition(new Position(115, -15));
$outerBorderAustralia->addPosition(new Position(153, -15));
$outerBorderAustralia->addPosition(new Position(148, -43));
$outerBorderAustralia->addPosition(new Position(114, -35));
$outerBorderAustralia->setFeatureClass('Continent');
$outerBorderAustralia->setTitle('Australia');
$polygonAustralia = new Polygon($outerBorderAustralia);
$continents->addPolygon($polygonAustralia);
$geoSVG->toFile($geometryCollection, 'output/file.svg');
```
Fluent:
```
(new GeoSVG())
->toFile(
(new GeometryCollection())
->addGeometryObject(
(new MultiPolygon())
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(-177, 74))
->addPosition(new Position(-80, 9))
->addPosition(new Position(-25, 82))
->setFeatureClass('Continent')
->setTitle('North America')
)
)
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(-80, 9))
->addPosition(new Position(-37, -7))
->addPosition(new Position(-70, -55))
->setFeatureClass('Continent')
->setTitle('South America')
)
)
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(-12, 36))
->addPosition(new Position(30, 37))
->addPosition(new Position(27, 70))
->addPosition(new Position(-24, 66))
->setFeatureClass('Continent')
->setTitle('Europe')
)
)
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(-12, 36))
->addPosition(new Position(30, 37))
->addPosition(new Position(51, 11))
->addPosition(new Position(22, -35))
->addPosition(new Position(-17, 17))
->setFeatureClass('Continent')
->setTitle('Africa')
)
)
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(27, 70))
->addPosition(new Position(30, 37))
->addPosition(new Position(51, 11))
->addPosition(new Position(131, -2))
->addPosition(new Position(171, 67))
->setFeatureClass('Continent')
->setTitle('Asia')
)
)
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(115, -15))
->addPosition(new Position(153, -15))
->addPosition(new Position(148, -43))
->addPosition(new Position(114, -35))
->setFeatureClass('Continent')
->setTitle('Australia')
)
)
),
'output/file.svg'
);
```
</details>
## Different globe-to-plane transformations; Projections
If you prefer a different projection other than the default EquiRectangular, you can! Currently, the following projections are supported, but please feel free to add any and open a PR;
- Equirectangular
- Mercator
- Miller
To specify the projection you want to use, you can do so either using the constructor;
```
$geoSVG = new GeoSVG(new MercatorProjection);
```
Or using the 'setProjection' method;
```
$geoSVG = new GeoSVG();
$geoSVG->setProjection(new MercatorProjection);
```
## Displaying only parts of the world; Using bounding boxes
If you want to use a bounding box, you have to know both the most southWestern and northEastern coordinates you want to show, and create 'BoundingBoxPositions' for both of them. Pass those along to a bounding box object and you have yourself a bounding box;
```
$northEastern = new BoundingBoxPosition(7.2, 53.5);
$southWestern = new BoundingBoxPosition(3.5, 50.8);
$boundingBox = new BoundingBox($southWestern, $northEastern);
```
To actually use it, either pass the bounding box in the constructor after the projection;
```
$geoSVG = new GeoSVG($projection, $boundingBox);
```
Or set the bounding box using the 'setBoundingBox' method;
```
$geoSVG = new GeoSVG();
$geoSVG->setBoundingBox($boundingBox);
```
<file_sep>/tests/Unit/Html/Factory/ElementFactoryTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Html\Factory;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Coordinator\Coordinator;
use PrinsFrank\PhpGeoSVG\Exception\NotImplementedException;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollection;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\GeometryObject;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiLineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPoint;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPolygon;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Point;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Polygon;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Html\Elements\CircleElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\Element;
use PrinsFrank\PhpGeoSVG\Html\Elements\GroupElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\PathElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\SvgElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\Text\TextContent;
use PrinsFrank\PhpGeoSVG\Html\Elements\TitleElement;
use PrinsFrank\PhpGeoSVG\Html\Factory\ElementFactory;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Html\Factory\ElementFactory
*/
class ElementFactoryTest extends TestCase
{
/**
* @covers ::buildForGeometryCollection
*/
public function testBuildForGeometryCollectionWithoutGeometryObjects(): void
{
$coordinator = $this->createMock(Coordinator::class);
$coordinator->expects(static::exactly(2))->method('getWidth')->with()->willReturn(200.0);
$coordinator->expects(static::exactly(2))->method('getHeight')->with()->willReturn(100.0);
static::assertEquals(
(new SvgElement())
->setAttribute('width', '200')
->setAttribute('height', '100')
->setAttribute('viewbox', '0 0 200 100'),
ElementFactory::buildForGeometryCollection(new GeometryCollection(), $coordinator)
);
}
/**
* @covers ::buildForGeometryCollection
*/
public function testBuildForGeometryCollection(): void
{
$coordinator = $this->createMock(Coordinator::class);
$coordinator->expects(static::exactly(2))->method('getWidth')->with()->willReturn(200.0);
$coordinator->expects(static::exactly(2))->method('getHeight')->with()->willReturn(100.0);
$geometryCollection = new GeometryCollection();
$geometryCollection->addGeometryObject(
(new LineString())
->addPosition($position1 = new Position(-90, 90))
->addPosition($position2 = new Position(-90, -90))
->addPosition($position3 = new Position(0, 0))
);
$geometryCollection->addGeometryObject(
(new LineString())
->addPosition($position4 = new Position(90, 90))
->addPosition($position5 = new Position(90, -90))
->addPosition($position6 = new Position(0, 0))
);
$coordinator->expects(static::exactly(6))
->method('getX')
->withConsecutive([$position1], [$position2], [$position3], [$position4], [$position5], [$position6])
->willReturnOnConsecutiveCalls(0, 0, 90, 180, 180, 90);
$coordinator->expects(static::exactly(6))
->method('getY')
->withConsecutive([$position1], [$position2], [$position3], [$position4], [$position5], [$position6])
->willReturnOnConsecutiveCalls(180, 0, 90, 180, 0, 90);
static::assertEquals(
(new SvgElement())
->setAttribute('width', '200')
->setAttribute('height', '100')
->setAttribute('viewbox', '0 0 200 100')
->addChildElement(
(new PathElement())->setAttribute('d', 'M0 180 L0 0 L90 90')
)
->addChildElement(
(new PathElement())->setAttribute('d', 'M180 180 L180 0 L90 90')
),
ElementFactory::buildForGeometryCollection($geometryCollection, $coordinator)
);
}
/**
* @covers ::buildForGeometryObject
*/
public function testBuildForGeometryObjectThrowsExceptionOnUnsupportedObject(): void
{
$this->expectException(NotImplementedException::class);
$this->expectExceptionMessage('GeometryObject with class "Foo" can\'t be built yet.');
$geometryObject = $this->getMockBuilder(GeometryObject::class)->setMockClassName('Foo')->getMock();
ElementFactory::buildForGeometryObject($geometryObject, $this->createMock(Coordinator::class));
}
/**
* @covers ::buildForGeometryObject
*/
public function testBuildForGeometryObject(): void
{
$coordinator = $this->createMock(Coordinator::class);
static::assertEquals((new PathElement())->setAttribute('d', ''), ElementFactory::buildForGeometryObject(new LineString(), $coordinator));
static::assertEquals(new GroupElement(), ElementFactory::buildForGeometryObject(new MultiPoint(), $coordinator));
static::assertEquals(new GroupElement(), ElementFactory::buildForGeometryObject(new MultiPolygon(), $coordinator));
static::assertEquals(new GroupElement(), ElementFactory::buildForGeometryObject(new MultiLineString(), $coordinator));
static::assertEquals(
(new GroupElement())->addChildElement((new PathElement())->setAttribute('d', '')),
ElementFactory::buildForGeometryObject(new Polygon(new LineString()), $coordinator)
);
static::assertEquals(
(new CircleElement())->setAttribute('cx', 0)->setAttribute('cy', 0),
ElementFactory::buildForGeometryObject(new Point(new Position(0, 1)), $coordinator)
);
}
/**
* @covers ::buildForGeometryObject
*/
public function testBuildForGeometryObjectBuildsTitleWhenPresent(): void
{
static::assertEquals(
(new PathElement())
->setAttribute('d', '')
->addChildElement(
(new TitleElement())->setTextContent(new TextContent('foo'))
),
ElementFactory::buildForGeometryObject(
(new LineString())->setTitle('foo'),
$this->createMock(Coordinator::class)
)
);
}
/**
* @covers ::buildForGeometryObject
*/
public function testBuildForGeometryObjectSetsFeatureClassWhenPresent(): void
{
static::assertEquals(
(new PathElement())
->setAttribute('d', '')
->setAttribute('data-feature-class', 'foo'),
ElementFactory::buildForGeometryObject(
(new LineString())->setFeatureClass('foo'),
$this->createMock(Coordinator::class)
)
);
}
/**
* @covers ::buildForMultiPolygon
*/
public function testBuildForMultiPolygonWithoutPolygons(): void
{
static::assertEquals(
(new GroupElement()),
ElementFactory::buildForMultiPolygon(new MultiPolygon(), $this->createMock(Coordinator::class))
);
}
/**
* @covers ::buildForMultiPolygon
*/
public function testBuildForMultiPolygon(): void
{
static::assertEquals(
(new GroupElement())
->addChildElement(
(new GroupElement())->addChildElement(
(new PathElement())->setAttribute('d', '')
)
)
->addChildElement(
(new GroupElement())->addChildElement(
(new PathElement())->setAttribute('d', '')
)
),
ElementFactory::buildForMultiPolygon(
(new MultiPolygon())
->addPolygon(new Polygon(new LineString()))
->addPolygon(new Polygon(new LineString())),
$this->createMock(Coordinator::class)
)
);
}
/**
* @covers ::buildForMultiLineString
*/
public function testBuildForMultiLineStringWithoutPolygons(): void
{
static::assertEquals(
(new GroupElement()),
ElementFactory::buildForMultiLineString(new MultiLineString(), $this->createMock(Coordinator::class))
);
}
/**
* @covers ::buildForMultiLineString
*/
public function testBuildForMultiLineString(): void
{
static::assertEquals(
(new GroupElement())
->addChildElement((new PathElement())->setAttribute('d', ''))
->addChildElement((new PathElement())->setAttribute('d', '')),
ElementFactory::buildForMultiLineString(
(new MultiLineString())
->addLineString(new LineString())
->addLineString(new LineString()),
$this->createMock(Coordinator::class)
)
);
}
/**
* @covers ::buildForLineString
*/
public function testBuildForLineString(): void
{
$lineString = new LineString();
$position1 = new Position(0, 45);
$lineString->addPosition($position1);
$position2 = new Position(0, -45);
$lineString->addPosition($position2);
$position3 = new Position(90, 0);
$lineString->addPosition($position3);
$coordinator = $this->createMock(Coordinator::class);
$coordinator->expects(static::exactly(3))
->method('getX')
->withConsecutive([$position1], [$position2], [$position3])
->willReturnOnConsecutiveCalls(0, 0, 100);
$coordinator->expects(static::exactly(3))
->method('getY')
->withConsecutive([$position1], [$position2], [$position3])
->willReturnOnConsecutiveCalls(0, 100, 50);
static::assertEquals(
(new PathElement())->setAttribute('d', 'M0 0 L0 100 L100 50'),
ElementFactory::buildForLineString($lineString, $coordinator)
);
}
/**
* @covers ::buildForMultiPoint
*/
public function testBuildForMultiPointWithoutPoints(): void
{
static::assertEquals(new GroupElement(), ElementFactory::buildForMultiPoint(new MultiPoint(), $this->createMock(Coordinator::class)));
}
/**
* @covers ::buildForMultiPoint
*/
public function testBuildForMultiPoint(): void
{
$multiPoint = new MultiPoint();
$position1 = new Position(-90, -90);
$point1 = new Point($position1);
$multiPoint->addPoint($point1);
$position2 = new Position(90, 90);
$point2 = new Point($position2);
$multiPoint->addPoint($point2);
$coordinator = $this->createMock(Coordinator::class);
$coordinator->expects(static::exactly(2))
->method('getX')
->withConsecutive([$position1], [$position2])
->willReturnOnConsecutiveCalls(-90.0, 90, 0);
$coordinator->expects(static::exactly(2))
->method('getY')
->withConsecutive([$position1], [$position2])
->willReturnOnConsecutiveCalls(-90.0, 90, 0);
static::assertEquals(
(new GroupElement())
->addChildElement((new CircleElement())->setAttribute('cy', -90)->setAttribute('cx', -90))
->addChildElement((new CircleElement())->setAttribute('cy', 90)->setAttribute('cx', 90)),
ElementFactory::buildForMultiPoint($multiPoint, $coordinator)
);
}
/**
* @covers ::buildForPolygon
*/
public function testBuildForPolygonWithoutInteriorRings(): void
{
$lineString = new LineString();
$position1 = new Position(0, 45);
$lineString->addPosition($position1);
$position2 = new Position(0, -45);
$lineString->addPosition($position2);
$polygon = new Polygon($lineString);
$coordinator = $this->createMock(Coordinator::class);
$coordinator->expects(static::exactly(2))
->method('getX')
->withConsecutive([$position1], [$position2])
->willReturnOnConsecutiveCalls(0, 0);
$coordinator->expects(static::exactly(2))
->method('getY')
->withConsecutive([$position1], [$position2])
->willReturnOnConsecutiveCalls(0, 100);
static::assertEquals(
(new GroupElement())
->addChildElement((new PathElement())->setAttribute('d', 'M0 0 L0 100')),
ElementFactory::buildForPolygon($polygon, $coordinator)
);
}
/**
* @covers ::buildForPolygon
*/
public function testBuildForPolygonWithInteriorRings(): void
{
$lineString = new LineString();
$position1 = new Position(0, 45);
$lineString->addPosition($position1);
$position2 = new Position(0, -45);
$lineString->addPosition($position2);
$polygon = new Polygon($lineString);
$interiorLineString = new LineString();
$position3 = new Position(0, 45);
$interiorLineString->addPosition($position3);
$position4 = new Position(0, -45);
$interiorLineString->addPosition($position4);
$polygon->addInteriorRing($interiorLineString);
$coordinator = $this->createMock(Coordinator::class);
$coordinator->expects(static::exactly(4))
->method('getX')
->withConsecutive([$position1], [$position2], [$position3], [$position4])
->willReturnOnConsecutiveCalls(0, 0, 100, 150);
$coordinator->expects(static::exactly(4))
->method('getY')
->withConsecutive([$position1], [$position2], [$position3], [$position4])
->willReturnOnConsecutiveCalls(0, 100, 200, 300);
static::assertEquals(
(new GroupElement())
->addChildElement((new PathElement())->setAttribute('d', 'M0 0 L0 100'))
->addChildElement((new PathElement())->setAttribute('d', 'M100 200 L150 300')),
ElementFactory::buildForPolygon($polygon, $coordinator)
);
}
/**
* @covers ::buildForPoint
*/
public function testBuildForPoint(): void
{
$position = new Position(100, 50);
$coordinator = $this->createMock(Coordinator::class);
$coordinator->expects(static::once())->method('getX')->with($position)->willReturn(13.0);
$coordinator->expects(static::once())->method('getY')->with($position)->willReturn(42.0);
static::assertEquals(
(new CircleElement())->setAttribute('cy', 42)->setAttribute('cx', 13),
ElementFactory::buildForPoint(new Point($position), $coordinator)
);
}
/**
* @covers ::buildForPosition
*/
public function testBuildForPositiont(): void
{
$position = new Position(100, 50);
$coordinator = $this->createMock(Coordinator::class);
$coordinator->expects(static::once())->method('getX')->with($position)->willReturn(13.0);
$coordinator->expects(static::once())->method('getY')->with($position)->willReturn(42.0);
static::assertEquals(
(new CircleElement())->setAttribute('cy', 42)->setAttribute('cx', 13),
ElementFactory::buildForPosition($position, $coordinator)
);
}
}
<file_sep>/tests/Unit/Geometry/GeometryObject/PolygonTest.php
<?php
declare(strict_types=1);
namespace Geometry\GeometryObject;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Polygon;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Polygon
*/
class PolygonTest extends TestCase
{
/**
* @covers ::__construct
* @covers ::getExteriorRing
*/
public function testExteriorRing(): void
{
$exteriorRing = new LineString();
$polygon = new Polygon($exteriorRing);
static::assertSame($exteriorRing, $polygon->getExteriorRing());
}
/**
* @covers ::getInteriorRings
* @covers ::addInteriorRing
*/
public function testInteriorRings(): void
{
$polygon = new Polygon(new LineString());
static::assertSame([], $polygon->getInteriorRings());
$interiorRing1 = new LineString();
$polygon->addInteriorRing($interiorRing1);
static::assertSame([$interiorRing1], $polygon->getInteriorRings());
$interiorRing2 = new LineString();
$polygon->addInteriorRing($interiorRing2);
static::assertSame([$interiorRing1, $interiorRing2], $polygon->getInteriorRings());
}
}
<file_sep>/src/Html/Rendering/ElementRenderer.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Rendering;
use PrinsFrank\PhpGeoSVG\Exception\InvalidArgumentException;
use PrinsFrank\PhpGeoSVG\Exception\RecursionException;
use PrinsFrank\PhpGeoSVG\Html\Elements\Element;
use PrinsFrank\PhpGeoSVG\Html\Elements\Text\TextContent;
class ElementRenderer
{
private const RECURSION_LIMIT = 10;
private const INDENTING_CHAR = ' ';
/**
* @throws RecursionException
*/
public static function renderElement(Element $element, int $currentDepth = 0): string
{
if ($currentDepth++ > self::RECURSION_LIMIT) {
throw new RecursionException('Recursion limit of ' . self::RECURSION_LIMIT . ' Reached');
}
$childElementContent = self::renderChildElements($element->getChildElements(), $currentDepth);
$textContent = self::renderTextContent($element->getTextContent(), $currentDepth);
if (null === $childElementContent && null === $textContent && $element->canSelfClose()) {
return self::renderSelfClosingElement($element);
}
$attributeString = AttributeRenderer::renderAttributes($element->getAttributes());
return '<' . $element->getTagName() . (null !== $attributeString ? ' ' . $attributeString : null) . '>' . PHP_EOL .
$childElementContent . $textContent .
str_repeat(self::INDENTING_CHAR, $currentDepth - 1) . '</' . $element->getTagName() . '>' . PHP_EOL;
}
/**
* @throws InvalidArgumentException
*/
public static function renderSelfClosingElement(Element $element): string
{
if ($element->canSelfClose() === false) {
throw new InvalidArgumentException('Only elements that can self close can be rendered as self closing elements');
}
$attributeString = AttributeRenderer::renderAttributes($element->getAttributes());
return '<' . $element->getTagName() . (null !== $attributeString ? ' ' . $attributeString : null) . '/>' . PHP_EOL;
}
/**
* @param Element[] $childElements
* @throws RecursionException
*/
public static function renderChildElements(array $childElements, int $currentDepth): ?string
{
$childElementString = null;
foreach ($childElements as $childElement) {
$childElementString .= str_repeat(self::INDENTING_CHAR, $currentDepth) . self::renderElement($childElement, $currentDepth);
}
return $childElementString;
}
public static function renderTextContent(?TextContent $textContent, int $currentDepth): ?string
{
if (null !== $textContent) {
return str_repeat(self::INDENTING_CHAR, $currentDepth) . $textContent->getContent() . PHP_EOL;
}
return null;
}
}
<file_sep>/src/Projection/MercatorProjection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Projection;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
class MercatorProjection implements Projection
{
public function getX(Position $position): float
{
return ($position->longitude + 180) * (Position::TOTAL_LONGITUDE * .5 / 360);
}
public function getY(Position $position): float
{
$latitude = $position->latitude;
if ($latitude > $this->getMaxLatitude() - 0.001) {
$latitude = $this->getMaxLatitude() - 0.001;
}
if ($latitude < (-$this->getMaxLatitude()) + 0.001) {
$latitude = (-$this->getMaxLatitude()) + 0.001;
}
return (Position::TOTAL_LATITUDE / 2) - (Position::TOTAL_LONGITUDE * .5 * log(tan((M_PI / 4) + (($latitude*M_PI / 180) / 2))) / (2 * M_PI));
}
public function getMaxX(): float
{
return Position::TOTAL_LONGITUDE * .5;
}
public function getMaxY(): float
{
return Position::TOTAL_LATITUDE;
}
public function getMaxLatitude(): float
{
return 85;
}
}
<file_sep>/src/Geometry/GeometryObject/MultiLineString.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\GeometryObject;
class MultiLineString extends GeometryObject
{
/** @var LineString[] */
protected array $lineStrings = [];
public function addLineString(LineString $lineString): self
{
$this->lineStrings[] = $lineString;
return $this;
}
/**
* @return LineString[]
*/
public function getLineStrings(): array
{
return $this->lineStrings;
}
}
<file_sep>/tests/Unit/Geometry/GeometryCollectionTest.php
<?php
declare(strict_types=1);
namespace Geometry;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollection;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiLineString;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\GeometryCollection
*/
class GeometryCollectionTest extends TestCase
{
/**
* @covers ::addGeometryObject
* @covers ::getGeometryObjects
*/
public function testGetAddGeometryObject(): void
{
$geometryCollection = new GeometryCollection();
static::assertSame([], $geometryCollection->getGeometryObjects());
$lineString = new LineString();
$geometryCollection->addGeometryObject($lineString);
static::assertSame([$lineString], $geometryCollection->getGeometryObjects());
$multiLineString = new MultiLineString();
$geometryCollection->addGeometryObject($multiLineString);
static::assertSame([$lineString, $multiLineString], $geometryCollection->getGeometryObjects());
}
}
<file_sep>/tests/Unit/Geometry/GeometryObject/MultiPointTest.php
<?php
declare(strict_types=1);
namespace Geometry\GeometryObject;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPoint;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Point;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPoint
*/
class MultiPointTest extends TestCase
{
/**
* @covers ::getPoints
* @covers ::addPoint
*/
public function testPositions(): void
{
$multiPoint = new MultiPoint();
static::assertSame([], $multiPoint->getPoints());
$point1 = new Point(new Position(0, 0));
$multiPoint->addPoint($point1);
static::assertSame([$point1], $multiPoint->getPoints());
$point2 = new Point(new Position(0, 0));
$multiPoint->addPoint($point2);
static::assertSame([$point1, $point2], $multiPoint->getPoints());
}
}
<file_sep>/src/Geometry/BoundingBox/BoundingBoxPosition.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\BoundingBox;
use PrinsFrank\PhpGeoSVG\Exception\InvalidBoundingBoxPositionException;
/**
* When crossing the 180th meridian with a bounding box, the bounding box wraps resulting in otherwise invalid coordinates.
* This class purposefully doesn't extend the default position class as otherwise this class could be used in parameters for the position class.
*/
class BoundingBoxPosition
{
public const MIN_LONGITUDE = -360;
public const MAX_LONGITUDE = 360;
public const MIN_LATITUDE = -90;
public const MAX_LATITUDE = 90;
/**
* @throws InvalidBoundingBoxPositionException
*/
public function __construct(public float $longitude, public float $latitude)
{
if ($this->longitude > static::MAX_LONGITUDE || $this->longitude < static::MIN_LONGITUDE) {
throw new InvalidBoundingBoxPositionException('The longitude should be between ' . static::MIN_LONGITUDE . ' and ' . static::MAX_LONGITUDE . ', "' . $this->longitude . '" provided.');
}
if ($this->latitude > static::MAX_LATITUDE || $this->latitude < static::MIN_LATITUDE) {
throw new InvalidBoundingBoxPositionException('The latitude should be between ' . static::MIN_LATITUDE . ' and ' . static::MAX_LATITUDE . ', "' . $this->latitude . '" provided.');
}
}
}
<file_sep>/src/Geometry/GeometryObject/GeometryObject.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\GeometryObject;
abstract class GeometryObject
{
protected ?string $title = null;
protected ?string $featureClass = null;
public function setTitle(?string $title): self
{
$this->title = $title;
return $this;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setFeatureClass(string $featureClass): self
{
$this->featureClass = $featureClass;
return $this;
}
public function getFeatureClass(): ?string
{
return $this->featureClass;
}
}
<file_sep>/src/Projection/AbstractCylindricalEqualAreaProjection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Projection;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
abstract class AbstractCylindricalEqualAreaProjection implements Projection
{
abstract public function getWidthToHeightAspectRatio(): float;
public function getX(Position $position): float
{
return ($position->longitude - Position::MIN_LONGITUDE) * $this->getWidthToHeightAspectRatio() / 2;
}
public function getY(Position $position): float
{
return (-sin(deg2rad($position->latitude)) + 1) * .5 * Position::TOTAL_LATITUDE;
}
public function getMaxX(): float
{
return $this->getMaxY() * $this->getWidthToHeightAspectRatio();
}
public function getMaxY(): float
{
return Position::TOTAL_LATITUDE;
}
public function getMaxLatitude(): float
{
return Position::MAX_LATITUDE;
}
}
<file_sep>/src/Geometry/BoundingBox/BoundingBox.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\BoundingBox;
use PrinsFrank\PhpGeoSVG\Exception\InvalidBoundingBoxException;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Projection\Projection;
class BoundingBox
{
/**
* @throws InvalidBoundingBoxException
*/
public function __construct(public BoundingBoxPosition $southWestern, public BoundingBoxPosition $northEastern)
{
if ($this->southWestern->longitude > Position::MAX_LONGITUDE) {
throw new InvalidBoundingBoxException(
'The bounding box is unnecessarily rotated. Use a minLongitude of "' . (($this->southWestern->longitude + 180) % 360 - 180) . '" instead to achieve the same bound.'
);
}
if ($this->northEastern->longitude < Position::MIN_LONGITUDE) {
throw new InvalidBoundingBoxException(
'The bounding box is unnecessarily rotated. Use a maxLongitude of "' . (($this->northEastern->longitude - 180) % 360 + 180) . '" instead to achieve the same bound.'
);
}
if ($this->northEastern->latitude < $this->southWestern->latitude) {
throw new InvalidBoundingBoxException(
'The latitude of the NorthEastern coordinate (' . $this->northEastern->latitude . ') is south of the SouthWestern coordinate (' . $this->southWestern->latitude . ')'
);
}
if ($this->northEastern->longitude < $this->southWestern->longitude) {
throw new InvalidBoundingBoxException(
'The longitude of the NorthEastern coordinate (' . $this->northEastern->longitude . ') is west of the SouthWestern coordinate (' . $this->southWestern->longitude . ')'
);
}
}
public function getWidth(): float
{
return - $this->southWestern->longitude + $this->northEastern->longitude;
}
public function getHeight(): float
{
return - $this->southWestern->latitude + $this->northEastern->latitude;
}
public function boundX(Position $position, Projection $projection): float
{
return $projection->getX($position)
- ($projection->getX(new Position($this->southWestern->longitude, 0))
- $projection->getX(new Position(Position::MIN_LONGITUDE, 0)));
}
public function boundY(Position $position, Projection $projection): float
{
return $projection->getY($position)
- ($projection->getY(new Position(0, $this->northEastern->latitude))
- $projection->getY(new Position(0, $projection->getMaxLatitude())));
}
}
<file_sep>/src/Projection/BehrmannProjection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Projection;
class BehrmannProjection extends AbstractCylindricalEqualAreaProjection
{
public function getWidthToHeightAspectRatio(): float
{
return 3 * M_PI / 4;
}
}
<file_sep>/tests/Unit/Scale/ScaleTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Scale;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Scale\Scale;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Scale\Scale
*/
class ScaleTest extends TestCase
{
/**
* @covers ::__construct
* @covers ::getFactorX
* @covers ::getFactorY
*/
public function testFactorOnlyX(): void
{
$scale = new Scale(42.0);
static::assertSame(42.0, $scale->getFactorX());
static::assertSame(42.0, $scale->getFactorY());
}
/**
* @covers ::__construct
* @covers ::getFactorX
* @covers ::getFactorY
*/
public function testFactorDifferentY(): void
{
$scale = new Scale(42.0, 43.0);
static::assertSame(42.0, $scale->getFactorX());
static::assertSame(43.0, $scale->getFactorY());
}
}
<file_sep>/tests/Unit/Html/Elements/ElementTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Html\Elements;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Html\Elements\Element;
use PrinsFrank\PhpGeoSVG\Html\Elements\GroupElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\PathElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\SvgElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\Text\TextContent;
use PrinsFrank\PhpGeoSVG\Html\Elements\TitleElement;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Html\Elements\Element
*/
class ElementTest extends TestCase
{
private Element $element;
protected function setUp(): void
{
parent::setUp();
$this->element = new class () extends Element {
public function getTagName(): string
{
return 'test';
}
};
}
/**
* @covers ::getChildElements
* @covers ::addChildElement
*/
public function testChildElements(): void
{
$element = $this->element;
static::assertSame([], $element->getChildElements());
$childElement1 = new TitleElement();
$element->addChildElement($childElement1);
static::assertSame([$childElement1], $element->getChildElements());
$childElement2 = new TitleElement();
$element->addChildElement($childElement2);
static::assertSame([$childElement1, $childElement2], $element->getChildElements());
}
/**
* @covers ::setAttribute
* @covers ::getAttributes
*/
public function testAttributes(): void
{
$element = $this->element;
static::assertSame([], $element->getAttributes());
$element->setAttribute('foo', 'bar');
static::assertSame(['foo' => 'bar'], $element->getAttributes());
$element->setAttribute('bar', 'foo');
static::assertSame(['foo' => 'bar', 'bar' => 'foo'], $element->getAttributes());
$element->setAttribute('bar', 'bop');
static::assertSame(['foo' => 'bar', 'bar' => 'bop'], $element->getAttributes());
}
/**
* @covers ::getTextContent
* @covers ::setTextContent
*/
public function testTextContent(): void
{
$element = $this->element;
static::assertNull($element->getTextContent());
$textContent1 = new TextContent();
$element->setTextContent($textContent1);
static::assertSame($textContent1, $element->getTextContent());
$textContent2 = new TextContent();
$element->setTextContent($textContent2);
static::assertSame($textContent2, $element->getTextContent());
}
/**
* @covers ::canSelfClose
*/
public function testCanSelfCloseNonForeignElements(): void
{
static::assertFalse((new TitleElement())->canSelfClose());
}
/**
* @covers ::canSelfClose
*/
public function testCanSelfCloseWhenWithChildElements(): void
{
static::assertFalse((new GroupElement())->addChildElement(new PathElement())->canSelfClose());
}
/**
* @covers ::canSelfClose
*/
public function testCanSelfCloseWhenWithTextContent(): void
{
static::assertFalse((new GroupElement())->setTextContent(new TextContent())->canSelfClose());
}
/**
* @covers ::canSelfClose
*/
public function testCanSelfClose(): void
{
static::assertTrue((new GroupElement())->canSelfClose());
static::assertTrue((new PathElement())->canSelfClose());
static::assertTrue((new SvgElement())->canSelfClose());
}
}
<file_sep>/tests/Unit/Projection/EquiRectangularProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Projection\EquiRectangularProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\EquiRectangularProjection
*/
class EquiRectangularProjectionTest extends TestCase
{
/**
* @covers ::getX
*/
public function testGetX(): void
{
static::assertSame(180.0, (new EquiRectangularProjection())->getX(new Position(0, 0)));
static::assertSame(0.0, (new EquiRectangularProjection())->getX(new Position(-180, 0)));
static::assertSame(360.0, (new EquiRectangularProjection())->getX(new Position(180, 0)));
}
/**
* @covers ::getY
*/
public function testGetY(): void
{
static::assertSame(90.0, (new EquiRectangularProjection())->getY(new Position(0, 0)));
static::assertSame(180.0, (new EquiRectangularProjection())->getY(new Position(0, -90)));
static::assertSame(0.0, (new EquiRectangularProjection())->getY(new Position(0, 90)));
}
/**
* @covers ::getMaxX
*/
public function testGetMaxX(): void
{
static::assertSame(360.0, (new EquiRectangularProjection())->getMaxX());
}
/**
* @covers ::getMaxY
*/
public function testGetMaxY(): void
{
static::assertSame(180.0, (new EquiRectangularProjection())->getMaxY());
}
/**
* @covers ::getMaxLatitude
*/
public function testGetMaxLatitude(): void
{
static::assertSame(90.0, (new EquiRectangularProjection())->getMaxLatitude());
}
}
<file_sep>/src/Html/Elements/CircleElement.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Elements;
use PrinsFrank\PhpGeoSVG\Html\Elements\Definition\ForeignElement;
class CircleElement extends Element implements ForeignElement
{
public function getTagName(): string
{
return 'circle';
}
}
<file_sep>/tests/Unit/Geometry/GeometryObject/GeometryObjectFactoryTest.php
<?php
declare(strict_types=1);
namespace Geometry\GeometryObject;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Exception\NotImplementedException;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\GeometryObjectFactory;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiLineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPoint;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPolygon;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Point;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Polygon;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\GeometryObjectFactory
*/
class GeometryObjectFactoryTest extends TestCase
{
/**
* @covers ::createForGeoJsonFeatureGeometry
*/
public function testCreateForGeoJsonFeatureGeometryThrowsExceptionForUnsupportedTypes(): void
{
$this->expectException(NotImplementedException::class);
$this->expectExceptionMessage('Feature geometries of type "foo" are currently not supported');
GeometryObjectFactory::createForGeoJsonFeatureGeometry(['type' => 'foo']);
}
/**
* @covers ::createForGeoJsonFeatureGeometry
*/
public function testCreateForGeoJsonFeatureGeometry(): void
{
static::assertEquals(new LineString(), GeometryObjectFactory::createForGeoJsonFeatureGeometry(['type' => 'LineString', 'coordinates' => []]));
static::assertEquals(new MultiLineString(), GeometryObjectFactory::createForGeoJsonFeatureGeometry(['type' => 'MultiLineString', 'coordinates' => []]));
static::assertEquals(new MultiPolygon(), GeometryObjectFactory::createForGeoJsonFeatureGeometry(['type' => 'MultiPolygon', 'coordinates' => []]));
static::assertEquals(new Point(new Position(0, 0)), GeometryObjectFactory::createForGeoJsonFeatureGeometry(['type' => 'Point', 'coordinates' => [0, 0]]));
static::assertEquals(new Polygon(new LineString()), GeometryObjectFactory::createForGeoJsonFeatureGeometry(['type' => 'Polygon', 'coordinates' => [[]]]));
}
/**
* @covers ::createForLineStringCoordinates
*/
public function testCreateForLineStringCoordinatesWithNoCoordinates(): void
{
static::assertEquals(new LineString(), GeometryObjectFactory::createForLineStringCoordinates([]));
}
/**
* @covers ::createForLineStringCoordinates
*/
public function testCreateForLineStringCoordinates(): void
{
static::assertEquals(
(new LineString())->addPosition(new Position(0, 1, 2))->addPosition(new Position(3, 4)),
GeometryObjectFactory::createForLineStringCoordinates([[0, 1, 2], [3, 4]])
);
}
/**
* @covers ::createForMultiLineStringCoordinates
*/
public function testCreateForMultiLineStringCoordinatesWithNoCoordinates(): void
{
static::assertEquals(new MultiLineString(), GeometryObjectFactory::createForMultiLineStringCoordinates([]));
}
/**
* @covers ::createForMultiLineStringCoordinates
*/
public function testCreateForMultiLineStringCoordinates(): void
{
static::assertEquals(
(new MultiLineString())
->addLineString(
(new LineString())
->addPosition(new Position(0, 1))
->addPosition(new Position(2, 3))
)->addLineString(
(new LineString())
->addPosition(new Position(4, 5))
),
GeometryObjectFactory::createForMultiLineStringCoordinates([[[0, 1], [2, 3]], [[4, 5]]])
);
}
/**
* @covers ::createForMultiLineStringCoordinates
*/
public function testCreateForMultiPointCoordinatesWithNoCoordinates(): void
{
static::assertEquals(new MultiPoint(), GeometryObjectFactory::createForMultiPointCoordinates([]));
}
/**
* @covers ::createForMultiPointCoordinates
*/
public function testCreateForMultiPointCoordinates(): void
{
static::assertEquals(
(new MultiPoint())->addPoint(new Point(new Position(0, 1)))->addPoint(new Point(new Position(2, 3))),
GeometryObjectFactory::createForMultiPointCoordinates([[0, 1], [2, 3]])
);
}
/**
* @covers ::createForMultiPolygonCoordinates
*/
public function testCreateForMultiPolygonoordinatesWithNoCoordinates(): void
{
static::assertEquals(new MultiPolygon(), GeometryObjectFactory::createForMultiPolygonCoordinates([]));
}
/**
* @covers ::createForMultiPolygonCoordinates
*/
public function testCreateForMultiPolygonCoordinates(): void
{
static::assertEquals(
(new MultiPolygon())
->addPolygon(
(new Polygon(
(new LineString())->addPosition(new Position(0, 1))
))->addInteriorRing(
(new LineString())->addPosition(new Position(2, 3))->addPosition(new Position(4, 5))
)
),
GeometryObjectFactory::createForMultiPolygonCoordinates([[], [[[0, 1]], [[2, 3], [4, 5]]]])
);
}
/**
* @covers ::createForPointCoordinates
*/
public function testCreateForPointCoordinates(): void
{
static::assertEquals(
new Point(new Position(1, 2)),
GeometryObjectFactory::createForPointCoordinates([1 ,2])
);
static::assertEquals(
new Point(new Position(1, 2, 3)),
GeometryObjectFactory::createForPointCoordinates([1, 2, 3])
);
}
/**
* @covers ::createForPolygonCoordinates
*/
public function testCreateForPolygonCoordinatesWithEmptyCoordinates(): void
{
static::assertNull(GeometryObjectFactory::createForPolygonCoordinates([]));
}
/**
* @covers ::createForPolygonCoordinates
*/
public function testCreateForPolygonCoordinatesWithOnlyExteriorRing(): void
{
static::assertEquals(
new Polygon(
(new LineString())->addPosition(new Position(0, 1))
),
GeometryObjectFactory::createForPolygonCoordinates([[[0, 1]]])
);
}
/**
* @covers ::createForPolygonCoordinates
*/
public function testCreateForPolygonCoordinates(): void
{
static::assertEquals(
(new Polygon(
(new LineString())->addPosition(new Position(0, 1))
))->addInteriorRing(
(new LineString())->addPosition(new Position(2, 3))->addPosition(new Position(4, 5))
)->addInteriorRing(
(new LineString())->addPosition(new Position(6, 7))
),
GeometryObjectFactory::createForPolygonCoordinates([[[0, 1]], [[2, 3], [4, 5]], [[6, 7]]])
);
}
}
<file_sep>/src/Projection/HoboDyerProjection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Projection;
class HoboDyerProjection extends AbstractCylindricalEqualAreaProjection
{
public function getWidthToHeightAspectRatio(): float
{
return 1.977;
}
}
<file_sep>/tests/Unit/Projection/TrystanEdwardsProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Projection\TrystanEdwardsProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\TrystanEdwardsProjection
*/
class TrystanEdwardsProjectionTest extends TestCase
{
/**
* @covers ::getWidthToHeightAspectRatio
*/
public function testGetWidthToHeightAspectRatio(): void
{
static::assertSame(1.983, (new TrystanEdwardsProjection())->getWidthToHeightAspectRatio());
}
}
<file_sep>/tests/Unit/Geometry/BoundingBox/BoundingBoxTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Geometry\BoundingBox;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Exception\InvalidBoundingBoxException;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBox;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBoxPosition;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Projection\MercatorProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBox
*/
class BoundingBoxTest extends TestCase
{
/**
* -------------------------------------------------------------
* | | |######|######|######|######| | | Default View box
* | xxx|xxx | | | | | | | Unnecessarily in wrapped context
* | | | | | vvv|vvv | | | Could be rotated into this context resulting in the same view
* | | |######|######|######|######| | | Default View box
* -------------------------------------------------------------
* -360 -270 -180 -90 0 90 180 270 360
*
* @covers ::__construct
*/
public function testViewBoxUnnecessarilyRotatedWest(): void
{
$this->expectException(InvalidBoundingBoxException::class);
$this->expectExceptionMessage('The bounding box is unnecessarily rotated. Use a maxLongitude of "135" instead to achieve the same bound.');
new BoundingBox(new BoundingBoxPosition(-315, 0), new BoundingBoxPosition(-225, 0));
}
/**
* -------------------------------------------------------------
* | | |######|######|######|######| | | Default View box
* | | | | | | | xxx|xxx | Unnecessarily in rotated context
* | | | vvv|vvv | | | | | Could be rotated into this context resulting in the same view
* | | |######|######|######|######| | | Default View box
* -------------------------------------------------------------
* -360 -270 -180 -90 0 90 180 270 360
*
* @covers ::__construct
*/
public function testViewBoxUnnecessarilyRotatedEast(): void
{
$this->expectException(InvalidBoundingBoxException::class);
$this->expectExceptionMessage('The bounding box is unnecessarily rotated. Use a minLongitude of "-135" instead to achieve the same bound.');
new BoundingBox(new BoundingBoxPosition(225, 0), new BoundingBoxPosition(315, 0));
}
/**
* @covers ::__construct
*/
public function testNorthSouthBoundingBoxFlipped(): void
{
$this->expectException(InvalidBoundingBoxException::class);
$this->expectExceptionMessage('The latitude of the NorthEastern coordinate (-45) is south of the SouthWestern coordinate (45)');
new BoundingBox(new BoundingBoxPosition(0, 45), new BoundingBoxPosition(0, -45));
}
/**
* @covers ::__construct
*/
public function testEastWestBoundingBoxFlipped(): void
{
$this->expectException(InvalidBoundingBoxException::class);
$this->expectExceptionMessage('The longitude of the NorthEastern coordinate (-90) is west of the SouthWestern coordinate (90)');
new BoundingBox(new BoundingBoxPosition(90, 0), new BoundingBoxPosition(-90, 0));
}
/**
* @covers ::__construct
* @covers ::getWidth
*/
public function testGetWidth(): void
{
static::assertSame(360.0, (new BoundingBox(new BoundingBoxPosition(-180, 0), new BoundingBoxPosition(180, 0)))->getWidth());
static::assertSame(90.0, (new BoundingBox(new BoundingBoxPosition(-90, 0), new BoundingBoxPosition(0, 0)))->getWidth());
static::assertSame(180.0, (new BoundingBox(new BoundingBoxPosition(-90, 0), new BoundingBoxPosition(90, 0)))->getWidth());
static::assertSame(90.0, (new BoundingBox(new BoundingBoxPosition(0, 0), new BoundingBoxPosition(90, 0)))->getWidth());
static::assertSame(0.0, (new BoundingBox(new BoundingBoxPosition(90, 0), new BoundingBoxPosition(90, 0)))->getWidth());
}
/**
* @covers ::__construct
* @covers ::getHeight
*/
public function testGetHeight(): void
{
static::assertSame(0.0, (new BoundingBox(new BoundingBoxPosition(0, 0), new BoundingBoxPosition(0, 0)))->getHeight());
static::assertSame(180.0, (new BoundingBox(new BoundingBoxPosition(0, -90), new BoundingBoxPosition(0, 90)))->getHeight());
static::assertSame(90.0, (new BoundingBox(new BoundingBoxPosition(0, -90), new BoundingBoxPosition(0, 0)))->getHeight());
static::assertSame(90.0, (new BoundingBox(new BoundingBoxPosition(0, 0), new BoundingBoxPosition(0, 90)))->getHeight());
}
/**
* @covers ::boundX
*/
public function testBoundX(): void
{
$position = new Position(90, 45);
$projection = $this->createMock(MercatorProjection::class);
$projection->expects(static::exactly(3))
->method('getX')
->withConsecutive([$position], [$this->equalTo(new Position(0, 0))], [$this->equalTo(new Position(-180, 0))])
->willReturnOnConsecutiveCalls(30.0, 20.0, 50.0);
static::assertSame(
60.0,
(new BoundingBox(new BoundingBoxPosition(0, 0), new BoundingBoxPosition(180, 90)))->boundX($position, $projection)
);
}
/**
* @covers ::boundY
*/
public function testBoundY(): void
{
$position = new Position(90, 45);
$projection = $this->createMock(MercatorProjection::class);
$projection->expects(static::exactly(3))
->method('getY')
->withConsecutive([$position], [$this->equalTo(new Position(0, 90))], [$this->equalTo(new Position(0, 0))])
->willReturnOnConsecutiveCalls(30.0, 20.0, 50.0);
static::assertSame(
60.0,
(new BoundingBox(new BoundingBoxPosition(0, 0), new BoundingBoxPosition(180, 90)))->boundY($position, $projection)
);
}
}
<file_sep>/src/Geometry/GeometryCollectionFactory.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry;
use JsonException;
use PrinsFrank\PhpGeoSVG\Exception\InvalidPositionException;
use PrinsFrank\PhpGeoSVG\Exception\NotImplementedException;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\GeometryObjectFactory;
class GeometryCollectionFactory
{
/**
* @throws NotImplementedException|InvalidPositionException
*/
public static function createFromGeoJSONArray(array $geoJSONArray): GeometryCollection
{
$geometryCollection = new GeometryCollection();
if ('FeatureCollection' !== $geoJSONArray['type']) {
throw new NotImplementedException('Only FeatureCollections are currently supported');
}
foreach ($geoJSONArray['features'] ?? [] as $feature) {
if ('Feature' !== $feature['type']) {
throw new NotImplementedException('Only features of type "Feature" are supported.');
}
$geometryObject = GeometryObjectFactory::createForGeoJsonFeatureGeometry($feature['geometry']);
if (null === $geometryObject) {
continue;
}
if (array_key_exists('properties', $feature) && array_key_exists('featurecla', $feature['properties'])) {
$geometryObject->setFeatureClass($feature['properties']['featurecla']);
}
$geometryCollection->addGeometryObject($geometryObject);
}
return $geometryCollection;
}
/**
* @throws JsonException|NotImplementedException|InvalidPositionException
*/
public static function createFromGeoJsonString(string $geoJsonString): GeometryCollection
{
return self::createFromGeoJSONArray(json_decode($geoJsonString, true, 512, JSON_THROW_ON_ERROR));
}
/**
* @throws JsonException|NotImplementedException|InvalidPositionException
*/
public static function createFromGeoJSONFilePath(string $path): GeometryCollection
{
return self::createFromGeoJsonString(file_get_contents($path));
}
}
<file_sep>/src/Html/Elements/Definition/ForeignElement.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Html\Elements\Definition;
/**
* @see https://html.spec.whatwg.org/#foreign-elements
* Foreign elements: Elements from the MathML namespace and the SVG namespace.
*/
interface ForeignElement
{
}
<file_sep>/tests/Unit/Html/Rendering/PathShapeRendererTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Html\Rendering;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Coordinator\Coordinator;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Html\Rendering\PathShapeRenderer;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Html\Rendering\PathShapeRenderer
*/
class PathShapeRendererTest extends TestCase
{
/**
* @covers ::renderLineStringPath
*/
public function testRenderLineStringPathWithoutPositions(): void
{
$coordinator = $this->createMock(Coordinator::class);
static::assertSame('', PathShapeRenderer::renderLineStringPath(new LineString(), $coordinator));
}
/**
* @covers ::renderLineStringPath
*/
public function testRenderLineStringPathWithOnlyOnePosition(): void
{
$lineString = new LineString();
$position = new Position(42, -42);
$lineString->addPosition($position);
$coordinator = $this->createMock(Coordinator::class);
$coordinator->expects(static::once())->method('getX')->with($position)->willReturn(21.0);
$coordinator->expects(static::once())->method('getY')->with($position)->willReturn(84.0);
static::assertSame('M21 84', PathShapeRenderer::renderLineStringPath($lineString, $coordinator));
}
/**
* @covers ::renderLineStringPath
*/
public function testRenderLineStringPath(): void
{
$lineString = new LineString();
$position1 = new Position(42, -42);
$lineString->addPosition($position1);
$position2 = new Position(12, 23);
$lineString->addPosition($position2);
$position3 = new Position(46, -50);
$lineString->addPosition($position3);
$coordinator = $this->createMock(Coordinator::class);
$coordinator->expects(static::exactly(3))
->method('getX')
->withConsecutive([$position1], [$position2], [$position3])
->willReturnOnConsecutiveCalls(42, 12, 46);
$coordinator->expects(static::exactly(3))
->method('getY')
->withConsecutive([$position1], [$position2], [$position3])
->willReturnOnConsecutiveCalls(8, 27, 0);
static::assertSame('M42 8 L12 27 L46 0', PathShapeRenderer::renderLineStringPath($lineString, $coordinator));
}
}
<file_sep>/src/Projection/MillerProjection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Projection;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
class MillerProjection extends MercatorProjection
{
public function getY(Position $position): float
{
return parent::getY($position) / 5 * 4;
}
public function getMaxY(): float
{
return parent::getMaxY() / 5 * 4;
}
}
<file_sep>/tests/Unit/Html/Rendering/ElementRendererTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Html\Rendering;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Exception\InvalidArgumentException;
use PrinsFrank\PhpGeoSVG\Exception\RecursionException;
use PrinsFrank\PhpGeoSVG\Html\Elements\GroupElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\PathElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\SvgElement;
use PrinsFrank\PhpGeoSVG\Html\Elements\Text\TextContent;
use PrinsFrank\PhpGeoSVG\Html\Elements\TitleElement;
use PrinsFrank\PhpGeoSVG\Html\Rendering\ElementRenderer;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Html\Rendering\ElementRenderer
*/
class ElementRendererTest extends TestCase
{
/**
* @covers ::renderElement
*/
public function testRenderElementThrowsRecursionExceptionWithCircularReference(): void
{
$element1 = new GroupElement();
$element2 = new GroupElement();
$element1->addChildElement($element2);
$element2->addChildElement($element1);
$this->expectException(RecursionException::class);
$this->expectExceptionMessage('Recursion limit of 10 Reached');
ElementRenderer::renderElement($element1);
}
/**
* @covers ::renderElement
*/
public function testRenderElementThrowsRecursionExceptionWithDeepTree(): void
{
$element1 = new GroupElement();
$element2 = new GroupElement();
$element1->addChildElement($element2);
$element3 = new GroupElement();
$element2->addChildElement($element3);
$element4 = new GroupElement();
$element3->addChildElement($element4);
$element5 = new GroupElement();
$element4->addChildElement($element5);
$element6 = new GroupElement();
$element5->addChildElement($element6);
$element7 = new GroupElement();
$element6->addChildElement($element7);
$element8 = new GroupElement();
$element7->addChildElement($element8);
$element9 = new GroupElement();
$element8->addChildElement($element9);
$element10 = new GroupElement();
$element9->addChildElement($element10);
$element11 = new GroupElement();
$element10->addChildElement($element11);
$element12 = new GroupElement();
$element11->addChildElement($element12);
$this->expectException(RecursionException::class);
$this->expectExceptionMessage('Recursion limit of 10 Reached');
ElementRenderer::renderElement($element1);
}
/**
* @covers ::renderElement
*/
public function testRenderElementWithEmptySelfClosingElement(): void
{
static::assertSame('<path/>' . PHP_EOL, ElementRenderer::renderElement(new PathElement()));
}
/**
* @covers ::renderElement
*/
public function testRenderElementWithEmptyNonSelfClosingElement(): void
{
static::assertSame('<title>' . PHP_EOL . '</title>' . PHP_EOL, ElementRenderer::renderElement(new TitleElement()));
}
/**
* @covers ::renderElement
*/
public function testRenderElementWithTextContent(): void
{
static::assertSame(
'<title>' . PHP_EOL .
' foo' . PHP_EOL .
'</title>' . PHP_EOL,
ElementRenderer::renderElement((new TitleElement())->setTextContent(new TextContent('foo')))
);
static::assertSame(
'<path>' . PHP_EOL .
' foo' . PHP_EOL .
'</path>' . PHP_EOL,
ElementRenderer::renderElement((new PathElement())->setTextContent(new TextContent('foo')))
);
}
/**
* @covers ::renderElement
*/
public function testRenderElementThatCannotSelfCloseWithAttributes(): void
{
static::assertSame(
'<title foo="bar" bar="foo">' . PHP_EOL .
'</title>' . PHP_EOL,
ElementRenderer::renderElement((new TitleElement())->setAttribute('foo', 'bar')->setAttribute('bar', 'foo'))
);
}
/**
* @covers ::renderElement
*/
public function testRenderElementThatCanSelfCloseWithAttributes(): void
{
static::assertSame(
'<path bar="bop"/>' . PHP_EOL,
ElementRenderer::renderElement((new PathElement())->setAttribute('bar', 'bop'))
);
}
/**
* @covers ::renderElement
*/
public function testRenderElementThatCannotSelfCloseWithChildElement(): void
{
static::assertSame(
'<title>' . PHP_EOL .
' <path/>' . PHP_EOL .
'</title>' . PHP_EOL,
ElementRenderer::renderElement((new TitleElement())->addChildElement(new PathElement()))
);
}
/**
* @covers ::renderElement
*/
public function testRenderElementThatCanSelfCloseWithChildElement(): void
{
static::assertSame(
'<path>' . PHP_EOL .
' <title>' . PHP_EOL .
' </title>' . PHP_EOL .
'</path>' . PHP_EOL,
ElementRenderer::renderElement((new PathElement())->addChildElement(new TitleElement()))
);
}
/**
* @covers ::renderSelfClosingElement
*/
public function testRenderSelfClosingElementThrowsExceptionWithNonSelfClosingElement(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Only elements that can self close can be rendered as self closing elements');
ElementRenderer::renderSelfClosingElement(new TitleElement());
}
/**
* @covers ::renderSelfClosingElement
*/
public function testRenderSelfClosingElement(): void
{
static::assertEquals(
'<path/>' . PHP_EOL,
ElementRenderer::renderSelfClosingElement(new PathElement())
);
static::assertEquals(
'<path foo="bar"/>' . PHP_EOL,
ElementRenderer::renderSelfClosingElement(
(new PathElement())->setAttribute('foo', 'bar')
)
);
}
/**
* @covers ::renderChildElements
*/
public function testRenderChildElementsWithNoChildElements(): void
{
static::assertNull(ElementRenderer::renderChildElements([], 0));
}
/**
* @covers ::renderChildElements
*/
public function testRenderChildElements(): void
{
static::assertSame(
' <svg xmlns="http://www.w3.org/2000/svg" version="1.1"/>' . PHP_EOL .
' <path/>' . PHP_EOL,
ElementRenderer::renderChildElements([new SvgElement(), new PathElement()], 3)
);
}
/**
* @covers ::renderTextContent
*/
public function testRenderTextContentWhenItIsNonExisting(): void
{
static::assertNull(ElementRenderer::renderTextContent(null, 42));
}
/**
* @covers ::renderTextContent
*/
public function testRenderTextContent(): void
{
static::assertSame(
' foo' . PHP_EOL,
ElementRenderer::renderTextContent(new TextContent('foo'), 3)
);
}
}
<file_sep>/src/Projection/GallPetersProjection.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Projection;
class GallPetersProjection extends AbstractCylindricalEqualAreaProjection
{
public function getWidthToHeightAspectRatio(): float
{
return M_PI_2;
}
}
<file_sep>/tests/Unit/Geometry/GeometryCollectionFactoryTest.php
<?php
declare(strict_types=1);
namespace Geometry;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Exception\NotImplementedException;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollection;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollectionFactory;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiLineString;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\GeometryCollectionFactory
*/
class GeometryCollectionFactoryTest extends TestCase
{
/**
* @covers ::createFromGeoJSONArray
*/
public function testCreateFromGeoJSONArrayThrowsExceptionWhenSomethingElseThenFeatureCollectionIsProvided(): void
{
$this->expectException(NotImplementedException::class);
$this->expectExceptionMessage('Only FeatureCollections are currently supported');
GeometryCollectionFactory::createFromGeoJSONArray(['type' => 'foo']);
}
/**
* @covers ::createFromGeoJSONArray
*/
public function testCreateFromGeoJSONArrayThrowsExceptionWhenTypeOfFeatureIsNotFeature(): void
{
$this->expectException(NotImplementedException::class);
$this->expectExceptionMessage('Only features of type "Feature" are supported.');
GeometryCollectionFactory::createFromGeoJSONArray(['type' => 'FeatureCollection', 'features' => [['type' => 'foo']]]);
}
/**
* @covers ::createFromGeoJSONArray
*/
public function testIgnoresEmptyGeometryObjects(): void
{
static::assertEquals(
new GeometryCollection(),
GeometryCollectionFactory::createFromGeoJSONArray(
[
'type' => 'FeatureCollection',
'features' => [
[
'type' => 'Feature',
'geometry' => [
'type' => 'Polygon',
'coordinates' => []
]
]
]
]
)
);
}
/**
* @covers ::createFromGeoJSONArray
*/
public function testCreatesFromGeoJSONArray(): void
{
static::assertEquals(
(new GeometryCollection())
->addGeometryObject(new MultiLineString()),
GeometryCollectionFactory::createFromGeoJSONArray(
[
'type' => 'FeatureCollection',
'features' => [
[
'type' => 'Feature',
'geometry' => [
'type' => 'MultiLineString',
'coordinates' => []
]
]
]
]
)
);
}
/**
* @covers ::createFromGeoJSONArray
*/
public function testCreatesFromGeoJSONArraySetsFeatureCla(): void
{
static::assertEquals(
(new GeometryCollection())
->addGeometryObject(
(new MultiLineString())
->setFeatureClass('bar')
),
GeometryCollectionFactory::createFromGeoJSONArray(
[
'type' => 'FeatureCollection',
'features' => [
[
'type' => 'Feature',
'properties' => [
'featurecla' => 'bar'
],
'geometry' => [
'type' => 'MultiLineString',
'coordinates' => []
]
]
]
]
)
);
}
/**
* @covers ::createFromGeoJsonString
*/
public function testCreateFromGeoJsonString(): void
{
static::assertEquals(
(new GeometryCollection())
->addGeometryObject(
(new MultiLineString())
->setFeatureClass('bar')
),
GeometryCollectionFactory::createFromGeoJsonString('{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"featurecla":"bar"},"geometry":{"type":"MultiLineString","coordinates":[]}}]}')
);
}
/**
* @covers ::createFromGeoJSONFilePath
*/
public function testCreateFromGeoJsonFilePath(): void
{
static::assertEquals(
(new GeometryCollection())
->addGeometryObject(
(new MultiLineString())
->setFeatureClass('bar')
),
GeometryCollectionFactory::createFromGeoJSONFilePath(__DIR__ . '/geometry_collection_factory_test.geojson')
);
}
}
<file_sep>/tests/Unit/Html/Elements/Text/TextContentTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Html\Elements\Text;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Html\Elements\Text\TextContent;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Html\Elements\Text\TextContent
*/
class TextContentTest extends TestCase
{
/**
* @covers ::__construct
* @covers ::getContent
*/
public function testContentInConstructor(): void
{
$textContent = new TextContent();
static::assertNull($textContent->getContent());
$textContent = new TextContent(null);
static::assertNull($textContent->getContent());
$textContent = new TextContent('');
static::assertSame('', $textContent->getContent());
$textContent = new TextContent('foo');
static::assertSame('foo', $textContent->getContent());
}
/**
* @covers ::setContent
* @covers ::getContent
*/
public function testSetContent(): void
{
$textContent = new TextContent();
$textContent->setContent('foo');
static::assertSame('foo', $textContent->getContent());
$textContent->setContent(null);
static::assertNull($textContent->getContent());
}
}
<file_sep>/tests/Unit/Projection/LambertProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Projection\LambertProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\LambertProjection
*/
class LambertProjectionTest extends TestCase
{
/**
* @covers ::getWidthToHeightAspectRatio
*/
public function testGetWidthToHeightAspectRatio(): void
{
static::assertEqualsWithDelta(3.141, (new LambertProjection())->getWidthToHeightAspectRatio(), 0.001);
}
}
<file_sep>/tests/Feature/GeoSVGTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Feature;
use JsonException;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Exception\InvalidPositionException;
use PrinsFrank\PhpGeoSVG\Exception\NotImplementedException;
use PrinsFrank\PhpGeoSVG\Exception\PhpGeoSVGException;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollection;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryCollectionFactory;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPolygon;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Polygon;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\GeoSVG;
/**
* @coversNothing
*/
class GeoSVGTest extends TestCase
{
private const GEO_JSON_FOLDER = 'vendor/prinsfrank/natural-earth-vector-geojson-only/geojson/';
public function testFromGeoJsonFile(): void
{
(new GeoSVG())
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(__DIR__ . '/geojson/continents.geojson'),
__DIR__ . '/actual/from-geojson-file.svg'
);
static::assertFileEquals(__DIR__ . '/expected/from-geojson-file.svg', __DIR__ . '/actual/from-geojson-file.svg');
}
/**
* @throws InvalidPositionException
* @throws PhpGeoSVGException
* @throws NotImplementedException
* @throws JsonException
*/
public function testGeneratesFromGeoJsonFiles(): void
{
$geoJsonFileNames = scandir(dirname(__DIR__, 2) . '/' . self::GEO_JSON_FOLDER);
$geoJsonFileNames = array_filter($geoJsonFileNames, static function ($geoJsonFileName) {
return str_contains($geoJsonFileName, '110m');
});
static::assertCount(32, $geoJsonFileNames);
foreach ($geoJsonFileNames as $geoJsonFileName) {
$baseFileName = substr($geoJsonFileName, 0, -8);
(new GeoSVG())
->toFile(
GeometryCollectionFactory::createFromGeoJSONFilePath(dirname(__DIR__, 2) . '/' . self::GEO_JSON_FOLDER . $geoJsonFileName),
__DIR__ . '/actual/' . $baseFileName . '.svg'
);
static::assertFileEquals(__DIR__ . '/expected/' . $baseFileName . '.svg', __DIR__ . '/actual/' . $baseFileName . '.svg');
}
}
public function testFromGeoJsonString(): void
{
(new GeoSVG())
->toFile(
GeometryCollectionFactory::createFromGeoJsonString(
'{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-177,74],[-80,9],[-25,82]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-80,9],[-37,-7],[-70,-55]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-12,36],[30,37],[27,70],[-24,66]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[-12,36],[30,37],[51,11],[22,-35],[-17,17]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[27,70],[30,37],[51,11],[131,-2],[171,67]]]}},{"type":"Feature","properties":{"featurecla":"Continent"},"geometry":{"type":"MultiLineString","coordinates":[[[115,-15],[153,-15],[148,-43],[114,-35]]]}}]}'
),
__DIR__ . '/actual/from-geojson-string.svg'
);
static::assertFileEquals(__DIR__ . '/expected/from-geojson-string.svg', __DIR__ . '/actual/from-geojson-string.svg');
}
public function testFromGeoJSONArray(): void
{
(new GeoSVG())
->toFile(
GeometryCollectionFactory::createFromGeoJSONArray(
[
'type' => 'FeatureCollection',
'features' => [
[
'type' => 'Feature',
'properties' => [
'featurecla' => 'Continent'
],
'geometry' => [
'type' => 'MultiLineString',
'coordinates' => [
[
[-177, 74],
[-80, 9],
[-25, 82]
]
]
]
],
[
'type' => 'Feature',
'properties' => [
'featurecla' => 'Continent'
],
'geometry' => [
'type' => 'MultiLineString',
'coordinates' => [
[
[-80, 9],
[-37, -7],
[-70, -55]
]
]
]
],
[
'type' => 'Feature',
'properties' => [
'featurecla' => 'Continent'
],
'geometry' => [
'type' => 'MultiLineString',
'coordinates' => [
[
[-12, 36],
[30, 37],
[27, 70],
[-24, 66]
]
]
]
],
[
'type' => 'Feature',
'properties' => [
'featurecla' => 'Continent'
],
'geometry' => [
'type' => 'MultiLineString',
'coordinates' => [
[
[-12, 36],
[30, 37],
[51, 11],
[22, -35],
[-17, 17]
]
]
]
],
[
'type' => 'Feature',
'properties' => [
'featurecla' => 'Continent'
],
'geometry' => [
'type' => 'MultiLineString',
'coordinates' => [
[
[27, 70],
[30, 37],
[51, 11],
[131, -2],
[171, 67]
]
]
]
],
[
'type' => 'Feature',
'properties' => [
'featurecla' => 'Continent'
],
'geometry' => [
'type' => 'MultiLineString',
'coordinates' => [
[
[115, -15],
[153, -15],
[148, -43],
[114, -35]
]
]
]
],
]
]
),
__DIR__ . '/actual/from-geojson-array.svg'
);
static::assertFileEquals(__DIR__ . '/expected/from-geojson-array.svg', __DIR__ . '/actual/from-geojson-array.svg');
}
/**
* @throws PhpGeoSVGException
* @throws InvalidPositionException
*/
public function testFromGeometryCollection(): void
{
(new GeoSVG())
->toFile(
(new GeometryCollection())
->addGeometryObject(
(new MultiPolygon())
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(-177, 74))
->addPosition(new Position(-80, 9))
->addPosition(new Position(-25, 82))
->setFeatureClass('Continent')
->setTitle('North America')
)
)
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(-80, 9))
->addPosition(new Position(-37, -7))
->addPosition(new Position(-70, -55))
->setFeatureClass('Continent')
->setTitle('South America')
)
)
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(-12, 36))
->addPosition(new Position(30, 37))
->addPosition(new Position(27, 70))
->addPosition(new Position(-24, 66))
->setFeatureClass('Continent')
->setTitle('Europe')
)
)
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(-12, 36))
->addPosition(new Position(30, 37))
->addPosition(new Position(51, 11))
->addPosition(new Position(22, -35))
->addPosition(new Position(-17, 17))
->setFeatureClass('Continent')
->setTitle('Africa')
)
)
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(27, 70))
->addPosition(new Position(30, 37))
->addPosition(new Position(51, 11))
->addPosition(new Position(131, -2))
->addPosition(new Position(171, 67))
->setFeatureClass('Continent')
->setTitle('Asia')
)
)
->addPolygon(
new Polygon(
(new LineString())
->addPosition(new Position(115, -15))
->addPosition(new Position(153, -15))
->addPosition(new Position(148, -43))
->addPosition(new Position(114, -35))
->setFeatureClass('Continent')
->setTitle('Australia')
)
)
),
__DIR__ . '/actual/from-geometry-collection.svg'
);
static::assertFileEquals(__DIR__ . '/expected/from-geometry-collection.svg', __DIR__ . '/actual/from-geometry-collection.svg');
}
}
<file_sep>/src/Geometry/GeometryObject/MultiPolygon.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\GeometryObject;
class MultiPolygon extends GeometryObject
{
/** @var Polygon[] */
protected array $polygons = [];
public function addPolygon(Polygon $polygon): self
{
$this->polygons[] = $polygon;
return $this;
}
/**
* @return Polygon[]
*/
public function getPolygons(): array
{
return $this->polygons;
}
}
<file_sep>/tests/Unit/Html/Rendering/AttributeRendererTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Html\Rendering;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Exception\InvalidArgumentException;
use PrinsFrank\PhpGeoSVG\Html\Rendering\AttributeRenderer;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Html\Rendering\AttributeRenderer
*/
class AttributeRendererTest extends TestCase
{
/**
* @covers ::renderAttributes
*/
public function testRenderAttributesThrowsExceptionWithNonStringAttributeName(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Attribute names have to be of type string, "integer"(0) given.');
AttributeRenderer::renderAttributes(['foo']);
}
/**
* @covers ::renderAttributes
*/
public function testRenderAttributesThrowsExceptionWithNonStringAttributeValue(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Attribute values have to be of type string, "integer"(42) given.');
AttributeRenderer::renderAttributes(['foo' => 42]);
}
/**
* @covers ::renderAttributes
*/
public function testRenderAttributes(): void
{
static::assertNull(AttributeRenderer::renderAttributes([]));
static::assertSame('foo="bar"', AttributeRenderer::renderAttributes(['foo' => 'bar']));
static::assertSame('foo="bar" bar="foo"', AttributeRenderer::renderAttributes(['foo' => 'bar', 'bar' => 'foo']));
}
/**
* @covers ::renderAttribute
*/
public function testRenderAttribute(): void
{
static::assertSame('foo="bar"', AttributeRenderer::renderAttribute('foo', 'bar'));
static::assertSame('foo="\\\'bar\\\'"', AttributeRenderer::renderAttribute('foo', '\'bar\''));
static::assertSame('foo="\'bar\'"', AttributeRenderer::renderAttribute('foo', '"bar"'));
static::assertSame('foo="\'bar\', \\\'bar\\\'"', AttributeRenderer::renderAttribute('foo', '"bar", \'bar\''));
}
}
<file_sep>/tests/Unit/Projection/SmythProjectionTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Projection;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Projection\SmythProjection;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Projection\SmythProjection
*/
class SmythProjectionTest extends TestCase
{
/**
* @covers ::getWidthToHeightAspectRatio
*/
public function testGetWidthToHeightAspectRatio(): void
{
static::assertSame(2.0, (new SmythProjection())->getWidthToHeightAspectRatio());
}
}
<file_sep>/src/Coordinator/Coordinator.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Coordinator;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBox;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
use PrinsFrank\PhpGeoSVG\Projection\Projection;
use PrinsFrank\PhpGeoSVG\Scale\Scale;
class Coordinator
{
public const BASE_SCALE_FACTOR = 2;
public function __construct(private Projection $projection, private BoundingBox $boundingBox, private Scale $scale)
{
}
public function getWidth(): float
{
return ($this->boundingBox->getWidth() / Position::TOTAL_LONGITUDE * $this->projection->getMaxX()) * $this->scale->getFactorX() * self::BASE_SCALE_FACTOR;
}
public function getHeight(): float
{
return ($this->boundingBox->getHeight() / Position::TOTAL_LATITUDE * $this->projection->getMaxY()) * $this->scale->getFactorY() * self::BASE_SCALE_FACTOR;
}
public function getX(Position $position): float
{
return $this->boundingBox->boundX($position, $this->projection) * $this->scale->getFactorX() * self::BASE_SCALE_FACTOR;
}
public function getY(Position $position): float
{
return $this->boundingBox->boundY($position, $this->projection) * $this->scale->getFactorY() * self::BASE_SCALE_FACTOR;
}
}
<file_sep>/src/Geometry/GeometryObject/LineString.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\GeometryObject;
use PrinsFrank\PhpGeoSVG\Geometry\Position\Position;
class LineString extends GeometryObject
{
/** @var Position[] */
protected array $positions = [];
public function addPosition(Position $position): self
{
$this->positions[] = $position;
return $this;
}
/**
* @return Position[]
*/
public function getPositions(): array
{
return $this->positions;
}
}
<file_sep>/tests/Unit/Geometry/GeometryObject/MultiPolygonTest.php
<?php
declare(strict_types=1);
namespace Geometry\GeometryObject;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\LineString;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPolygon;
use PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\Polygon;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\GeometryObject\MultiPolygon
*/
class MultiPolygonTest extends TestCase
{
/**
* @covers ::addPolygon
* @covers ::getPolygons
*/
public function testPolygons(): void
{
$multiPolygon = new MultiPolygon();
static::assertSame([], $multiPolygon->getPolygons());
$polygon1 = new Polygon(new LineString());
$multiPolygon->addPolygon($polygon1);
static::assertSame([$polygon1], $multiPolygon->getPolygons());
$polygon2 = new Polygon(new LineString());
$multiPolygon->addPolygon($polygon2);
static::assertSame([$polygon1, $polygon2], $multiPolygon->getPolygons());
}
}
<file_sep>/tests/Unit/Geometry/BoundingBox/BoundingBoxPositionTest.php
<?php
declare(strict_types=1);
namespace Geometry\BoundingBox;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Exception\InvalidBoundingBoxPositionException;
use PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBoxPosition;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Geometry\BoundingBox\BoundingBoxPosition
*/
class BoundingBoxPositionTest extends TestCase
{
/**
* @covers ::__construct
*/
public function testThrowsExceptionWhenLongitudeTooHigh(): void
{
$this->expectException(InvalidBoundingBoxPositionException::class);
$this->expectExceptionMessage('The longitude should be between -360 and 360, "360.01" provided.');
new BoundingBoxPosition(360.01, 0);
}
/**
* @covers ::__construct
*/
public function testThrowsExceptionWhenLongitudeTooLow(): void
{
$this->expectException(InvalidBoundingBoxPositionException::class);
$this->expectExceptionMessage('The longitude should be between -360 and 360, "-360.01" provided.');
new BoundingBoxPosition(-360.01, 0);
}
/**
* @covers ::__construct
*/
public function testThrowsExceptionWhenLatitudeTooHigh(): void
{
$this->expectException(InvalidBoundingBoxPositionException::class);
$this->expectExceptionMessage('The latitude should be between -90 and 90, "90.01" provided.');
new BoundingBoxPosition(0, 90.01);
}
/**
* @covers ::__construct
*/
public function testThrowsExceptionWhenLatitudeTooLow(): void
{
$this->expectException(InvalidBoundingBoxPositionException::class);
$this->expectExceptionMessage('The latitude should be between -90 and 90, "-90.01" provided.');
new BoundingBoxPosition(0, -90.01);
}
/**
* @covers ::__construct
*/
public function testValidBoundingBoxPositions(): void
{
new BoundingBoxPosition(0, 0);
new BoundingBoxPosition(360, 90);
new BoundingBoxPosition(-360, 90);
new BoundingBoxPosition(360, -90);
new BoundingBoxPosition(-360, -90);
// There are no assertions as we only check if there is no exception thrown here
$this->addToAssertionCount(1);
}
}
<file_sep>/src/Geometry/GeometryObject/Polygon.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Geometry\GeometryObject;
class Polygon extends GeometryObject
{
/** @var LineString[] elements representing interior rings (or holes) */
protected array $interiorRings = [];
public function __construct(protected LineString $exteriorRing)
{
}
public function addInteriorRing(LineString $lineString): self
{
$this->interiorRings[] = $lineString;
return $this;
}
public function getExteriorRing(): LineString
{
return $this->exteriorRing;
}
/**
* @return LineString[]
*/
public function getInteriorRings(): array
{
return $this->interiorRings;
}
}
<file_sep>/tests/Unit/Html/Elements/SvgElementTest.php
<?php
declare(strict_types=1);
namespace PrinsFrank\PhpGeoSVG\Tests\Unit\Html\Elements;
use PHPUnit\Framework\TestCase;
use PrinsFrank\PhpGeoSVG\Html\Elements\SvgElement;
/**
* @coversDefaultClass \PrinsFrank\PhpGeoSVG\Html\Elements\SvgElement
*/
class SvgElementTest extends TestCase
{
/**
* @covers ::getTagName
*/
public function testGetTagName(): void
{
static::assertSame('svg', (new SvgElement())->getTagName());
}
}
| ca6e88db58397ed4232c367cd9e514f9192f4845 | [
"Markdown",
"PHP"
]
| 82 | PHP | PrinsFrank/php-geo-svg | a87b69e32285c743b705b673942835c3a9ec410f | 4c7831734aec519c374bc5316e83289b24f114c5 |
refs/heads/master | <repo_name>multiarts/crumbs<file_sep>/spec/CrumbsItemSpec.php
<?php
namespace spec\Atorscho\Crumbs;
use Illuminate\Config\Repository as Config;
use Illuminate\Routing\UrlGenerator;
use Mockery;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class CrumbsItemSpec extends ObjectBehavior
{
/**
* @var \Mockery\MockInterface
*/
protected $urlMock;
/**
* @var \Mockery\MockInterface
*/
protected $configMock;
public function let()
{
$this->urlMock = Mockery::mock(UrlGenerator::class);
$this->configMock = Mockery::mock(Config::class);
$this->beConstructedWith('/home', 'Home Page', $this->urlMock, $this->configMock);
}
public function it_is_initializable()
{
$this->shouldHaveType('Atorscho\Crumbs\CrumbsItem');
}
public function it_returns_item_url()
{
$this->url->shouldReturn('/home');
}
public function it_returns_item_title()
{
$this->title->shouldReturn('Home Page');
}
public function it_detects_active_item_and_returns_true()
{
$this->urlMock->shouldReceive('current')->once()->andReturn('/home');
$this->isActive()->shouldReturn(true);
}
public function it_outputs_active_class_attribute_when_on_current_crumbs_item()
{
$this->configMock->shouldReceive('get')->once()->andReturn('active');
$this->urlMock->shouldReceive('current')->once()->andReturn('/home');
$this->active()->shouldReturn('class="active"');
}
public function it_outputs_active_class_when_on_current_crumbs_item_and_argument_to_false()
{
$this->configMock->shouldReceive('get')->once()->andReturn('active');
$this->urlMock->shouldReceive('current')->once()->andReturn('/home');
$this->active(false)->shouldReturn('active');
}
public function it_throws_an_exception_when_an_inexisting_property_is_called()
{
$this->shouldThrow(\Atorscho\Crumbs\Exceptions\PropertyNotFoundException::class)->during('__get', ['someProperty']);
}
}
<file_sep>/src/Crumbs.php
<?php
namespace Atorscho\Crumbs;
use Illuminate\Config\Repository as Config;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Translation\Translator;
/**
* Atorscho\Crumbs\Crumbs
*
* @package Atorscho\Crumbs
* @version 2.1.6
*/
class Crumbs
{
/**
* The array of breadcrumb items.
*
* @var array
*/
protected $crumbs = [];
/**
* @var Router
*/
protected $route;
/**
* @var UrlGenerator
*/
protected $url;
/**
* @var Request
*/
protected $request;
/**
* @var Config
*/
protected $config;
/**
* @var Translator
*/
protected $translator;
/**
* @param Request $request
* @param Router $route
* @param UrlGenerator $url
* @param Config $config
* @param Translator $translator
*/
public function __construct(
Request $request,
Router $route,
UrlGenerator $url,
Config $config,
Translator $translator
) {
$this->request = $request;
$this->route = $route;
$this->url = $url;
$this->config = $config;
$this->translator = $translator;
$this->autoAddItems();
}
/**
* Add new item to the breadcrumbs array.
*
* @param string $url
* @param string $title
* @param array $parameters
*
* @return $this
*/
public function add($url, $title = '', $parameters = [])
{
// If only {$url} specified, use it as title for current page
if (func_num_args() === 1) {
return $this->addCurrent($url);
}
$url = $this->parseUrl($url, $parameters);
$this->crumbs[] = new CrumbsItem($url, $title, $this->url, $this->config);
return $this;
}
/**
* Add current page to the breadcrumbs array.
*
* @param string $title
*
* @return $this
*/
public function addCurrent($title)
{
return $this->add($this->url->current(), $title);
}
/**
* Add home page to the breadcrumbs array.
*
* @return $this
*/
public function addHomePage()
{
return $this->add($this->config->get('crumbs.home_url'), $this->config->get('crumbs.home_title'));
}
/**
* Add admin page to the breadcrumbs array.
*
* @return $this
*/
public function addAdminPage()
{
return $this->add($this->config->get('crumbs.admin_url'), $this->config->get('crumbs.admin_title'));
}
/**
* Return structured page title string.
*
* @param string $appends A string to append.
*
* @return string
*
* @since 2.1.7
*/
public function pageTitle($appends = '')
{
// Get crumbs titles
$crumbs = array_map(function ($crumb) {
return $crumb->title;
}, $this->crumbs);
// Reverse array elements order
$crumbs = array_reverse($crumbs);
$title = implode($this->config->get('crumbs.page_title_separator'), $crumbs);
return $title . ($title ? $appends : '');
}
/**
* Render breadcrumbs HTML.
*
* @param string $view Custom breadcrumbs template view.
*
* @return string Breadcrumbs template with all items.
*/
public function render($view = '')
{
// Check for existing crumbs items
if (!$this->hasItems()) {
return '';
}
// Check for custom view
if (!$view) {
$view = $this->config->get('crumbs.crumbs_view');
}
return view($view, ['crumbs' => $this->getCrumbs()])->render();
}
/**
* Get first item of the breadcrumbs array.
*
* @return mixed
*/
public function getFirstItem()
{
return $this->hasCrumbs() ? $this->getCrumbs()[0] : false;
}
/**
* Get last item of the breadcrumbs array.
*
* @return mixed
*/
public function getLastItem()
{
return $this->hasCrumbs() ? end($this->getCrumbs()) : false;
}
/**
* Get the breadcrumbs array.
*
* @return array
*/
public function getCrumbs()
{
return $this->crumbs;
}
/**
* Return true if breadcrumbs are not empty.
*
* @return bool
*/
protected function hasCrumbs()
{
return (bool) $this->getCrumbs() && $this->hasManyItems();
}
/**
* Return true if breadcrumbs has at least one item.
*
* @return bool
*/
protected function hasItems()
{
return (bool) count($this->getCrumbs());
}
/**
* Return true if breadcrumbs have more than one item.
*
* @return bool
*/
protected function hasManyItems()
{
return count($this->getCrumbs()) > 1;
}
/**
* Return a named route if it exists.
*
* @param string $url
* @param array $parameters
*
* @return string
*/
protected function parseUrl($url, $parameters)
{
// If provided $url is a route name...
if ($this->route->has($url)) {
$url = $this->url->route($url, $parameters);
} else {
$url = $this->url->to($url, $parameters);
}
return $url;
}
/**
* Automatically prefix breadcrumbs with default items.
*
* @return void
*/
protected function autoAddItems()
{
if ($this->config->get('crumbs.display_both_pages')) {
$this->addHomePage();
if ($this->request->is($this->config->get('crumbs.admin_pattern'))) {
$this->addAdminPage();
}
} else {
if ($this->config->get('crumbs.display_home_page') && !$this->request->is($this->config->get('crumbs.admin_pattern'))) {
$this->addHomePage();
}
if ($this->config->get('crumbs.display_admin_page') && $this->request->is($this->config->get('crumbs.admin_pattern'))) {
$this->addAdminPage();
}
}
}
/**
* Return an instance of Crumbs.
*
* @return $this
*
* @since 2.1.7
*/
public function getInstance()
{
return $this;
}
}
<file_sep>/src/Exceptions/PropertyNotFoundException.php
<?php
namespace Atorscho\Crumbs\Exceptions;
class PropertyNotFoundException extends \Exception
{
}
<file_sep>/README.md
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Total Downloads][ico-downloads]][link-downloads]
[![StyleCI][ico-styleci]][link-styleci]
[![Software License][ico-license]][link-license]
Simple and functional breadcrumbs package for Laravel 5.
> [v1 branch][link-branch-v1] is for Laravel 4.
## Summary
* [Installation](docs/installation.md)
* [How To Use](docs/howto.md)
## Change log
Please see [CHANGELOG][link-changelog] for more information what has changed recently.
## Contributing
Please see [CONTRIBUTING][link-contributing] for details.
## Security
If you discover any security related issues, please contact me via the form below instead of using the issue tracker.
## Credits
- [<NAME>][link-author]
- [All Contributors][link-contributors]
## License
The MIT License (MIT). Please see [License File][link-license] for more information.
[ico-version]: https://poser.pugx.org/atorscho/crumbs/version
[ico-license]: https://poser.pugx.org/atorscho/crumbs/license
[ico-downloads]: https://poser.pugx.org/atorscho/crumbs/downloads
[ico-styleci]: https://styleci.io/repos/26128680/shield?style=flat
[link-branch-v1]: https://github.com/atorscho/crumbs/tree/v1
[link-packagist]: https://packagist.org/packages/atorscho/crumbs
[link-downloads]: https://packagist.org/packages/atorscho/crumbs
[link-styleci]: https://styleci.io/repos/26128680
[link-author]: https://github.com/atorscho
[link-contributors]: https://github.com/atorscho/crumbs/graphs/contributors
[link-contributing]: https://github.com/atorscho/crumbs/blob/master/CONTRIBUTING.md
[link-changelog]: https://github.com/atorscho/crumbs/blob/master/CHANGELOG.md
[link-license]: https://github.com/atorscho/crumbs/blob/master/LICENSE.md
[link-howto]: http://alextorscho.com/docs/crumbs/how-to-use<file_sep>/spec/CrumbsSpec.php
<?php
namespace spec\Atorscho\Crumbs;
use Illuminate\Config\Repository as Config;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Translation\Translator;
use Mockery;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class CrumbsSpec extends ObjectBehavior
{
/**
* @var \Mockery\MockInterface
*/
protected $requestMock;
/**
* @var \Mockery\MockInterface
*/
protected $routeMock;
/**
* @var \Mockery\MockInterface
*/
protected $urlMock;
/**
* @var \Mockery\MockInterface
*/
protected $configMock;
/**
* @var \Mockery\MockInterface
*/
protected $translatorMock;
public function let()
{
$this->requestMock = Mockery::mock(Request::class);
$this->routeMock = Mockery::mock(Router::class);
$this->urlMock = Mockery::mock(UrlGenerator::class);
$this->configMock = Mockery::mock(Config::class);
$this->translatorMock = Mockery::mock(Translator::class);
$this->beConstructedWith($this->requestMock, $this->routeMock, $this->urlMock, $this->configMock, $this->translatorMock);
}
public function it_is_initializable()
{
$this->shouldHaveType('Atorscho\Crumbs\Crumbs');
}
public function it_adds_an_item_to_the_breadcrumbs_array()
{
$this->routeMock->shouldReceive('has')->once()->andReturn(false);
$this->urlMock->shouldReceive('to')->once()->andReturn('http://example.com/articles');
$this->configMock->shouldReceive('get')->once()->andReturn(false);
$this->configMock->shouldReceive('get')->twice()->andReturn(true);
$this->requestMock->shouldReceive('is')->once()->andReturn(false);
$this->requestMock->shouldReceive('is')->once()->andReturn(true);
$this->add('/articles', 'All Articles');
$this->getCrumbs()[0]->shouldBeAnInstanceOf(\Atorscho\Crumbs\CrumbsItem::class);
}
public function it_adds_current_page_by_only_specifying_its_title()
{
$this->urlMock->shouldReceive('current')->once()->andReturn('http://example.com/articles');
$this->routeMock->shouldReceive('has')->once()->andReturn(false);
$this->urlMock->shouldReceive('to')->once()->andReturn('http://example.com/articles');
$this->configMock->shouldReceive('get')->once()->andReturn(false);
$this->configMock->shouldReceive('get')->twice()->andReturn(true);
$this->requestMock->shouldReceive('is')->once()->andReturn(false);
$this->requestMock->shouldReceive('is')->once()->andReturn(true);
$this->addCurrent('All Articles');
$this->getCrumbs()[1]->title->shouldBeEqualTo('All Articles');
}
}
<file_sep>/SUMMARY.md
# Summary
* [Installation](docs/installation.md)
* [How To Use](docs/howto.md)<file_sep>/src/helpers.php
<?php
if (!function_exists('crumbs')) {
/**
* Add an item to the breadcrumbs.
* If no parameters specified, return an instance of Crumbs.
*
* @param string $url
* @param string $title
* @param array $parameters
*
* @return Crumbs
*/
function crumbs($url = '', $title = '', $parameters = [])
{
if (func_num_args() === 0) {
return Crumbs::getInstance();
} elseif (func_num_args() === 1) {
return Crumbs::addCurrent($url);
}
return Crumbs::add($url, $title, $parameters);
}
}
<file_sep>/docs/installation.md
# Installation
## Composer
To install "Crumbs", you must add a new dependency to your root `composer.json` file:
```json
"atorscho/crumbs": "^2.2"
```
`"^2.1"` for Laravel 5.1, `"^2.0"` for Laravel 5.0, `"^1.0"` for Laravel 4.2.
## Service Provider
Now add new Service Provider to your `providers` array in `/config/app.php`:
```php
Atorscho\Crumbs\CrumbsServiceProvider::class,
```
## Configurations
In order to copy Crumbs' configuration file `crumbs.php` to your `/config` directory, you must run artisan command:
```
php artisan vendor:publish --provider="Atorscho\Crumbs\CrumbsServiceProvider" --tag="config"
```<file_sep>/src/CrumbsItem.php
<?php
namespace Atorscho\Crumbs;
use Atorscho\Crumbs\Exceptions\PropertyNotFoundException;
use Illuminate\Config\Repository as Config;
use Illuminate\Routing\UrlGenerator;
/**
* Atorscho\Crumbs\CrumbsItem
*
* @property string $title Item title.
* @property string $url Item URL.
*
* @package Atorscho\Crumbs
* @version 2.1.6
*/
class CrumbsItem
{
/**
* @var string
*/
protected $url;
/**
* @var string
*/
protected $title;
/**
* @var UrlGenerator
*/
protected $routing;
/**
* @var Config
*/
protected $config;
/**
* @param string $url
* @param string $title
* @param UrlGenerator $routing
* @param Config $config
*/
public function __construct($url, $title, UrlGenerator $routing, Config $config)
{
$this->url = $url;
$this->title = $title;
$this->routing = $routing;
$this->config = $config;
}
/**
* Return current crumb item class name when needed.
*
* @param bool $attr If true, it will return `class="active"`.
* @param string $className Active item class. Default: 'active'
*
* @return string
*/
public function active($attr = true, $className = '')
{
if (!$className) {
$className = $this->config->get('crumbs.current_item_class');
}
if ($attr) {
return $this->isActive() ? 'class="' . $className . '"' : '';
}
return $this->isActive() ? $className : '';
}
/**
* Return disabled class name when needed.
*
* @param string $className
*
* @return mixed|string
*/
public function disabled($className = '')
{
if (!$className) {
$className = $this->config->get('crumbs.disabled_item_class');
}
return $this->isDisabled() ? $className : '';
}
/**
* Return true if current breadcrumb item is active.
*
* @return bool
*/
public function isActive()
{
return $this->url == $this->routing->current();
}
/**
* Return true if current breadcrumb item is disabled.
*
* @return bool
*/
public function isDisabled()
{
return $this->url == '#';
}
/**
* Return only class' properties.
*
* @param string $property
*
* @return mixed
* @throws PropertyNotFoundException
*/
public function __get($property)
{
if (array_key_exists($property, get_class_vars(__CLASS__))) {
return $this->{$property};
}
throw new PropertyNotFoundException("Property [$property] not found in class [" . __CLASS__ . '].');
}
}
<file_sep>/src/CrumbsServiceProvider.php
<?php
namespace Atorscho\Crumbs;
use Blade;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider;
class CrumbsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
require __DIR__ . '/helpers.php';
$this->registerViews();
$this->registerConfigs();
$this->registerBladeExtension();
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
// Register Crumbs
$this->app->bind('crumbs', function (Application $app) {
return $app->make(Crumbs::class);
});
// Register an Alias
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Crumbs', CrumbsFacade::class);
});
}
/**
* Extending Blade with new 'crumbs' directive.
*/
protected function registerBladeExtension()
{
Blade::directive('crumbs', function ($view = '') {
return "<?php echo Crumbs::render({$view}); ?>";
});
}
/**
* Setup views.
*/
protected function registerViews()
{
$this->loadViewsFrom(__DIR__ . '/../resources/views', 'crumbs');
$this->publishes([
__DIR__ . '/../resources/views' => base_path('resources/views/vendor/crumbs')
], 'views');
}
/**
* Register configuration file.
*/
protected function registerConfigs()
{
$this->publishes([
__DIR__ . '/../config/crumbs.php' => config_path('crumbs.php')
], 'config');
$this->mergeConfigFrom(__DIR__ . '/../config/crumbs.php', 'crumbs');
}
}
<file_sep>/CHANGELOG.md
# Changelog
All Notable changes to `crumbs` will be documented in this file.
## NEXT - 2.2.2
### Modified
- `admin_Pattern` config to `admin_pattern`.
- Some changes to config comments.
### Fixed
- CS fixed.
## 2.2.1 [2016-04-03]
### Added
- `Crumbs::pageTitle()` now takes a `$appends` argument which appends a string to the title.
## 2.2.0 [2016-03-17]
### Added
- Laravel 5.2 Support. (Thanks to [pionl](https://github.com/pionl))
## 2.1.7 [2015-12-27]
### Added
- New `Crumbs::pageTitle()` method which outputs a structured page title.
### Modified
- The "crumbs-" prefix from views has been removed.
- Configuration file options have been snaked_cased.
## 2.1.6 [2015-12-24]
### Added
- New helper function `crumbs()`:
``` php
crumbs('/home', 'Home Page')->add('/categories', 'Categories')->add('Main Category');
```
### Modified
- `Crumbs::add()` now adds current page (its alias `Crumbs::addCurrent()`) if only {$url} specified.
## 2.1.5 [2015-09-04]
### Added
- `CrumbsItem`: disabled state.
- Foundation Framework template views.
### Modified
- `Crumbs::render` and `@crumbs`: now take an optional `$view` parameter.
- Semantic UI views have a new separator.
- Template views now unescape titles so you may pass an icon with/instead of the string.
### Fixed
- Semantic UI views.
### Removed
- `Crumbs::parseConfigLocalization()` removed from the class.
## 2.1.4 [2015-08-27]
### Added
- Semantic UI and Twitter Bootstrap views with microdatas.
### Modified
- `CrumbsItem::active()` got a new parameter `className` to change the active item class name.
## 2.1.3 [2015-08-06]
### Added
- PhpSpec tests.
### Replaced
- Calls to `config()` helper function replaced with relevant class method call for better unit testing.
## 2.1.2 [2015-08-06]
### Added
- Support for configuration localizations.
- StyleCI support.
### Fixed
- Problem with localized strings in config file.
- Bug detecting admin pages if URL has some prefixes (for example `'/en/admin'`).
## 2.0.0 - 2.1.1 [2015-05-13 - 2015-06-15]
### Added
- Support for Laravel 5.1
- Automatic breadcrumbs items
- More config options
- Blade extension: `@crumbs`
- Other minor features
- PSR-2 Code Style
<file_sep>/docs/howto.md
# How To Use
## Quick Start
In order to add breadcrumb items, you can simply use the `Crumbs` facade in your controller's method:
```php
public function index()
{
Crumbs::add('/users', 'List of Users');
$users = User::all();
return view('users.index', compact('users'));
}
```
When adding current page, you may use the `addCurrent( $title )` method instead of the simple `add( $url, $title, $params = [] )`:
```php
public function index()
{
Crumbs::addCurrent('List of Users');
$users = User::all();
return view('users.index', compact('users'));
}
```
If you use route names, just specify it instead of the URL:
```php
public function show(User $user)
{
Crumbs::add('users.index', 'List of Users'));
Crumbs::add("{$user->name}'s Profile"); // is the same as 'addCurrent()'
return view('users.show', compact('user'));
}
```
When needed, you may specify route parameters as the third parameter, just as you would with the Laravel's `route()` function:
```php
public function edit(User $user)
{
Crumbs::add('users.index', 'List of Users'));
Crumbs::add('users.show', $user->name, $user->id);
Crumbs::addCurrent($user->name);
return view('users.edit', compact('user'));
}
```
You may also use the helper function `crumbs()`:
``` php
crumbs('/categories', 'Categories')->add('main-category', 'Main Category')->add('Sample Article');
```
## Let's Dig In
### Default and Custom Crumbs Templates
You will need to render the created breacrumbs somewhere in your template. To do so you have two options: `Crumbs::render($view = '')` or the Blade extension `@crumbs` or `@crumbs($view)` which is just a shortcut for this `Crumbs` method.
```html
<div class="column">
@crumbs
<h1>Welcome!</h1>
</div>
```
The `crumbsView` config from `/config/crumbs.php` is the default template for all your breadcrumb lists. This is what will be used when you just call `@crumbs` with no arguments. The `$view` parameter from above rewrites this option.
### Templates Overview
Crumbs come with several view files for three popular CSS frameworks: Twitter Bootstrap, Foundation and Semantic UI. Each one also includes a microdata variation (`-md` suffix).
```html
<ul class="breadcrumbs">
@foreach ($crumbs as $crumb)
<li class="{{ $crumb->active(false, 'current') }} {{ $crumb->disabled('unavailable') }}">
<a href="{{ $crumb->url }}">
{!! $crumb->title !!}
</a>
</li>
@endforeach
</ul>
```
Each view template has access to the `crumbs` variable. Each of its items is an instance of `CrumbsItem` class which gives you access to:
- `$url` property
- `$title` property: is unescaped, so you may also use icons in your breadcrumbs (e.g. the home icon).
- `isActive()` method
- `isDisabled()` method
- `active($attr = true, $className = '')` method
- `disabled($className = '')` method
#### `isActive()`
Checks wheter the crumb item is the current page. Return `true` or `false`.
#### `isDisabled()`
Returns true if crumb item's URL is equal to `'#'`.
#### `active()`
If `$attr` is true, returns `class="{active}"`, if false: `{active}`. `{active}` being the active item class defined in the `/config/crumbs.php` file. You may also pass it as a second argument.
#### `disabled()`
Returns the disabled class name defined in the `/config/crumbs.php` file, or you may once again pass it as a second argument.
### Autogenerated Crumbs Items
In the `/config/crumbs.php` file you may find the 'Display Default Crumbs Items' section.
```php
[
'display_home_page' => true,
'display_admin_page' => true,
'display_both_pages' => false
];
```
What it does is simply adding to the beginning the 'Home' and 'Admin' sections.
```php
Crumbs::add('users.index', 'List of Users'));
Crumbs::addCurrent("{$user->name}'s Profile");
```
Becomes:
```
Home > List of Users > User's Profile
```
Because of the `'display_home_page' => true`. If your current page's URL matches the `*admin*` pattern (which also is configurable), it will replace the 'Home' with 'Admin':
```
Admin > List of Users > User's Profile
```
If `'display_both_pages' => true`, it will use both of them, if they are `true`.
```
Home > Admin > List of Users > User's Profile
```
You may configure the home and admin pages' URLs.
### Page Title
Since 2.1.7 you may use the `Crumbs::pageTitle()` method to output structured title string.
```html
<title>{{ crumbs()->pageTitle() }}</title>
```
It takes uses the Crumbs titles to build a page title.
There is a special configuration option `page_title_separator` in `/config/crumbs.php` where you can change the separator for each item. Default: `' » '`. | c4b9691abdfde72ed183e371766a37d386b2ccb7 | [
"Markdown",
"PHP"
]
| 12 | PHP | multiarts/crumbs | 6c4f75d5a8d9100d644585a01d84ed680f0fd715 | f411a56fcab09dc52fdd0ad2cd0b5457ceb7d416 |
refs/heads/master | <repo_name>omnicolor/php-server-sdk<file_sep>/src/LaunchDarkly/Util.php
<?php
namespace LaunchDarkly;
use DateTime;
use DateTimeZone;
class Util
{
/**
* @param $dateTime DateTime
* @return int
*/
public static function dateTimeToUnixMillis($dateTime)
{
$timeStampSeconds = (int)$dateTime->getTimestamp();
$timestampMicros = $dateTime->format('u');
return $timeStampSeconds * 1000 + (int)($timestampMicros / 1000);
}
/**
* @return int
*/
public static function currentTimeUnixMillis()
{
return Util::dateTimeToUnixMillis(new DateTime('now', new DateTimeZone("UTC")));
}
/**
* @param $key string
* @param $user LDUser
* @param $value
* @param $default
* @param null $version int | null
* @param null $prereqOf string | null
* @return array
*/
public static function newFeatureRequestEvent($key, $user, $variation, $value, $default, $version = null, $prereqOf = null, $reason = null)
{
$event = array();
$event['user'] = $user;
$event['variation'] = $variation;
$event['value'] = $value;
$event['kind'] = "feature";
$event['creationDate'] = Util::currentTimeUnixMillis();
$event['key'] = $key;
$event['default'] = $default;
$event['version'] = $version;
$event['prereqOf'] = $prereqOf;
if ($reason !== null) {
$event['reason'] = $reason->jsonSerialize();
}
return $event;
}
/**
* @param $status int
* @return boolean
*/
public static function isHttpErrorRecoverable($status)
{
if ($status >= 400 && $status < 500) {
return ($status == 400) || ($status == 408) || ($status == 429);
}
return true;
}
/**
* @param $status int
* @param $context string
* @param $retryMessage string
* @return string
*/
public static function httpErrorMessage($status, $context, $retryMessage)
{
return 'Received error ' . $status
. (($status == 401) ? ' (invalid SDK key)' : '')
. ' for ' . $context . ' - '
. (Util::isHttpErrorRecoverable($status) ? $retryMessage : 'giving up permanently');
}
}
<file_sep>/scripts/release.sh
#!/usr/bin/env bash
# This script updates the version in the client code. It does not need to do anything else to release
# a new version, because Packagist will pick up the new version automatically by watching our public
# repository.
# It takes exactly one argument: the new version.
# It should be run from the root of this git repo like this:
# ./scripts/release.sh 4.0.9
# When done you should commit and push the changes made.
set -uxe
echo "Starting php-server-sdk release (version update only)"
VERSION=$1
echo $VERSION >./VERSION
# Update version in LDClient class
LDCLIENT_PHP=src/LaunchDarkly/LDClient.php
LDCLIENT_PHP_TEMP=./LDClient.php.tmp
sed "s/const VERSION = '.*'/const VERSION = '${VERSION}'/g" $LDCLIENT_PHP > $LDCLIENT_PHP_TEMP
mv $LDCLIENT_PHP_TEMP $LDCLIENT_PHP
echo "Done with php-server-sdk release (version update only)"
| d9d69fe55f29b8a1b97e59de7cb3e040c9dec6de | [
"PHP",
"Shell"
]
| 2 | PHP | omnicolor/php-server-sdk | a75d288fdf9ede16d3beda298d7fde98408c4cd7 | cb9deaaa725957a85990475fc50acc9e6fdb1d54 |
refs/heads/master | <repo_name>jinsu3758/BrandNews<file_sep>/BrandNews/Main/Word/NewsWordViewController.swift
//
// NewsWordViewController.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
class NewsWordViewController: UIViewController {
@IBOutlet weak var wordCollectionView: UICollectionView!
@IBOutlet weak var ovalView: UIView!
private var wordList: [Word] = []
override func viewDidLoad() {
super.viewDidLoad()
ovalView.layer.cornerRadius = 9.3
wordCollectionView.register(UINib.init(nibName: "WordCell", bundle: nil), forCellWithReuseIdentifier: "cell")
if let flowLayout = self.wordCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
wordCollectionView.dataSource = self
wordCollectionView.delegate = self
setList()
}
private func setList() {
wordList.append(Word(sentence: "선행", frequency: 110, category: .good))
wordList.append(Word(sentence: "송치", frequency: 120, category: .bad))
wordList.append(Word(sentence: "공헌", frequency: 10, category: .good))
wordList.append(Word(sentence: "연탄봉사", frequency: 180, category: .good))
wordList.append(Word(sentence: "폭행", frequency: 30, category: .bad))
wordList.append(Word(sentence: "기부", frequency: 200, category: .good))
wordList.append(Word(sentence: "봉사", frequency: 30, category: .good))
wordList.append(Word(sentence: "입막음", frequency: 10, category: .bad))
wordList.append(Word(sentence: "위조", frequency: 70, category: .bad))
wordList.append(Word(sentence: "횡령", frequency: 120, category: .bad))
wordList.append(Word(sentence: "자선기부", frequency: 10, category: .good))
wordList.append(Word(sentence: "지원", frequency: 70, category: .bad))
wordCollectionView.reloadData()
}
}
extension NewsWordViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return wordList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? WordCell {
let frequencyList = wordList.map{$0.frequency}
cell.fill(word: wordList[indexPath.row], frequencyList: frequencyList)
return cell
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
}
<file_sep>/BrandNews/Model/Word.swift
//
// Word.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import Foundation
enum WordCategory {
case good
case bad
case place
case institute
case person
case rest
}
struct Word {
let sentence: String
let frequency: Int
let category: WordCategory
}
<file_sep>/BrandNews/Main/MainViewController.swift
//
// ViewController.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var companyNameLabel: UILabel!
@IBOutlet weak var companyFieldLabel: UILabel!
@IBOutlet weak var goodView: UIView!
@IBOutlet weak var badView: UIView!
@IBOutlet weak var badGoodView: UIView!
@IBOutlet weak var newsCollectionView: UICollectionView!
@IBOutlet weak var newsCollectionViewHeightConstraint: NSLayoutConstraint!
private var pageVC = UIPageViewController()
private var cellHeight: CGFloat = 0
var newsList: [NewsCard] = []
lazy var pageArray: [UIViewController] = {
return [getVC(name: "news"), getVC(name: "brand")]
}()
override func viewDidLoad() {
super.viewDidLoad()
guard let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView else { return }
statusBar.backgroundColor = .dark
pageVC.setViewControllers([pageArray[0]], direction: .forward, animated: true, completion: nil)
pageVC.delegate = self
pageVC.dataSource = self
pageControl.currentPage = pageArray.count
newsCollectionView.register(UINib(nibName: "GoodNewsCell", bundle: nil), forCellWithReuseIdentifier: "goodNewsCell")
newsCollectionView.register(UINib(nibName: "BadNewsCell", bundle: nil), forCellWithReuseIdentifier: "badNewsCell")
if let flowLayout = newsCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
newsCollectionView.delegate = self
newsCollectionView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let header1 = News(title: "네이버, LG유플러스와 AI기술로 사회적약자 돕는다", content: "네이버는 사회적 약자도 AI 기술 서비스를 쉽게 이용할 수 있도록 LG유플러스와 함께 지난해..", company: "네이버")
let list1 = [News(title: "네이버, LG U+, 지체장애인 300명 AI 스피커 지원", content: "ee", company: "데이터넷"), News(title: "네이버와 LG U+, 지체장애인에게 음원이용권 전달", content: "ee", company: "대한금융지원")]
let header2 = News(title: "구매직원 36억 횡령까지… 네이버에 무슨일이..", content: "인터넷업계 최강자 네이버가 흔들리고 있다. 네이버 창업 직후부터 일해 온 주요 임원들이...", company: "네이버")
let list2 = [News(title: "회삿돈으로 호화 요트 구입 혐의’ CJ 이재환 대표 불구속 송치", content: "ee", company: "네이버뉴스"), News(title: "NHN, 총체적 위기 직면..", content: "ee", company: "아이뉴스24")]
let header3 = News(title: "서울시-네이버, '교통약자·따릉이 길찾기 서비스' 개발", content: "네이버가 기존에 서비스하고 있는 최단시간, 최소 환승 중심 대중교통 경로 안내와 별도로 노약자나 장애인, 영유아 동반자, 무거운 짐을 든 관광객 등 '교통약자'를 위한 맞춤형 길찾기 및 내비게이션 기능을 네이버 교통안내 시스템에 추가한다", company: "네이버")
let list3 = [News(title: "서울시+네이버, 교통약자·따릉이 길찾기 서비스 만든다", content: "뉴스토마토", company: "뉴스토마토"), News(title: "서울시-네이버 손잡고 교통약자·따릉이 길찾기 서비스 개발", content: "ee", company: "위클리오늘")]
let cardList = [NewsCard(header: header1, list: list1, isGood: true, num: 1), NewsCard(header: header2, list: list2, isGood: false, num: 2), NewsCard(header: header3, list: list3, isGood: true, num: 3) ]
newsList = cardList
newsCollectionView.reloadData()
newsCollectionViewHeightConstraint.constant = newsCollectionView.collectionViewLayout.collectionViewContentSize.height
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let container = segue.destination as? UIPageViewController {
pageVC = container
}
}
private func getVC(name: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: name)
}
}
extension MainViewController: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = pageArray.firstIndex(of: viewController) else { return nil }
let previousIndex = index - 1
guard previousIndex >= 0 else { return pageArray.last }
guard pageArray.count > previousIndex else { return nil }
return pageArray[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = pageArray.firstIndex(of: viewController) else { return nil }
let nextIndex = index + 1
guard nextIndex < pageArray.count else { return pageArray.first }
guard pageArray.count > nextIndex else { return nil }
return pageArray[nextIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
if let page = self.pageArray.firstIndex(of: pendingViewControllers[0]) {
pageControl.currentPage = page
}
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return pageArray.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
}
extension MainViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return newsList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if newsList[indexPath.item].isGood, let goodCell = collectionView.dequeueReusableCell(withReuseIdentifier: "goodNewsCell", for: indexPath) as? GoodNewsCell {
goodCell.fill(news: newsList[indexPath.item])
return goodCell
}
else if let badCell = collectionView.dequeueReusableCell(withReuseIdentifier: "badNewsCell", for: indexPath) as? BadNewsCell {
badCell.fill(news: newsList[indexPath.item])
return badCell
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// let edgeInset = self.collectionView(collectionView, layout: collectionViewLayout, insetForSectionAt: indexPath.section)
// let width = collectionView.frame.width * 304 / 375
let newsCount = newsList[indexPath.item].list.count
let height = 85.5 + CGFloat(newsCount * 35)
return CGSize(width: 321, height: height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 9.5
}
}
<file_sep>/BrandNews/Main/News/NewsHeaderView.swift
//
// NewsHeaderView.swift
// BrandNews
//
// Created by 박진수 on 09/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
class NewsHeaderView: UICollectionReusableView {
@IBOutlet weak var newsImg: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
}
<file_sep>/BrandNews/Main/Word/WordCloudFlowLayout.swift
//
// WordCloudFlowLayout.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
class WordCloudFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let superAttributes = super.layoutAttributesForElements(in: rect) else { return nil }
guard let attributes = NSArray(array: superAttributes, copyItems: true) as? [UICollectionViewLayoutAttributes] else { return nil }
let interItemSpacing = minimumInteritemSpacing
// Tracking values
var maxY: CGFloat = -1.0 // to Know when the line breaks
var rowWidth: CGFloat = 0
var rowWidthList: [CGFloat] = []
var currentRow: Int = -1
//get the row width
attributes.forEach { layoutAttribute in
// Each layoutAttribute represents its own item
if layoutAttribute.frame.origin.y >= maxY {
currentRow += 1
maxY = layoutAttribute.frame.maxY
rowWidth = 0
rowWidthList.append(0)
}
rowWidth += layoutAttribute.frame.width
rowWidthList[currentRow] = rowWidth
rowWidth += interItemSpacing
}
// using Row Width. make first item of the row's x the value it should be when center aligned
// Then, locate following items having the minimum inter item spacing to the lft item
var leftMargin: CGFloat = 0 // to set attribute's frame.x
maxY = -1.0
currentRow = -1
attributes.forEach { layoutAttribute in
// Each layoutAttribute is its own item
if layoutAttribute.frame.origin.y >= maxY {
currentRow += 1
maxY = layoutAttribute.frame.maxY
leftMargin = (collectionView!.frame.width - rowWidthList[currentRow])/2
}
layoutAttribute.frame.origin.x = leftMargin
leftMargin += interItemSpacing + layoutAttribute.frame.width
//vertically center
if let collectionView = collectionView {
let topInset = (collectionView.frame.size.height - collectionViewContentSize.height) / 2
collectionView.contentInset = UIEdgeInsets(top: topInset, left: 0, bottom: 0, right: 0)
}
}
return attributes
}
}
<file_sep>/BrandNews/Model/News.swift
//
// News.swift
// BrandNews
//
// Created by 박진수 on 09/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import Foundation
struct News {
let title: String
let content: String
let company: String
init(title: String, content: String, company: String) {
self.title = title
self.content = content
self.company = company
}
}
<file_sep>/BrandNews/Main/News/BadNewsCell.swift
//
// BadNewsCell.swift
// BrandNews
//
// Created by 박진수 on 13/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
class BadNewsCell: UICollectionViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var rightView: UIView!
@IBOutlet weak var newsCollectionView: UICollectionView!
var newsList: [News] = []
var mainNews: News?
var newsNum: Int = 0
private let gradient = CAGradientLayer()
override func awakeFromNib() {
super.awakeFromNib()
// self.contentView.translatesAutoresizingMaskIntoConstraints = false
newsCollectionView.register(UINib(nibName: "NewsCell", bundle: nil), forCellWithReuseIdentifier: "newsCell")
newsCollectionView.register(UINib(nibName: "NewsHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "newsHeader")
newsCollectionView.delegate = self
newsCollectionView.dataSource = self
newsCollectionView.layer.setShadow(color: .veryDarkBrown7, alpha: 1, x: 0, y: 0, blur: 4, spread: 1.1)
}
func fill(news: NewsCard) {
self.newsList = news.list
self.mainNews = news.header
newsNum = news.num
self.newsCollectionView.collectionViewLayout.invalidateLayout()
self.newsCollectionView.reloadData()
self.newsCollectionView.performBatchUpdates(nil, completion: { [unowned self] _ in
self.gradient.frame = self.rightView.bounds
self.gradient.colors = [UIColor.vermillion.cgColor, UIColor.orange.cgColor]
self.rightView.layer.insertSublayer(self.gradient, at: 0)
})
self.newsCollectionView.reloadData()
}
}
extension BadNewsCell: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return newsList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "newsCell", for: indexPath)
if let newsCell = cell as? NewsCell {
// if indexPath.item == newsList.count - 1 {
// newsCell.bottomView.isHidden = true
// }
newsCell.fill(newsList[indexPath.item])
return newsCell
}
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "newsHeader", for: indexPath) as? NewsHeaderView else { fatalError()}
header.layoutIfNeeded()
header.titleLabel.text = mainNews!.title
header.contentLabel.text = mainNews!.content
header.newsImg.image = UIImage(named: "naver" + String(newsNum))
return header
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 296, height: 35)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: 294, height: 72)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
<file_sep>/BrandNews/Util/Extension.swift
//
// UIColor.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(hex: Int, a: CGFloat = 1.0) {
self.init(
red: (hex >> 16) & 0xFF,
green: (hex >> 8) & 0xFF,
blue: hex & 0xFF,
a: a
)
}
convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: a
)
}
class var dark: UIColor {
return UIColor(hex: 0x1c1f23)
}
class var veryDarkBrown7: UIColor {
return UIColor(red: 4, green: 0, blue: 0, a: 0.07)
}
class var textWhite: UIColor {
return UIColor(hex: 0xfefefe)
}
class var squash: UIColor {
return UIColor(red: 248, green: 165, blue: 27)
}
class var velvet: UIColor {
return UIColor(red: 129, green: 13, blue: 112)
}
class var grapefruit: UIColor {
return UIColor(red: 254, green: 88, blue: 88)
}
class var sapphire: UIColor {
return UIColor(red: 30, green: 51, blue: 175)
}
class var darkSkyBlue: UIColor {
return UIColor(red: 35, green: 137, blue: 223)
}
class var vermillion: UIColor {
return UIColor(red: 222, green: 14, blue: 14)
}
class var orange: UIColor {
return UIColor(red: 245, green: 96, blue: 6)
}
class var warmGrey: UIColor {
return UIColor(red: 155, green: 155, blue: 155)
}
class var turquoise: UIColor {
return UIColor(red: 0, green: 172, blue: 172)
}
class var sapphireTwo: UIColor {
return UIColor(red: 29, green: 37, blue: 167)
}
}
extension CALayer {
func setShadow(color: UIColor = .black, alpha: Float = 0.5, x: CGFloat = 0, y: CGFloat = 2, blur: CGFloat = 4, spread: CGFloat = 0) {
masksToBounds = false
shadowColor = color.cgColor
shadowOpacity = alpha
shadowOffset = CGSize(width: x, height: y)
shadowRadius = blur / 2.0
if spread == 0 {
shadowPath = nil
} else {
let dx = -spread
let rect = bounds.insetBy(dx: dx, dy: dx)
shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath
}
}
}
extension UIView {
enum ViewBorder {
case left
case right
case top
case bottom
}
func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
func addBorder(toSide side: ViewBorder, withColor color: UIColor, andThickness thickness: CGFloat) {
let border = CALayer()
border.backgroundColor = color.cgColor
switch side {
case .left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height)
case .right:
border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
case .top:
border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
case .bottom:
border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
}
layer.addSublayer(border)
}
}
<file_sep>/BrandNews/Model/NewsCard.swift
//
// NewsCard.swift
// BrandNews
//
// Created by 박진수 on 09/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import Foundation
struct NewsCard {
let header: News
let list: [News]
let isGood: Bool
let num: Int
}
<file_sep>/BrandNews/Main/Word/BrandWordViewController.swift
//
// BrandWordViewController.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
class BrandWordViewController: UIViewController {
@IBOutlet weak var wordCollectionView: UICollectionView!
@IBOutlet weak var ovalView: UIView!
private var wordList: [Word] = []
override func viewDidLoad() {
super.viewDidLoad()
ovalView.layer.cornerRadius = 9.3
wordCollectionView.register(UINib.init(nibName: "WordCell", bundle: nil), forCellWithReuseIdentifier: "cell")
if let flowLayout = self.wordCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
wordCollectionView.dataSource = self
wordCollectionView.delegate = self
setList()
}
private func setList() {
wordList.append(Word(sentence: "카카오톡", frequency: 100, category: .institute))
wordList.append(Word(sentence: "판교", frequency: 50, category: .place))
wordList.append(Word(sentence: "한성숙", frequency: 10, category: .person))
wordList.append(Word(sentence: "라이브러리", frequency: 30, category: .rest))
wordList.append(Word(sentence: "iOS", frequency: 70, category: .rest))
wordList.append(Word(sentence: "송창현", frequency: 120, category: .person))
wordList.append(Word(sentence: "일본", frequency: 10, category: .place))
wordList.append(Word(sentence: "쿠팡", frequency: 180, category: .institute))
wordList.append(Word(sentence: "배달의민족", frequency: 50, category: .institute))
wordList.append(Word(sentence: "게임", frequency: 10, category: .rest))
wordList.append(Word(sentence: "노래", frequency: 30, category: .rest))
wordList.append(Word(sentence: "기안84", frequency: 70, category: .person))
wordList.append(Word(sentence: "서울", frequency: 190, category: .place))
wordList.append(Word(sentence: "네이버웹툰", frequency: 50, category: .institute))
wordCollectionView.reloadData()
}
}
extension BrandWordViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return wordList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? WordCell {
let frequencyList = wordList.map{$0.frequency}
cell.fill(word: wordList[indexPath.row], frequencyList: frequencyList)
return cell
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
}
<file_sep>/BrandNews/Main/MainDataController.swift
//
// MainDataController.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
enum NewsState: String {
case bad = "bad"
case good = "good"
}
enum Path: String {
case newsList = "/access_news_list/"
}
class MainDataController: NSObject {
static let baseUrl = "http://ec2-13-124-106-168.ap-northeast-2.compute.amazonaws.com:8080"
static func getNews(brand: String, _ state: NewsState) -> [News] {
let parameter = [
"access_key": "ere",
"brand_key": "ere",
"brand_name": brand,
"from": "2015-01-01",
"top_count": "10",
"until": "2019-05-14"
]
var newsList: [News] = []
Alamofire.request(baseUrl + "/analyze/access_news_list/" + state.rawValue, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: nil)
.validate()
.responseJSON { response in
if response.result.isSuccess {
if let data = response.result.value {
let json = JSON(data)
for item in json["return_object"]["documents"].arrayValue {
newsList.append(News(title: item["title"].stringValue, content: item["content"].stringValue, company: item["provider"].stringValue))
}
}
}
else {
guard let error = response.result.error else { return }
print("\(error.localizedDescription)!!")
}
}
return newsList
}
}
<file_sep>/BrandNews/Custom/CircleView.swift
//
// CircleView.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
class CircleView: UIView {
override func awakeFromNib() {
self.layer.cornerRadius = self.frame.width / 2
}
}
<file_sep>/BrandNews/Main/Word/WordCell.swift
//
// WordCell.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
class WordCell: UICollectionViewCell {
@IBOutlet weak var wordLabel: UILabel!
// var frequencyList: [Int] = []
var maxFrequency:Int = 0
var minFrequency:Int = 0
let maxFontSize:CGFloat = 36
let minFontSize:CGFloat = 12
let maxAlpha:CGFloat = 1
let minAlpha:CGFloat = 0.5
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.translatesAutoresizingMaskIntoConstraints = false
}
func fill(word: Word, frequencyList: [Int]) {
maxFrequency = frequencyList.max() ?? 0
minFrequency = frequencyList.min() ?? 0
wordLabel.text = word.sentence
let fontSize = self.calculateItemValue(minValue: minFontSize, maxValue: maxFontSize, itemFrequency: word.frequency, minFrequency: minFrequency, maxFrequency: maxFrequency)
// wordLabel.font = wordLabel.font.withSize(fontSize)
wordLabel.font = UIFont(name: "YDIYGO350", size: fontSize)
// wordLabel.alpha = self.calculateItemValue(minValue: minAlpha, maxValue: maxAlpha, itemFrequency: word.frequency, minFrequency: minFrequency, maxFrequency: maxFrequency)
switch word.category {
case .institute:
self.wordLabel.textColor = .squash
case .person:
self.wordLabel.textColor = .velvet
case .place:
self.wordLabel.textColor = .turquoise
case .bad:
self.wordLabel.textColor = .vermillion
case .good:
self.wordLabel.textColor = .sapphireTwo
case .rest:
self.wordLabel.textColor = .grapefruit
}
}
func calculateItemValue(minValue: CGFloat, maxValue: CGFloat, itemFrequency: Int, minFrequency: Int, maxFrequency: Int) -> CGFloat {
if maxFrequency == minFrequency {
return (maxValue + minValue)/2
}
let itemFrequency = CGFloat(itemFrequency)
let minFrequency = CGFloat(minFrequency)
let maxFrequency = CGFloat(maxFrequency)
let a = (maxValue - minValue)/(maxFrequency-minFrequency)
let b = (maxFrequency*minValue-minFrequency*maxValue)/(maxFrequency - minFrequency)
return a*itemFrequency + b
}
}
<file_sep>/BrandNews/Custom/ShadowView.swift
//
// ShadowView.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
class ShadowView: UIView {
override func awakeFromNib() {
self.layer.setShadow(color: .veryDarkBrown7, alpha: 1, x: 0, y: 0, blur: 4, spread: 1.1)
}
}
<file_sep>/BrandNews/Main/News/NewsCell.swift
//
// NewsCell.swift
// BrandNews
//
// Created by 박진수 on 09/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import UIKit
class NewsCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var companyLabel: UILabel!
@IBOutlet weak var bottomView: UIView!
func fill(_ news: News) {
titleLabel.text = news.title
companyLabel.text = news.company
}
}
<file_sep>/BrandNews/Util/Enums.swift
//
// Enums.swift
// BrandNews
//
// Created by 박진수 on 08/05/2019.
// Copyright © 2019 박진수. All rights reserved.
//
import Foundation
| 7d2129acada6be68f91a88f2ac2e9f7000790f25 | [
"Swift"
]
| 16 | Swift | jinsu3758/BrandNews | c882602bfbf7a21e9c0de7601570e3da9378fd89 | 15afabc1ffe6f793b83b393ae1dc0dc16c85a8b0 |
refs/heads/master | <file_sep>(function() {
$('.btn-clipboard').on('click', function(e) {
// e.preventDefault();
console.log('Is clicked');
var $flashMessage = $(this).parent().parent().parent().find('.alert');
$flashMessage.slideDown(function() {
setTimeout(function() {
$flashMessage.slideUp();
}, 1000);
})
}).zclip({
path: 'http://www.steamdev.com/zclip/js/ZeroClipboard.swf',
copy: function() {
return $(this).parent().parent().parent().find('.to-copy').html();
},
afterCopy: function() {
console.log('COPIED');
}
});
$('.btn-clipboard').hover(function() {
$(this).toggleClass('btn-clipboard-hover');
});
})();
<file_sep># [Load-icons.css](http://thomaslam.rocks/bower_components/load-icons-css/index.html)
A collection of free pure css loading icons created by [<NAME>](http://thomaslam.rocks)
## Browser Support
 |  |  |  | 
--- | --- | --- | --- | --- |
Latest ✔ | Latest ✔ | 10+ ✔ | Latest ✔ | Latest ✔ |
##Usage
Install via bower
```
$ bower install load-icons-css
```
or clone from github
```
$ git clone <EMAIL>.com:thomaslam/load-icons.css.git
```
Include link tag in your html file to where you install the load-icons-css package. E.g.
```
<head>
...
<link rel='stylesheet' href='./bower_components/load-icons-css/css/load-icons.css'>
...
</head>
```
Or include individual css files for specific animations.
Then include the appropriate div to where you want the load icon to appear. See all divs [here](http://thomaslam.rocks/bower_components/load-icons-css/index.html).
##Custom color
Go to `/sass/_shared.scss` (it's a Sass file). There are several color variables defined already, or you can create your own color (see below). Set `$color: $your-color`

Then compile Sass into CSS file. See [Sass](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
All Sass code for animations are in `/sass/icons/` directory. Feel free to customize to your liking.
##License
###MIT License
See LICENSE.md
| f84cb442f677590d1a10e0b25e9f59d68b005935 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | thomaslam/load-icons.css | 24bec086ba294a65a2ba13e75e1f0ace1130aadf | 1b4094b4449c45e9d5edfb1b138978abfa960c23 |
refs/heads/master | <repo_name>SokratisVidros/authx<file_sep>/test/tests/endpoints/session.js
'use strict';
const chai = require('chai');
const url = require('url');
var assert = chai.assert;
require('../../init.js');
describe('Session', () => {
it('should return 404 for an invalid authority', done => {
agent.get('/v1/session/foo')
.expect(404)
.end(done);
});
it('should return 404 for nonexistant user', done => {
agent.post('/v1/session/password')
.send({
username: ['password', '<PASSWORD>'],
password: '<PASSWORD>'
})
.expect(404)
.end(done);
});
it('should return 200 with a session cookie upon successful login', done => {
agent.post('/v1/session/password')
.send({
username: ['password', '<PASSWORD>'],
password: '<PASSWORD>'
})
.expect(200)
.expect(res => {
if(!res.headers['set-cookie'].some(c => /^session=.+/.test(c)))
throw new Error('Expect a cookie with the name `session`.');
})
.end(done);
});
it('should redirect with ?status=404 for nonexistant user', done => {
agent.post('/v1/session/password')
.query({
url: 'http://www.example.com/'
})
.send({
username: ['password', '<PASSWORD>'],
password: '<PASSWORD>'
})
.expect(302)
.expect(res => {
var query = url.parse(res.headers.location, true).query;
assert.equal(query.status, '404');
JSON.parse(query.body);
})
.end(done);
});
it('should redirect with ?status=200 and a session cookie upon successful login', done => {
agent.post('/v1/session/password')
.query({
url: 'http://www.example.com/'
})
.send({
username: ['password', '<PASSWORD>'],
password: '<PASSWORD>'
})
.expect(302)
.expect(res => {
var query = url.parse(res.headers.location, true).query;
assert.equal(query.status, '200');
JSON.parse(query.body);
})
.expect(res => {
if(!res.headers['set-cookie'].some(c => /^session=.+/.test(c)))
throw new Error('Expect a cookie with the name `session`.');
})
.end(done);
});
});
<file_sep>/src/models/Authority.js
const r = require('rethinkdb');
const Model = require('../Model');
const validate = require('../util/validator');
const errors = require('../errors');
const CREDENTIALS = Symbol('credentials');
// this is used to get around limitations of circular dependancies in commonjs
const models = {};
module.exports = class Authority extends Model {
static get table() {
return 'authorities';
}
static async create(conn, data) {
var now = Date.now() / 1000;
data = Object.assign({}, data, {created: now, last_updated: now});
// validate data
var err = validate('authority', data, {useDefault: true});
if (err) throw new errors.ValidationError('A valid authority must be supplied.', err.validation);
// update the model (use super.create when babel.js supports it)
return Model.create.call(this, conn, data);
}
static async save(conn, id, data) {
var now = Date.now() / 1000;
data = Object.assign({id: id}, data, {created: now, last_updated: now});
// validate data
var err = validate('authority', data, {useDefault: true});
if (err) throw new errors.ValidationError('A valid authority must be supplied.', err.validation);
if (data.id !== id) throw new Error('The supplied `id` did not match the `id` in the data.');
// don't overwrite an existing `created` timestamp
data.created = r.row('created').default(data.created);
// save the model (use super.create when babel.js supports it)
return Model.save.call(this, conn, id, data);
}
static async update(conn, id, data) {
data = Object.assign({}, data, {last_updated: Date.now() / 1000});
// validate data
var err = validate('authority', data, {checkRequired: false});
if (err) throw new errors.ValidationError('A valid authority must be supplied.', err.validation);
// update the model (use super.update when babel.js supports it)
return Model.update.call(this, conn, id, data);
}
async credentials(refresh) {
// query the database for users
if (!this[CREDENTIALS] || refresh)
this[CREDENTIALS] = await models.Credential.query(this[Model.Symbols.CONN], q => q.getAll(this.id, {index: 'authority_id'}));
return this[CREDENTIALS];
}
};
models.Credential = require('./Credential');
<file_sep>/test/tests/strategies/password.js
'use strict';
const chai = require('chai');
const url = require('url');
var assert = chai.assert;
require('../../init.js');
describe('Strategy: Password', () => {
it('should return 404 for nonexistant user', done => {
agent.post('/v1/session/password')
.send({
username: ['password', '<PASSWORD>'],
password: '<PASSWORD>'
})
.expect(404)
.end(done);
});
it('should return 401 for an incorrect password', done => {
agent.post('/v1/session/password')
.send({
username: ['password', '<PASSWORD>'],
password: '<PASSWORD>'
})
.expect(401)
.end(done);
});
it('should return 200 upon successful login', done => {
agent.post('/v1/session/password')
.send({
username: ['password', '<PASSWORD>'],
password: '<PASSWORD>'
})
.expect(200)
.end(done);
});
it('should identify users by the IDs of other authorities', done => {
agent.post('/v1/session/password')
.send({
username: ['email', '<EMAIL>'],
password: '<PASSWORD>'
})
.expect(200)
.end(done);
});
it('should accept a form-encoded body', done => {
agent.post('/v1/session/password')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('password=<PASSWORD>&username=password&username=a6a0946d-eeb4-45cd-83c6-c7920f2272eb')
.expect(200)
.end(done);
});
it('should accept HTTP basic credentials', done => {
agent.get('/v1/session/password')
.set('Authorization', 'Basic <KEY>
.expect(200)
.end(done);
});
});
<file_sep>/src/namespace.js
module.exports = Symbol('AuthX');<file_sep>/fixtures/teams.js
'use strict';
module.exports = {
table: 'teams',
secondary_indexes: [
['last_updated'],
['created']
],
data: [{
id: 'a4d1e02a-54fd-4ee7-81c8-b66ffa4dbdda',
name: '<NAME>',
settings: {},
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: '5063863a-174d-49f4-85e6-14046afe25aa',
name: '<NAME>',
settings: {},
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}]
};
<file_sep>/src/errors.js
module.exports.ValidationError = class ValidationError extends Error {
constructor(message, validation, fileName, lineNumber) {
super(message, fileName, lineNumber);
this.message = message || 'The data is not valid.';
this.validation = validation || {};
this.status = this.statusCode = 400;
}
expose() {
return {
message: this.message,
validation: this.validation
};
}
};
module.exports.NotFoundError = class NotFoundError extends Error {
constructor(message, fileName, lineNumber) {
super(message, fileName, lineNumber);
this.expose = true;
this.message = message || 'The resource does not exist.';
this.status = this.statusCode = 404;
}
};
module.exports.ConflictError = class ConflictError extends Error {
constructor(message, fileName, lineNumber) {
super(message, fileName, lineNumber);
this.expose = true;
this.message = message || 'A duplicate resource already exists.';
this.status = this.statusCode = 409;
}
};
module.exports.AuthenticationError = class AuthenticationError extends Error {
constructor(message, fileName, lineNumber) {
super(message, fileName, lineNumber);
this.expose = true;
this.message = message || 'Authentication failed.';
this.status = this.statusCode = 401;
}
};
module.exports.ForbiddenError = class ForbiddenError extends Error {
constructor(message, fileName, lineNumber) {
super(message, fileName, lineNumber);
this.expose = true;
this.message = message || 'The action is forbidden.';
this.status = this.statusCode = 403;
}
};
module.exports.ServerError = class ServerError extends Error {
constructor(message, fileName, lineNumber) {
super(message, fileName, lineNumber);
this.expose = true;
this.message = message || 'An unknown error has occurred.';
this.status = this.statusCode = 500;
}
};
module.exports.NotImplementedError = class NotImplementedError extends Error {
constructor(message, fileName, lineNumber) {
super(message, fileName, lineNumber);
this.expose = true;
this.message = message || 'The requested functionality is not implemented.';
this.status = this.statusCode = 501;
}
};
<file_sep>/test/tests/endpoints/users.js
'use strict';
var assert = require('chai').assert;
require('../../init.js');
describe.skip('Users', function() {
var ids = [];
describe('#post', function() {
it.skip('should reject an unauthorized request', done => {
done();
});
it('should reject an invalid request', done => {
agent.post('/resources/users')
.send({foo: 'bar'})
.expect(400)
.expect(function(res) {
assert.isObject(res.body);
assert.isObject(res.body.validation);
})
.end(done);
});
it('should create a new user', done => {
agent.post('/resources/users')
.send({name: '<NAME>', type: 'human'})
.expect(201)
.expect(function(res) {
assert.isObject(res.body);
assert.isString(res.body.id);
assert.equal(res.body.name, '<NAME>');
ids.push(res.body.id);
})
.end(done);
});
});
// TODO: clean up users
after(done => {
done();
});
});
<file_sep>/src/strategies/email.js
const jjv = require('jjv');
const jwt = require('jsonwebtoken');
const Handlebars = require('handlebars');
const json = require('../util/json');
const form = require('../util/form');
const nodemailer = require('nodemailer');
const errors = require('../errors');
const { can } = require('../util/protect');
const x = require('../namespace');
const Strategy = require('../Strategy');
const Credential = require('../models/Credential');
const User = require('../models/User');
const env = jjv();
env.addSchema({
id: 'authority',
type: 'object',
properties: {
expiresIn: {
type: 'number',
default: 900
},
authentication_email_subject: {
type: ['null', 'string'],
title: 'Authentication Email Subject',
description: 'Handlebars template used to generate the email subject. Provided `token`, `credential`, and `url`.',
default: 'Authenticate by email'
},
authentication_email_text: {
type: ['null', 'string'],
title: 'Authentication Email Plain Text Body',
description: 'Handlebars template used to generate the email plain text body. Provided `token`, `credential`, and `url`.',
default: 'Please authenticate at the following URL: {{{url}}}'
},
authentication_email_html: {
type: ['null', 'string'],
title: 'Authentication Email HTML Body',
description: 'Handlebars template used to generate the email HTML body. Provided `token`, `credential`, and `url`.',
default: 'Please click <a href="{{url}}">here</a> to authenticate.'
},
verification_email_subject: {
type: ['null', 'string'],
title: 'Verification Email Subject',
description: 'Handlebars template used to generate the email subject. Provided `token`, `credential`, and `url`.',
default: 'Verify email'
},
verification_email_text: {
type: ['null', 'string'],
title: 'Verification Email Plain Text Body',
description: 'Handlebars template used to generate the email plain text body. Provided `token`, `credential`, and `url`.',
default: 'Please verify this email at the following URL: {{{url}}}'
},
verification_email_html: {
type: ['null', 'string'],
title: 'Verification Email HTML Body',
description: 'Handlebars template used to generate the email HTML body. Provided `token`, `credential`, and `url`.',
default: 'Please click <a href="{{url}}">here</a> to verify this email.'
},
mailer: {
type: 'object',
default: {
transport: null,
auth: {},
defaults: {}
},
properties: {
transport: {
type: ['null', 'string'],
default: null
},
auth: {
type: 'object',
default: {}
},
defaults: {
type: 'object',
default: {}
}
}
}
}
});
env.addSchema({
id: 'credential',
type: 'object',
properties: {}
});
module.exports = class EmailStrategy extends Strategy {
async authenticate(ctx) {
ctx.redirect_to = ctx.query.url;
var request = ctx.query;
// HTTP POST (json)
if (ctx.method === 'POST' && ctx.is('application/json'))
request = await json(ctx.req);
// HTTP POST (form)
else if (ctx.method === 'POST' && ctx.is('application/x-www-form-urlencoded'))
request = await form(ctx.req);
// check for token in the request; if we find one then the user has already received an email
// and has clicked the link containing the token
if (request.token) {
let token;
ctx[x].authx.config.session_token.public.some(pub => {
try {
return token = jwt.verify(request.token, pub.key, {
algorithms: [pub.algorithm],
audience: ctx[x].authx.config.realm + ':session.' + this.authority.id,
issuer: ctx[x].authx.config.realm + ':session.' + this.authority.id
});
} catch (err) { return; }
});
if (!token)
throw new errors.AuthenticationError('The supplied token is invalid or expired.');
// credential token
if (token.sub[0] === 'credential') {
// get the credential
const credential = await Credential.get(this.conn, token.sub[1]);
if (ctx[x].user && (ctx[x].user.id !== credential.user_id))
throw new errors.AuthenticationError('This email is associated with a different user.');
if(new Date(credential.last_used) > new Date(token.iat))
throw new errors.AuthenticationError('This credential has been used since the token was issued.');
const [user] = await Promise.all([
// get the user
User.get(this.conn, credential.user_id),
// update the credential's last_used timestamp
credential.update({ last_used: Date.now() / 1000 })
]);
// return the user
return user;
}
// user token
if (token.sub[0] === 'user') {
let user = ctx[x].user;
let tokenUserId = token.sub[1];
let tokenEmail = token.sub[2];
// no user is currently logged-in, so we won't try to associate a new email
if (!user)
throw new errors.AuthenticationError('A new credential cannot be created because no user is currently logged in.');
// verify that the logged-in user matches the intended user
if (user.id !== tokenUserId)
throw new errors.AuthenticationError('A new credential cannot be created because the logged-in user does not match the intended user.');
// verify that the user is permitted to add an email
if (!can(ctx, ctx[x].authx.config.realm + ':credential.' + this.authority.id + '.me' + ':create'))
throw new errors.ForbiddenError(`You are not permitted to create a new ${this.authority.name} credential for yourself.`);
// add a new credential
await Credential.create(this.conn, {
id: [this.authority.id, tokenEmail],
user_id: user.id,
last_used: Date.now(),
profile: null
});
return user;
}
throw new errors.AuthenticationError('The supplied token subject is not supported.');
}
// check for an email address in the request; if we find one then we need to generate a token
// and send the user a link by email
else if (request.email)
try {
let credential = await Credential.get(this.conn, [this.authority.id, request.email]);
// generate token from user
let token = jwt.sign({}, ctx[x].authx.config.session_token.private_key, {
algorithm: ctx[x].authx.config.session_token.algorithm,
expiresIn: this.authority.expiresIn,
audience: ctx[x].authx.config.realm + ':session.' + this.authority.id,
subject: ['credential', credential.id],
issuer: ctx[x].authx.config.realm + ':session.' + this.authority.id
});
let templateContext = {
token: token,
credential: credential,
url: ctx.request.href + (ctx.request.href.includes('?') ? '&' : '?') + 'token=' + token
};
// send the token in an email
await this.mail({
to: request.email,
subject: Handlebars.compile(this.authority.details.authentication_email_subject)(templateContext),
text: Handlebars.compile(this.authority.details.authentication_email_text)(templateContext),
html: Handlebars.compile(this.authority.details.authentication_email_html)(templateContext)
});
ctx.status = 202;
ctx.body = {message: 'Token sent to "' + request.email + '".'};
}
catch (err) {
// this is an unexpected error
if (!(err instanceof errors.NotFoundError))
throw err;
// no user is currently logged-in, so we can't try to associate a new email
if (!ctx[x].user)
throw err;
// the user is not permitted to add an email
if (!can(ctx, ctx[x].authx.config.realm + ':credential.' + this.authority.id + '.me' + ':create'))
throw new errors.ForbiddenError(`You are not permitted to create a new ${this.authority.name} credential for yourself.`);
// generate token from user
let token = jwt.sign({}, ctx[x].authx.config.session_token.private_key, {
algorithm: ctx[x].authx.config.session_token.algorithm,
expiresIn: this.authority.expiresIn,
audience: ctx[x].authx.config.realm + ':session.' + this.authority.id,
subject: ['user', ctx[x].user.id, request.email],
issuer: ctx[x].authx.config.realm + ':session.' + this.authority.id
});
let templateContext = {
token: token,
user: ctx[x].user,
url: ctx.request.href + (ctx.request.href.includes('?') ? '&' : '?') + 'token=' + token
};
// send the token in an email
await this.mail({
to: request.email,
subject: Handlebars.compile(this.authority.details.verification_email_subject)(templateContext),
text: Handlebars.compile(this.authority.details.verification_email_text)(templateContext),
html: Handlebars.compile(this.authority.details.verification_email_html)(templateContext)
});
ctx.status = 202;
ctx.body = {message: 'Token sent to "' + request.email + '".'};
}
// this isn't a valid request
else
throw new errors.ValidationError('You must send an email address or token.');
}
async mail(message) {
const config = this.authority.details.mailer;
// stub out a transporter if none is specified
const transport = config.transport ?
nodemailer.createTransport(config.transport)
: { sendMail: (message, cb) => {
console.warn('Email transport is not set up; message not sent:', message);
cb(null, message);
}};
// wrap nodemailer in a promise
return new Promise( (resolve, reject) => {
message = Object.assign({}, config.defaults, message);
transport.sendMail(message, (err, res) => {
if(err) return reject(err);
return resolve(res);
});
});
}
// Authority Methods
// -----------------
static async createAuthority(conn, data) {
data.details = data.details || {};
// validate data
const err = env.validate('authority', data, {useDefault: true});
if(err) throw new errors.ValidationError('The authority details were invalid.', err.validation);
return Strategy.createAuthority.call(this, conn, data);
}
static async updateAuthority(authority, delta) {
delta.details = delta.details || {};
// validate data
const err = env.validate('authority', delta, {useDefault: true});
if(err) throw new errors.ValidationError('The authority details were invalid.', err.validation);
return Strategy.updateAuthority.call(this, authority, delta);
}
// Credential Methods
// ------------------
async createCredential(data) {
data.details = data.details || {};
// validate data
const err = env.validate('credential', data, {useDefault: true});
if (err) throw new errors.ValidationError('The credential details were invalid.', err.validation);
return Strategy.prototype.createCredential.call(this, data);
}
async updateCredential(credential, delta) {
delta.details = delta.details || {};
// validate data
const err = env.validate('credential', delta, {useDefault: true});
if (err) throw new errors.ValidationError('The credential details were invalid.', err.validation);
return Strategy.prototype.updateCredential.call(this, credential, delta);
}
};
<file_sep>/test/tests/strategies/email.js
'use strict';
const chai = require('chai');
var assert = chai.assert;
require('../../init.js');
describe('Strategy: Email', () => {
var messages = [];
var mail;
// stub out the mail function
before(() => {
mail = authx.strategies.email.prototype.mail;
authx.strategies.email.prototype.mail = m => messages.unshift(m);
});
it('should return 400 for an invalid request', done => {
agent.post('/v1/session/email')
.expect(400)
.end(done);
});
it('should return 404 for nonexistant user', done => {
agent.post('/v1/session/email')
.send({
email: 'this-does-not-exist'
})
.expect(404)
.end(done);
});
it('should return 202 for a valid email', done => {
agent.post('/v1/session/email')
.send({
email: '<EMAIL>'
})
.expect(202)
.end(done);
});
it('should send a token for a valid email', () => {
assert.equal(messages[0].to, '<EMAIL>');
assert.equal(messages[0].subject, 'Reset your password');
assert.match(messages[0].html, /^<a href="http/);
assert.isString(messages[0].text);
});
it('should return 401 for an invalid token', done => {
agent.get('/v1/session/email')
.query({
token: 'foo'
})
.expect(401)
.end(done);
});
it('should return 401 for an invalid token', done => {
agent.get('/v1/session/email')
.query({
token: 'foo'
})
.expect(401)
.end(done);
});
it('should return 200 for a valid token', done => {
agent.get('/v1/session/email')
.query({
token: messages[0].text
})
.expect(200)
.end(done);
});
// replace original mail function
after(() => {
authx.strategies.email.prototype.mail = mail;
});
});
<file_sep>/readme.md
[](https://app.wercker.com/project/bykey/fe30b946cc0ec765b7f89d03ae512793)
This is the TCG auth service. It's named AuthX because it's an "exchange" of sorts, consolidating upstream identities from several authorities into a single identity for downstream clients. AuthX uses the (kinda disgusting) OAuth2 framework in both directions, and adds an *authorization* layer. Authorizations are based on the [simple scopes spec](https://github.com/the-control-group/scopeutils).
Concepts
--------
### User
The user is (obviously) the primary component. It consists of a unique ID and profile information in the format of [Portable Contacts](http://portablecontacts.net/draft-spec.html). Information in the profile is **not** verified, and is not directly used by AuthX system for authentication.
### Authority
An authority is a mechanism for authentication, and provides the configuration for corresponding units of code called *strategies*. Several strategies are included by default:
1. **email** - use an email address to verify a visitor's identity (most people call this "reset your password")
2. **password** - verify your identity with a password (which is protected with bcrypt)
3. **google** - connect to one or more Google and Google Apps accounts
4. **onelogin** - connect to one or more OneLogin accounts through SAML
### Credential
Credentials connect users to authorities. A user can typically have multiple authorities of the same authority (multiple emails, for example).
### Client
Clients are downstream applications that uses AuthX for authentication/authorization.
### Grant
A user gives a client permission to act on her behalf via a grant.
### Role
A role bestows its permissions to every user it includes.
```
╔══════════════════════════════════════════╗
║ ║
║ Upstream Providers ║
║ ║
║ │ ║
║▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓│▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓║
║ ┌────────────┐ ┌─────┴─────┐ ║
║ │ Credential ├─┤ Authority │ ║
║ └───┬────────┘ └───────────┘ ║
║ ┌───┴──┐ Authentication ║
║░░░│ User │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░║
║ └─┬──┬─┘ ┌──────┐ ║
║ │ └────────────────┤ Role │ ║
║ ┌┴──────┐ ┌────────┐ └──────┘ ║
║ │ Grant ├─┤ Client │ ║
║ └───────┘ └───┬────┘ Authorization ║
║▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓│▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓║
║ │ ║
║ ║
║ Downstream Clients ║
║ ║
╚══════════════════════════════════════════╝
```
Anatomy of a scope
------------------
Scopes are composed of 3 domains, separated by the `:` character:
```
AuthX:role.abc:read
|___| |______| |__|
| | |
realm resource action
```
Each domain can contain parts, separated by the `.` character. Domain parts can be `/[a-zA-Z0-9_]*/` strings or glob pattern identifiers `*` or `**`:
```
role.abc
role.*
**
```
AuthX Scopes
------------
AuthX dogfoods. It uses its own authorization system to restrict access to its resources. Below are the scopes used by AuthX internally:
```
AuthX:user:create
AuthX:user:read
AuthX:user:update
AuthX:user:delete
AuthX:me:read
AuthX:me:update
AuthX:me:delete
AuthX:role:create
AuthX:role.<role_id>:read
AuthX:role.<role_id>:update
AuthX:role.<role_id>:update.scopes
AuthX:role.<role_id>:update.assignments
AuthX:role.<role_id>:delete
AuthX:authority:create
AuthX:authority.<authority_id>:read
AuthX:authority.<authority_id>:update
AuthX:authority.<authority_id>:delete
AuthX:credential.<authority_id>.user:create
AuthX:credential.<authority_id>.user:read
AuthX:credential.<authority_id>.user:update
AuthX:credential.<authority_id>.user:delete
AuthX:credential.<authority_id>.me:create
AuthX:credential.<authority_id>.me:read
AuthX:credential.<authority_id>.me:update
AuthX:credential.<authority_id>.me:delete
AuthX:client:create
AuthX:client.<client_id>:read
AuthX:client.<client_id>:update
AuthX:client.<client_id>:update.scopes
AuthX:client.<client_id>:delete
AuthX:grant.<client_id>.user:create
AuthX:grant.<client_id>.user:read
AuthX:grant.<client_id>.user:update
AuthX:grant.<client_id>.user:delete
AuthX:grant.<client_id>.me:create
AuthX:grant.<client_id>.me:read
AuthX:grant.<client_id>.me:update
AuthX:grant.<client_id>.me:delete
```
<file_sep>/src/controllers/users.js
const Promise = require('bluebird');
const r = require('rethinkdb');
const json = require('../util/json');
const {protect, can} = require('../util/protect');
const {parseIncludes, parseRoles} = require('../util/queryParams');
const errors = require('../errors');
const Role = require('../models/Role');
const User = require('../models/User');
const x = require('../namespace');
let includable = ['credentials', 'grants', 'roles', 'scopes', 'team'];
module.exports.post = async function post(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':user:create');
var includes = parseIncludes(includable, ctx);
var data = await json(ctx.req);
var user = await User.create(ctx[x].conn, data);
ctx.body = await include(user, includes, ctx);
ctx.status = 201;
};
module.exports.query = async function query(ctx) {
if (!await can(ctx, ctx[x].authx.config.realm + ':me:read') && !await can(ctx, ctx[x].authx.config.realm + ':user:read'))
throw new errors.ForbiddenError(`You lack permission for the required scope "${ctx[x].authx.config.realm}:user:read".`);
var ids;
// restrict to the current user
if (!await can(ctx, ctx[x].authx.config.realm + ':user:read'))
ids = [ctx[x].user.id];
// restrict to provided roles
else if (ctx.query.role_ids) {
let role_ids = parseRoles(ctx);
// make sure we have permission to access these roles
await Promise.map(role_ids, id => protect(ctx, ctx[x].authx.config.realm + ':role.' + id + ':read'));
// fetch the roles from the database
let roles = await Role.query(ctx[x].conn, x => x.getAll(r.args(role_ids), {index: 'id'}));
// combine assignments
let assignments = {};
roles.forEach(role => {
Object.keys(role.assignments).forEach(a => {
if (role.assignments[a]) assignments[a] = true;
});
});
// get user IDs
ids = Object.keys(assignments);
}
var transformer = x => {
var index;
// restrict to known ids
if (ids) {
x = x.getAll(r.args(ids), {index: 'id'});
index = 'id';
}
// order
if (!index || index === 'created') {
x = x.orderBy({index: 'created'});
index = 'created';
} else
x = x.orderBy('created');
// filter by status
if (ctx.query.status)
if (!index || index === 'status') {
x = x.getAll(ctx.query.status, {index: 'status'});
index = 'status';
} else
x = x.filter({status: ctx.query.status});
// fuzzy search by name
var search = ctx.query.search ? ctx.query.search.toLowerCase() : null;
if (ctx.query.search)
x = x.filter(row => r.or(
row('profile')('displayName').downcase().match(search),
row('profile')('nickname').default('').downcase().match(search),
row('profile')('name')('familyName').default('').downcase().match(search),
row('profile')('name')('givenName').default('').downcase().match(search),
row('profile')('name')('middleName').default('').downcase().match(search)
));
// skip
var skip = parseInt(ctx.query.skip);
if (skip) x = x.skip(skip);
// limit
var limit = parseInt(ctx.query.limit);
if (limit) x = x.limit(limit);
return x;
};
var includes = parseIncludes(includable, ctx);
var users = await User.query(ctx[x].conn, transformer);
ctx.body = await Promise.all(users.map(async u => await include(u, includes, ctx)));
};
module.exports.get = async function get(ctx) {
let user_id = ctx.params.user_id || (ctx[x].user ? ctx[x].user.id : null);
await protect(ctx, ctx[x].authx.config.realm + ':' + (ctx[x].user && ctx[x].user.id === user_id ? 'me' : 'user') + ':read');
var includes = parseIncludes(includable, ctx);
var user = await User.get(ctx[x].conn, user_id);
ctx.body = await include(user, includes, ctx);
};
module.exports.patch = async function patch(ctx) {
let user_id = ctx.params.user_id || (ctx[x].user ? ctx[x].user.id : null);
await protect(ctx, ctx[x].authx.config.realm + ':' + (ctx[x].user && ctx[x].user.id === user_id ? 'me' : 'user') + ':update');
var includes = parseIncludes(includable, ctx);
var data = await json(ctx.req);
var user = await User.update(ctx[x].conn, user_id, data);
ctx.body = await include(user, includes, ctx);
};
module.exports.del = async function del(ctx) {
let user_id = ctx.params.user_id || (ctx[x].user ? ctx[x].user.id : null);
await protect(ctx, ctx[x].authx.config.realm + ':' + (ctx[x].user && ctx[x].user.id === user_id ? 'me' : 'user') + ':delete');
var includes = parseIncludes(includable, ctx);
// make sure to include credentials, which are automatically deleted with the user
includes = includes || [];
if (includes.indexOf('credentials') === -1)
includes.push('credentials');
var user = await User.delete(ctx[x].conn, user_id);
ctx.body = await include(user, includes, ctx);
};
async function include(user, includes, ctx) {
if (!includes || !includes.length)
return user;
// call the included functions in parallel
var results = await Promise.map(includes, async i => {
// get the results
var result = await user[i]();
// filter out unauthorized credentials
if (i === 'credentials')
result = await Promise.filter(result, c => can(ctx, ctx[x].authx.config.realm + ':credential.' + c.authority_id + '.' + (ctx[x].user && ctx[x].user.id === user.id ? 'me' : 'user') + ':read'));
// filter out unauthorized grants
if (i === 'grants')
result = await Promise.filter(result, g => can(ctx, ctx[x].authx.config.realm + ':grant.' + g.client_id + '.' + (ctx[x].user && ctx[x].user.id === user.id ? 'me' : 'user') + ':read'));
// filter out unauthorized roles
if (i === 'roles')
result = await Promise.filter(result, r => can(ctx, ctx[x].authx.config.realm + ':role.' + r.id + ':read'));
return result;
});
// assign the results to a new object
var included = Object.assign(Object.create(User.prototype), user);
results.forEach((v, i) => included[includes[i]] = v);
// return the user with includes
return included;
}
<file_sep>/test/init/1. db.js
'use strict';
var r = require('rethinkdb');
var fs = require('fs');
var async = require('async');
module.exports = {
setup: function(done){
// make a timestamped db
var database = global.setup.config.db.db + Date.now();
delete global.setup.config.db.db;
// connect to rethinkdb
r.connect(global.setup.config.db, function(err, conn) {
if(err) return done(err);
// create database
r.dbCreate(database).run(conn, function(err) {
if(err) return done(err);
// now we can set the default database
global.setup.config.db.db = database;
// load the fixtures
async.map(fs.readdirSync(__dirname + '/../../fixtures/'), function(file, done){
var fixture = require(__dirname + '/../../fixtures/' + file);
// create table
r.db(database).tableCreate(fixture.table).run(conn, function(err) {
if(err) return done(err);
// insert data
r.db(database).table(fixture.table).insert(fixture.data).run(conn, function(err) {
if(err) return done(err);
// no secondary indices to create
if(!fixture.secondary_indexes.length)
return done();
// create secondary indices
async.map(fixture.secondary_indexes, function(index, loop){
var q = r.db(database).table(fixture.table);
q.indexCreate.apply(q, index).run(conn, loop);
}, function(err){
if(err) return done(err);
// wait for indices to finish
r.db(database).table(fixture.table).indexWait().run(conn, done);
});
});
});
}, done);
});
});
},
teardown: function(done){
// destroy test database
r.connect(global.setup.config.db, function(err, conn) {
if(err) return done(err);
r.dbDrop(global.setup.config.db.db).run(conn, function(err) {
if(err) return done(err);
conn.close(done);
});
});
}
};
<file_sep>/src/Model.js
const r = require('rethinkdb');
const _ = require('lodash');
const errors = require('./errors');
const CONN = Symbol('conn');
class Model {
// Static Methods
// --------------
static get table() {
throw new Error('A Model must define a static getter `table`.');
}
static parseRethinkError(message) {
// duplicate key
if(message && message.indexOf('Duplicate primary key') === 0)
return new errors.ConflictError('A record with the same id already exists.');
// other error
return new Error(message);
}
// get a record by its primary ID
static async query(conn, transform) {
if (!transform) transform = (q => q);
var result = await transform(r.table(this.table)).run(conn);
result = await result.toArray();
return result.map( record => new this(conn, record) );
}
// get a record by its primary ID
static async get(conn, id) {
var result = await r.table(this.table).get(id).run(conn);
if(!result)
throw new errors.NotFoundError();
return new this(conn, result);
}
// update a record by its primary ID
static async update(conn, id, data) {
var result = await r.table(this.table).get(id).update(data, {returnChanges: 'always'}).run(conn);
if(result.errors > 0)
throw this.parseRethinkError(result.first_error);
if(!result.replaced && !result.unchanged)
throw new errors.NotFoundError();
return new this(conn, result.changes[0].new_val);
}
// save a record by its primary ID
static async save(conn, id, data) {
var result = await r.table(this.table).get(id).replace(data, {returnChanges: 'always'}).run(conn);
if(result.errors > 0)
throw this.parseRethinkError(result.first_error);
return new this(conn, result.changes[0].new_val);
}
// delete a record by its primary ID
static async delete(conn, id) {
var result = await r.table(this.table).get(id).delete({returnChanges: 'always'}).run(conn);
if(result.errors > 0)
throw this.parseRethinkError(result.first_error);
if(!result.deleted)
throw new errors.NotFoundError();
return new this(conn, result.changes[0].old_val);
}
// create a new record
static async create(conn, data) {
var result = await r.table(this.table).insert(data, {returnChanges: 'always'}).run(conn);
if(result.errors > 0)
throw this.parseRethinkError(result.first_error);
if(!result.inserted)
throw new errors.NotFoundError();
return new this(conn, result.changes[0].new_val);
}
// Constructor
// -----------
constructor(conn, data) {
// assign data
_.assign(this, data);
// assign the connection
this[Model.Symbols.CONN] = conn;
}
// Methods
// -------
// update this model instance
async update(data) {
return await this.constructor.update(this[Model.Symbols.CONN], this.id, data);
}
// delete this model instance{}
async delete() {
return await this.constructor.delete(this[Model.Symbols.CONN], this.id);
}
}
Model.Symbols = {
CONN: CONN
};
module.exports = Model;
<file_sep>/src/controllers/roles.js
const Promise = require('bluebird');
const json = require('../util/json');
const {protect, can} = require('../util/protect');
const Role = require('../models/Role');
const x = require('../namespace');
module.exports.post = async function post(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':role:create');
var data = await json(ctx.req);
ctx.body = await Role.create(ctx[x].conn, data);
ctx.status = 201;
};
module.exports.query = async function query(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':role.*:read', false);
var roles = await Role.query(ctx[x].conn);
ctx.body = await Promise.filter(roles, r => can(ctx, ctx[x].authx.config.realm + ':role.' + r.id + ':read'));
};
module.exports.get = async function get(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':role.' + ctx.params.role_id + ':read');
ctx.body = await Role.get(ctx[x].conn, ctx.params.role_id);
};
module.exports.patch = async function patch(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':role.' + ctx.params.role_id + ':update');
var data = await json(ctx.req);
if (typeof data.assignments !== 'undefined')
await protect(ctx, ctx[x].authx.config.realm + ':role.' + ctx.params.role_id + ':update.assignments');
if (typeof data.scopes !== 'undefined')
await protect(ctx, ctx[x].authx.config.realm + ':role.' + ctx.params.role_id + ':update.scopes');
ctx.body = await Role.update(ctx[x].conn, ctx.params.role_id, data);
};
module.exports.del = async function del(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':role.' + ctx.params.role_id + ':delete');
ctx.body = await Role.delete(ctx[x].conn, ctx.params.role_id);
};
<file_sep>/src/middleware/db.js
const x = require('../namespace');
module.exports = async (ctx, next) => {
ctx[x].conn = await ctx[x].authx.pool.acquire();
try {
await next();
} finally {
if (ctx[x].conn) ctx[x].conn.release();
}
};
<file_sep>/test/init/2. app.js
'use strict';
const Promise = require('bluebird');
const Test = require('supertest/lib/test');
Test.prototype.end = Promise.promisify(Test.prototype.end);
const supertest = require('supertest');
const Koa = require('koa');
const AuthX = require('../../src/index.js');
const { EmailStrategy, GoogleStrategy, PasswordStrategy, SecretStrategy, InContactStrategy } = AuthX;
module.exports = {
setup: function(done){
global.authx = new AuthX(global.setup.config, {
email: EmailStrategy,
google: GoogleStrategy,
password: <PASSWORD>,
secret: SecretStrategy,
incontact: InContactStrategy
});
global.app = (new Koa()).use(global.authx.routes());
global.server = app.listen();
Object.defineProperty(global, 'agent', {
get: () => supertest.agent(global.server)
});
done();
},
teardown: function(done){
done();
}
};
<file_sep>/src/util/pool.js
'use strict';
const gp = require('generic-pool');
const r = require('rethinkdb');
module.exports = class Pool {
constructor (options, max, min, idleTimeoutMillis) {
this.pool = gp.Pool({
name: 'rethinkdb',
create: (callback) => {
return r.connect(options, callback);
},
destroy: (connection) => {
return connection.close();
},
validate: function(connection) {
return connection.isOpen();
},
log: false,
min: min || 2,
max: max || 10,
idleTimeoutMillis: idleTimeoutMillis || 30000
});
}
acquire() {
return new Promise((resolve, reject) => {
return this.pool.acquire((err, conn) => {
if(err) return reject(err);
conn.release = () => {
return this.pool.release(conn);
};
resolve(conn);
});
});
}
};
<file_sep>/server.js
const path = require('path');
const Koa = require('koa');
const send = require('koa-send');
const AuthX = require('./src/index');
const { EmailStrategy, GoogleStrategy, PasswordStrategy, SecretStrategy, InContactStrategy, OneLoginStrategy, SCIMExtension } = AuthX;
const config = require(process.argv[2] || process.env.AUTHX_CONFIG_FILE || './config');
const root = path.join(__dirname, 'public');
// create a Koa app
const app = new Koa();
app.proxy = true;
// create a new instanciate of AuthX
const authx = new AuthX(config, {
email: EmailStrategy,
google: GoogleStrategy,
password: <PASSWORD>,
secret: SecretStrategy,
incontact: InContactStrategy,
onelogin: OneLoginStrategy
});
// create a new instanciate of the SCIM extension
const scim = new SCIMExtension({
authorityId: 'onelogin',
emailAuthorityId: 'email',
passwordAuthorityId: 'password',
});
// apply the SCIM extension
authx.use(scim.routes());
// apply the AuthX routes to the app
app.use(authx.routes());
// serve reference UI
app.use(async (ctx) => {
await send(ctx, (ctx.path || '/').replace(/^(.*)\/$/, '$1/index.html'), { root });
});
// log errors - everything as JSON makes a happier you
app.on('error', (err) => {
if (err.status && err.status < 500)
console.log(JSON.stringify(Object.assign({level: 'info', message: err.message}, err)));
else
console.error(JSON.stringify(Object.assign({level: 'error', message: err.message, stack: err.stack}, err)));
});
// start listening
app.listen(process.env.PORT || 3000);
<file_sep>/fixtures/credentials.js
'use strict';
module.exports = {
table: 'credentials',
secondary_indexes: [
['authority_id', function(row) {
return row('id').nth(0);
}],
['authority_user_id', function(row) {
return row('id').nth(1);
}],
['user_id'],
['last_used'],
['last_updated'],
['created']
],
data: [{
id: ['email', '<EMAIL>'],
user_id: 'a6a0946d-eeb4-45cd-83c6-c7920f2272eb',
details: {
token: null
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['email', '<EMAIL>'],
user_id: '0cbd3783-0424-4f35-be51-b42f07a2a987',
details: {
token: null
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['email', '<EMAIL>'],
user_id: 'd0fc4c64-a3d6-4d97-9341-07de24439bb1',
details: {
token: null
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['email', '<EMAIL>'],
user_id: 'eaa9fa5e-088a-4ae2-a6ab-f120006b20a9',
details: {
token: null
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['email', '<EMAIL>'],
user_id: '306eabbb-cc2b-4f88-be19-4bb6ec98e5c3',
details: {
token: null
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['email', '<EMAIL>'],
user_id: 'dc396449-2c7d-4a23-a159-e6415ded71d2',
details: {
token: null
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['email', '<EMAIL>'],
user_id: '51192909-3664-44d5-be62-c6b45f0b0ee6',
details: {
token: null
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['email', '<EMAIL>'],
user_id: '<PASSWORD>',
details: {
token: null
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['password', '<PASSWORD>'],
user_id: 'a6a0946d-eeb4-45cd-83c6-c7920f2272eb',
details: {
password: <PASSWORD>' // password: <PASSWORD>
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['password', '<PASSWORD>'],
user_id: '0cbd3783-0424-4f35-be51-b42f07a2a987',
details: {
password: <PASSWORD>' // password: <PASSWORD>
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['password', '<PASSWORD>41-07de24439bb1'],
user_id: 'd0fc4c64-a3d6-4d97-9341-07de24439bb1',
details: {
password: <PASSWORD>' // password: <PASSWORD>
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['password', '<PASSWORD>'],
user_id: 'eaa9fa5e-088a-4ae2-a6ab-f120006b20a9',
details: {
password: <PASSWORD>' // password: <PASSWORD>
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['password', '<PASSWORD>'],
user_id: '306eabbb-cc2b-4f88-be19-4bb6ec98e5c3',
details: {
password: <PASSWORD>' // password: <PASSWORD>
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['password', '<PASSWORD>'],
user_id: 'dc396449-2c7d-4a23-a159-e6415ded71d2',
details: {
password: <PASSWORD>' // password: <PASSWORD>
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['password', '<PASSWORD>'],
user_id: '51192909-3664-44d5-be62-c6b45f0b0ee6',
details: {
password: <PASSWORD>' // password: <PASSWORD>
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['password', '<PASSWORD>'],
user_id: '9ad4b34b-781d-44fe-ac39-9b7ac43dde21',
details: {
password: <PASSWORD>' // password: <PASSWORD>
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['secret', '1691f38d-92c8-4d86-9a8<KEY>'],
user_id: '1691f38d-92c8-4d86-9a89-da99528cfcb5',
details: {
secret: <KEY>' // secret: da8ad1c19e0f
},
profile: null,
last_used: null,
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}]
};
<file_sep>/test/tests/models/Credential.js
'use strict';
const r = require('rethinkdb');
const {assert} = require('chai');
const errors = require('../../../src/errors');
const Authority = require('../../../src/models/Authority');
const Credential = require('../../../src/models/Credential');
const User = require('../../../src/models/User');
require('../../init.js');
var conn;
before(async () => {
conn = await r.connect(global.setup.config.db);
});
var ids = [];
describe('Credential', () => {
// Static Methods
// --------------
describe('(static methods)', () => {
describe('query', () => {
it('should return all objects', async () => {
var credentials = await Credential.query(conn);
assert.isArray(credentials);
assert.lengthOf(credentials, 17);
});
it('accepts a query tranformation argument', async () => {
var credentials = await Credential.query(conn, (q) => q.filter({details: {password: <PASSWORD>'}}));
assert.isArray(credentials);
assert.lengthOf(credentials, 1);
});
});
describe('create', () => {
var time;
before(() => time = Date.now() / 1000);
it('should reject an invalid object', async () => {
try {
await Credential.create(conn, {foo: 'bar'});
} catch (err) {
assert.instanceOf(err, errors.ValidationError);
return;
}
throw new Error('Should throw an error.');
});
it('should reject a mismatched profile ID', async () => {
try {
await Credential.create(conn, {id: ['email', '<EMAIL>'], user_id: 'eaa9fa5e-088a-4ae2-a6ab-f120006b20a9', details: {token: '<PASSWORD>'}, profile: {id: 'foo', displayName: 'Dunder Mifflin Support'}});
} catch (err) {
assert.instanceOf(err, errors.ValidationError);
return;
}
throw new Error('Should throw an error.');
});
it('should create a new object without a profile', async () => {
var credential = await Credential.create(conn, {id: ['email', '<EMAIL>'], user_id: 'eaa9fa5e-088a-4ae2-a6ab-f120006b20a9', details: {token: '<PASSWORD>'}});
assert.isArray(credential.id);
assert.equal(credential.id[0], 'email');
assert.equal(credential.id[1], '<EMAIL>');
assert.equal(credential.details.token, 'Created Credential');
// assert.equal(credential.profile.id, credential.id[1]);
assert.isNull(credential.last_used);
assert(credential.created >= time, 'Expected `created` timestamp to be after ' + time);
assert(credential.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
ids.push(credential.id);
});
it('should create a new object with a profile', async () => {
var credential = await Credential.create(conn, {id: ['email', '<EMAIL>'], user_id: 'eaa9fa5e-088a-4ae2-a6ab-f120006b20a9', details: {token: '<PASSWORD>'}, profile: {id: '<EMAIL>', displayName: '<NAME>'}});
assert.isArray(credential.id);
assert.equal(credential.id[0], 'email');
assert.equal(credential.id[1], '<EMAIL>');
assert.equal(credential.details.token, 'Created Credential');
assert.equal(credential.profile.id, credential.id[1]);
assert.isNull(credential.last_used);
assert(credential.created >= time, 'Expected `created` timestamp to be after ' + time);
assert(credential.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
ids.push(credential.id);
});
});
describe('get', () => {
it('should fail to find a nonexistant object', async () => {
try {
await Credential.get(conn, 'i-dont-exist');
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should fetch the correct object', async () => {
var credential = await Credential.get(conn, ['email', '<EMAIL>']);
assert.isArray(credential.id);
assert.equal(credential.id[0], 'email');
assert.equal(credential.id[1], '<EMAIL>');
});
});
describe('save', () => {
var time;
before(() => time = Date.now() / 1000);
it('should reject an invalid object', async () => {
try {
await Credential.save(conn, 'test-static-save', {foo: 'bar'});
} catch (err) {
assert.instanceOf(err, errors.ValidationError);
return;
}
throw new Error('Should throw an error.');
});
it('should save a new object', async () => {
var credential = await Credential.save(conn, ['email', '<EMAIL>'], {id: ['email', '<EMAIL>'], user_id: 'eaa9fa5e-088a-4ae2-a6ab-f120006b20a9', details: {token: '<PASSWORD>'}, profile: {id: '<EMAIL>', displayName: '<NAME>'}});
assert.deepEqual(credential.id, ['email', '<EMAIL>']);
assert.equal(credential.details.token, 'Saved New Credential');
assert(credential.created >= time, 'Expected `created` timestamp to be after ' + time);
assert(credential.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
ids.push(credential.id);
});
it('should save an existing object', async () => {
var credential = await Credential.save(conn, ['email', '<EMAIL>'], {id: ['email', '<EMAIL>'], user_id: 'eaa9fa5e-088a-4ae2-a6ab-f120006b20a9', details: {token: '<PASSWORD>'}, profile: {id: '<EMAIL>', displayName: '<NAME>'}});
assert.deepEqual(credential.id, ['email', '<EMAIL>']);
assert.equal(credential.details.token, 'Saved Existing Credential');
assert(credential.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('update', () => {
var time;
before(() => time = Date.now() / 1000);
it('should fail to find a nonexistant object', async () => {
try {
await Credential.update(conn, 'i-dont-exist', {});
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should update the correct object', async () => {
var credential = await Credential.update(conn, ids[0], {details: {token: 'Updated <PASSWORD>'}});
assert.equal(credential.id[0], ids[0][0]);
assert.equal(credential.id[1], ids[0][1]);
assert.equal(credential.details.token, 'Updated Credential');
assert(credential.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('delete', () => {
var id;
before(() => id = ids.shift() );
it('should fail to find a nonexistant object', async () => {
try {
await Credential.delete(conn, 'i-dont-exist');
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should delete the correct object', async () => {
var credential = await Credential.delete(conn, id);
assert.equal(credential.id[0], id[0]);
assert.equal(credential.id[1], id[1]);
});
it('should fail to find a deleted object', async () => {
try {
await Credential.get(conn, id);
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
});
});
// Instance Methods
// ----------------
describe('(instance methods)', () => {
before(async () => {
var credential = await Credential.create(conn, {id: ['email', '<EMAIL>'], user_id: 'eaa9fa5e-088a-4ae2-a6ab-f120006b20a9', details: {token: 'Created Credential'}});
assert.isArray(credential.id);
ids.push(credential.id);
});
describe('user', () => {
it('should return the associated user', async () => {
var credential = await Credential.get(conn, ['email', '<EMAIL>']);
var user = await credential.user();
assert.instanceOf(user, User);
});
});
describe('authority', () => {
it('should return the associated authority', async () => {
var credential = await Credential.get(conn, ['email', '<EMAIL>']);
var authority = await credential.authority();
assert.instanceOf(authority, Authority);
});
});
describe('update', () => {
var time;
before(() => time = Date.now() / 1000);
it('should update the correct object', async () => {
var credential = await Credential.get(conn, ids[0]);
assert.equal(credential.id[0], ids[0][0]);
assert.equal(credential.id[1], ids[0][1]);
assert.notEqual(credential.name, 'Updated Credential');
credential = await credential.update({details: {token: '<PASSWORD>'}});
assert.equal(credential.id[0], ids[0][0]);
assert.equal(credential.id[1], ids[0][1]);
assert.equal(credential.details.token, 'Updated Credential');
assert(credential.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('delete', () => {
var id;
before(() => id = ids.shift() );
it('should update the correct object', async () => {
var credential = await Credential.get(conn, id);
assert.equal(credential.id[0], id[0]);
assert.equal(credential.id[1], id[1]);
credential = await credential.delete();
assert.equal(credential.id[0], id[0]);
assert.equal(credential.id[1], id[1]);
});
});
});
after(async () => {
await Promise.all(ids.map(id => Credential.delete(conn, id)));
await conn.close();
});
});
<file_sep>/src/models/Credential.js
const r = require('rethinkdb');
const Model = require('../Model');
const validate = require('../util/validator');
const errors = require('../errors');
const USER = Symbol('user');
const AUTHORITY = Symbol('authority');
// this is used to get around limitations of circular dependancies in commonjs
const models = {};
module.exports = class Credential extends Model {
static get table() {
return 'credentials';
}
static async create(conn, data) {
var now = Date.now() / 1000;
data = Object.assign({}, data, {created: now, last_updated: now});
data.profile = data.profile ? Object.assign({}, data.profile) : null;
// normalize the authority_user_id and profile ID
if (data.id && data.id[1] && data.profile && typeof data.profile.id === 'undefined')
data.profile.id = data.id[1];
// validate data
var err = validate('credential', data, {useDefault: true});
if (err) throw new errors.ValidationError('A valid credential must be supplied.', err.validation);
if (data.profile && data.profile.id !== data.id[1]) throw new errors.ValidationError('If a profile ID is present, it must match the `authority_user_id`.');
// update the model (use super.create when babel.js supports it)
return Model.create.call(this, conn, data);
}
static async save(conn, id, data) {
var now = Date.now() / 1000;
data = Object.assign({id: id}, data, {created: now, last_updated: now});
data.profile = data.profile ? Object.assign({}, data.profile) : null;
// normalize the authority_user_id and profile ID
if (data.id && data.id[1] && data.profile && typeof data.profile.id === 'undefined')
data.profile.id = data.id[1];
// validate data
var err = validate('credential', data, {useDefault: true});
if (err) throw new errors.ValidationError('A valid credential must be supplied.', err.validation);
if (data.profile && data.profile.id !== data.id[1]) throw new errors.ValidationError('If a profile ID is present, it must match the `authority_user_id`.');
if (!Array.isArray(data.id) || data.id.some((v,i) => v !== id[i])) throw new Error('The supplied `id` did not match the `id` in the data.');
// don't overwrite an existing `created` timestamp
data.created = r.row('created').default(data.created);
// save the model (use super.create when babel.js supports it)
return Model.save.call(this, conn, id, data);
}
static async update(conn, id, data) {
data = Object.assign({}, data, {last_updated: Date.now() / 1000});
// validate data
var err = validate('credential', data, {checkRequired: false});
if (err) throw new errors.ValidationError('A valid credential must be supplied.', err.validation);
// update the model (use super.update when babel.js supports it)
return Model.update.call(this, conn, id, data);
}
async user(refresh) {
// get the user from the database
if (!this[USER] || refresh)
this[USER] = models.User.get(this[Model.Symbols.CONN], this.user_id);
return this[USER];
}
async authority(refresh) {
// get the user from the database
if (!this[AUTHORITY] || refresh)
this[AUTHORITY] = models.Authority.get(this[Model.Symbols.CONN], this.authority_id);
return this[AUTHORITY];
}
get authority_id() {
return this.id[0];
}
};
models.User = require('./User');
models.Authority = require('./Authority');
<file_sep>/test/tests/models/Authority.js
'use strict';
const r = require('rethinkdb');
const {assert} = require('chai');
const errors = require('../../../src/errors');
const Authority = require('../../../src/models/Authority');
const Credential = require('../../../src/models/Credential');
require('../../init.js');
var conn;
before(async () => {
conn = await r.connect(global.setup.config.db);
});
var ids = [];
describe('Authority', () => {
// Static Methods
// --------------
describe('(static methods)', () => {
describe('query', () => {
it('should return all objects', async () => {
var authoritys = await Authority.query(conn);
assert.isArray(authoritys);
assert.lengthOf(authoritys, 4);
});
it('accepts a query tranformation argument', async () => {
var authoritys = await Authority.query(conn, (q) => q.filter({strategy: 'google'}));
assert.isArray(authoritys);
assert.lengthOf(authoritys, 1);
});
});
describe('create', () => {
var time;
before(() => time = Date.now() / 1000);
it('should reject an invalid object', async () => {
try {
await Authority.create(conn, {foo: 'bar'});
} catch (err) {
assert.instanceOf(err, errors.ValidationError);
return;
}
throw new Error('Should throw an error.');
});
it('should create a new object', async () => {
var authority = await Authority.create(conn, {name: 'Created Authority', strategy: '2factor'});
assert.isString(authority.id);
assert.equal(authority.name, 'Created Authority');
assert(authority.created >= time, 'Expected `created` timestamp to be after ' + time);
assert(authority.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
ids.push(authority.id);
});
});
describe('get', () => {
it('should fail to find a nonexistant object', async () => {
try {
await Authority.get(conn, 'i-dont-exist');
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should fetch the correct object', async () => {
var authority = await Authority.get(conn, 'password');
assert.equal(authority.id, 'password');
});
});
describe('save', () => {
var time;
before(() => time = Date.now() / 1000);
it('should reject an invalid object', async () => {
try {
await Authority.save(conn, 'test-static-save', {foo: 'bar'});
} catch (err) {
assert.instanceOf(err, errors.ValidationError);
return;
}
throw new Error('Should throw an error.');
});
it('should save a new object', async () => {
var authority = await Authority.save(conn, 'test-static-save', {id: 'test-static-save', name: 'Saved New Authority', strategy: '2factor'});
assert.isString(authority.id);
assert.equal(authority.name, 'Saved New Authority');
assert(authority.created >= time, 'Expected `created` timestamp to be after ' + time);
assert(authority.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
ids.push(authority.id);
});
it('should save an existing object', async () => {
var authority = await Authority.update(conn, 'test-static-save', {id: 'test-static-save', name: 'Saved Existing Authority', strategy: '2factor'});
assert.equal(authority.id, 'test-static-save');
assert.equal(authority.name, 'Saved Existing Authority');
assert(authority.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('update', () => {
var time;
before(() => time = Date.now() / 1000);
it('should fail to find a nonexistant object', async () => {
try {
await Authority.update(conn, 'i-dont-exist', {});
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should update the correct object', async () => {
var authority = await Authority.update(conn, ids[0], {name: 'Updated Authority'});
assert.equal(authority.id, ids[0]);
assert.equal(authority.name, 'Updated Authority');
assert(authority.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('delete', () => {
var id;
before(() => id = ids.shift() );
it('should fail to find a nonexistant object', async () => {
try {
await Authority.delete(conn, 'i-dont-exist');
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should delete the correct object', async () => {
var authority = await Authority.delete(conn, id);
assert.equal(authority.id, id);
});
it('should fail to find a deleted object', async () => {
try {
await Authority.get(conn, id);
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
});
});
// Instance Methods
// ----------------
describe('(instance methods)', () => {
before(async () => {
var authority = await Authority.create(conn, {name: 'Created Authority', strategy: '2factor'});
assert.isString(authority.id);
ids.push(authority.id);
});
describe('credentials', () => {
it('should return all assigned credentials', async () => {
var authority = await Authority.get(conn, 'password');
var credentials = await authority.credentials();
assert.isArray(credentials);
assert.lengthOf(credentials, 8);
credentials.forEach(credential => assert.instanceOf(credential, Credential));
});
});
describe('update', () => {
var time;
before(() => time = Date.now() / 1000);
it('should update the correct object', async () => {
var authority = await Authority.get(conn, ids[0]);
assert.equal(authority.id, ids[0]);
assert.notEqual(authority.name, 'Updated Authority');
authority = await authority.update({name: 'Updated Authority'});
assert.equal(authority.id, ids[0]);
assert.equal(authority.name, 'Updated Authority');
assert(authority.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('delete', () => {
var id;
before(() => id = ids.shift() );
it('should update the correct object', async () => {
var authority = await Authority.get(conn, id);
assert.equal(authority.id, id);
authority = await authority.delete();
assert.equal(authority.id, id);
});
});
});
after(async () => {
await Promise.all(ids.map(id => Authority.delete(conn, id)));
await conn.close();
});
});
<file_sep>/src/strategies/google.js
const qs = require('querystring');
const jjv = require('jjv');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const request = require('request-promise');
const errors = require('../errors');
const { can } = require('../util/protect');
const profileSchema = require('../../schema/profile');
const Strategy = require('../Strategy');
const Credential = require('../models/Credential');
const Role = require('../models/Role');
const User = require('../models/User');
const x = require('../namespace');
var env = jjv();
env.addSchema({
id: 'authority',
type: 'object',
properties: {
client_id: {
type: 'string',
title: 'Client ID'
},
client_secret: {
type: 'string',
title: 'Client Secret'
},
email_authority_id: {
type: ['null', 'string'],
title: 'Email Authority ID',
description: 'The ID of an email authority with which verified email addresses can be registered.',
default: null
},
email_domains: {
type: ['null', 'object'],
title: 'Email Domains',
description: 'Restrict creation of new users to these domain names. If null, all domains are allowed.',
additionalProperties: {
type: 'array',
title: 'Domain Role IDs',
description: 'The IDs of AuthX roles to assign any users verified with this domain.',
items: {
type: 'string'
}
},
default: null
},
role_ids: {
type: 'array',
title: 'Role IDs',
description: 'The IDs of AuthX roles to assign any users verified by this authority.',
default: []
}
},
required: [
'client_id',
'client_secret'
]
});
env.addSchema({
id: 'credential',
type: 'object',
properties: {}
});
env.addSchema(profileSchema);
function without(o, key) {
o = Object.assign({}, o);
delete o[key];
return o;
}
module.exports = class OAuth2Strategy extends Strategy {
async authenticate(ctx) {
// Complete Authorization Request
// ------------------------------
if (ctx.query.code) {
// retrieve the url from the cookie
ctx.redirect_to = ctx.cookies.get('AuthX/session/' + this.authority.id + '/url');
ctx.cookies.set('AuthX/session/' + this.authority.id + '/url');
// retreive the state from the cookie
let state = ctx.cookies.get('AuthX/session/' + this.authority.id + '/state');
if (ctx.query.state !== state)
throw new errors.ValidationError('Mismatched state parameter.');
// get an oauth access token & details
let response = JSON.parse(await request({
method: 'POST',
uri: 'https://www.googleapis.com/oauth2/v3/token',
form: {
client_id: this.authority.details.client_id,
client_secret: this.authority.details.client_secret,
redirect_uri: ctx.request.protocol + '://' + ctx.request.host + ctx.request.path,
grant_type: 'authorization_code',
code: ctx.query.code,
state: state
}
}));
// get the user's profile from the Google+ API
let profile = JSON.parse(await request({
method: 'GET',
uri: 'https://www.googleapis.com/plus/v1/people/me',
headers: {
'Authorization': 'Bearer ' + response.access_token
}
}));
// normalize the profile with our schema
if(profile.url && !profile.urls)
profile.urls = [{value: profile.url}];
if(profile.image && profile.image.url && !profile.photos)
profile.photos = [{value: profile.image.url}];
var err = env.validate('profile', profile, {removeAdditional: true});
if (err) throw new errors.ValidationError('The credential details were invalid.', err.validation);
// TODO: right now we aren't verifying any of the JWT's assertions! We need to get Google's public
// keys from https://www.googleapis.com/oauth2/v1/certs (because they change every day or so) and
// use them to check the JWT's signature. What we're doing here isn't exactly best practice, but the
// verification step isn't necessary because we just received the token directly (and securely) from
// Google.
// decode the JWT
let details = jwt.decode(response.id_token);
let credential, user, role_ids = this.authority.details.role_ids;
// check that the email domain is whitelisted
if (this.authority.details.email_domains !== null) {
let parts = details.email.split('@');
let domain = parts[parts.length - 1];
if(!Array.isArray(this.authority.details.email_domains[domain]))
throw new errors.AuthenticationError('The email domain "' + parts[parts.length - 1] + '" is not allowed.');
// add role_ids specific to the email domain
role_ids = role_ids
.concat(this.authority.details.email_domains[domain])
.reduce((reduction, role_id) => {
if (reduction.indexOf(role_id) < 0) reduction.push(role_id);
return reduction;
}, []);
}
// look for an existing credential by ID
try {
credential = await Credential.update(this.conn, [this.authority.id, details.sub], {
details: details,
profile: profile,
last_used: Date.now()
});
// if already logged in, make sure this credential belongs to the logged-in user
if (ctx[x].user && ctx[x].user.id !== credential.user_id)
throw new errors.ConflictError('This Google account is associated with a different user.');
user = await User.get(this.conn, credential.user_id);
} catch (err) { if (!(err instanceof errors.NotFoundError)) throw err; }
// lookup customer by verified email
if (!credential
&& this.authority.details.email_authority_id
&& details.email
&& details.email_verified
) try {
let email_credential = await Credential.get(this.conn, [this.authority.details.email_authority_id, details.email]);
user = await User.get(this.conn, email_credential.user_id);
// if already logged in, make sure this credential belongs to the logged-in user
if (ctx[x].user && ctx[x].user.id !== user.id)
throw new errors.ConflictError('This email address is already associated with a different user.');
// create a new credential
credential = await Credential.create(this.conn, {
id: [this.authority.id, details.sub],
user_id: email_credential.user_id,
last_used: Date.now(),
details: details,
profile: profile
});
// assign the user to all configured roles
let assignments = {}; assignments[user.id] = true;
await Promise.all(role_ids.map(id => Role.update(this.conn, id, {
assignments: assignments
})));
} catch (err) { if (!(err instanceof errors.NotFoundError)) throw err; }
// this account is not yet associated with our system
if (!credential) {
// associate with the logged-in user
if (ctx[x].user) {
// make sure the logged-in user is allowed to add credentials
if (!can(ctx, ctx[x].authx.config.realm + ':credential.' + this.authority.id + '.me' + ':create'))
throw new errors.ForbiddenError(`You are not permitted to create a new ${this.authority.name} credential for yourself.`);
user = ctx[x].user;
}
// create a new user account
else user = await User.create(this.conn, {
type: 'human',
profile: without(profile, 'id')
});
// create a new credential
credential = await Credential.create(this.conn, {
id: [this.authority.id, details.sub],
user_id: user.id,
last_used: Date.now(),
details: details,
profile: profile
});
// create a new email credential
if (this.authority.details.email_authority_id) {
await Credential.create(this.conn, {
id: [this.authority.details.email_authority_id, details.email],
user_id: user.id,
last_used: Date.now(),
profile: null
});
}
// assign the user to all configured roles
let assignments = {}; assignments[user.id] = true;
await Promise.all(role_ids.map(id => Role.update(this.conn, id, {
assignments: assignments
})));
}
return user;
}
// New Authorization Request
// -------------------------
else {
// store the url in a cookie
ctx.cookies.set('AuthX/session/' + this.authority.id + '/url', ctx.query.url);
// store the state in a cookie
let state = crypto.randomBytes(32).toString('base64');
ctx.cookies.set('AuthX/session/' + this.authority.id + '/state', state);
// redirect the user to the authorization provider
ctx.redirect('https://accounts.google.com/o/oauth2/auth?' + qs.stringify({
client_id: this.authority.details.client_id,
redirect_uri: ctx.request.protocol + '://' + ctx.request.host + ctx.request.path,
response_type: 'code',
scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',
state: state
}));
}
}
// Authority Methods
// -----------------
static async createAuthority(conn, data) {
data.details = data.details || {};
// validate data
var err = env.validate('authority', data.details, {useDefault: true});
if(err) throw new errors.ValidationError('The authority details were invalid.', err.validation);
return Strategy.createAuthority.call(this, conn, data);
}
static async updateAuthority(authority, delta) {
delta.details = delta.details || {};
// validate data
var err = env.validate('authority', delta.details, {useDefault: true});
if(err) throw new errors.ValidationError('The authority details were invalid.', err.validation);
return Strategy.updateAuthority.call(this, authority, delta);
}
// Credential Methods
// ------------------
async createCredential(data) {
data.details = data.details || {};
// validate data
var err = env.validate('credential', data.details, {useDefault: true});
if (err) throw new errors.ValidationError('The credential details were invalid.', err.validation);
return Strategy.prototype.createCredential.call(this, data);
}
async updateCredential(credential, delta) {
delta.details = delta.details || {};
// validate data
var err = env.validate('credential', delta.details, {useDefault: true});
if (err) throw new errors.ValidationError('The credential details were invalid.', err.validation);
return Strategy.prototype.updateCredential.call(this, credential, delta);
}
};
<file_sep>/test/tests/models/Role.js
'use strict';
const r = require('rethinkdb');
const {assert} = require('chai');
const errors = require('../../../src/errors');
const Role = require('../../../src/models/Role');
const User = require('../../../src/models/User');
require('../../init.js');
var conn;
before(async () => {
conn = await r.connect(global.setup.config.db);
});
var ids = [];
describe('Role', () => {
// Static Methods
// --------------
describe('(static methods)', () => {
describe('query', () => {
it('should return all objects', async () => {
var roles = await Role.query(conn);
assert.isArray(roles);
assert.lengthOf(roles, 5);
});
it('accepts a query tranformation argument', async () => {
var roles = await Role.query(conn, (q) => q.filter({name: 'Sales Team'}));
assert.isArray(roles);
assert.lengthOf(roles, 1);
});
});
describe('create', () => {
var time;
before(() => time = Date.now() / 1000);
it('should reject an invalid object', async () => {
try {
await Role.create(conn, {foo: 'bar'});
} catch (err) {
assert.instanceOf(err, errors.ValidationError);
return;
}
throw new Error('Should throw an error.');
});
it('should create a new object', async () => {
var role = await Role.create(conn, {name: 'Created Role'});
assert.isString(role.id);
assert.equal(role.name, 'Created Role');
assert(role.created >= time, 'Expected `created` timestamp to be after ' + time);
assert(role.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
ids.push(role.id);
});
});
describe('get', () => {
it('should fail to find a nonexistant object', async () => {
try {
await Role.get(conn, 'i-dont-exist');
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should fetch the correct object', async () => {
var role = await Role.get(conn, '2ec2118e-9c49-474f-9f44-da35c4420ef6');
assert.equal(role.id, '2ec2118e-9c49-474f-9f44-da35c4420ef6');
});
});
describe('update', () => {
var time;
before(() => time = Date.now() / 1000);
it('should fail to find a nonexistant object', async () => {
try {
await Role.update(conn, 'i-dont-exist', {});
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should update the correct object', async () => {
var role = await Role.update(conn, ids[0], {name: 'Updated Role'});
assert.equal(role.id, ids[0]);
assert.equal(role.name, 'Updated Role');
assert(role.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('delete', () => {
var id;
before(() => id = ids.shift() );
it('should fail to find a nonexistant object', async () => {
try {
await Role.delete(conn, 'i-dont-exist');
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should delete the correct object', async () => {
var role = await Role.delete(conn, id);
assert.equal(role.id, id);
});
it('should fail to find a deleted object', async () => {
try {
await Role.get(conn, id);
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
});
});
// Instance Methods
// ----------------
describe('(instance methods)', () => {
before(async () => {
var role = await Role.create(conn, {name: 'Created Role'});
assert.isString(role.id);
ids.push(role.id);
});
describe('users', () => {
it('should return all assigned users', async () => {
var role = await Role.get(conn, '2ec2118e-9c49-474f-9f44-da35c4420ef6');
var users = await role.users();
assert.isArray(users);
assert.lengthOf(users, 3);
});
it('should ignore unassigned users', async () => {
var role = await Role.get(conn, 'root');
var users = await role.users();
assert.isArray(users);
assert.lengthOf(users, 1);
users.forEach(user => assert.instanceOf(user, User));
});
});
describe('can', () => {
it('should calculate user permissions', async () => {
var role = await Role.get(conn, '08e2b39e-ba9f-4de2-8dca-aef460793566');
assert.isTrue(await role.can('AuthX:user:create'));
assert.isTrue(await role.can('AuthX:credential.foo.user:create'));
assert.isTrue(await role.can('AuthX:user:create.other'));
assert.isFalse(await role.can('AuthX:authority.foo:delete'));
assert.isFalse(await role.can('AuthX:grant.foo:update'));
});
});
describe('update', () => {
var time;
before(() => time = Date.now() / 1000);
it('should update the correct object', async () => {
var role = await Role.get(conn, ids[0]);
assert.equal(role.id, ids[0]);
assert.notEqual(role.name, 'Updated Role');
role = await role.update({name: 'Updated Role'});
assert.equal(role.id, ids[0]);
assert.equal(role.name, 'Updated Role');
assert(role.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('delete', () => {
var id;
before(() => id = ids.shift() );
it('should update the correct object', async () => {
var role = await Role.get(conn, id);
assert.equal(role.id, id);
role = await role.delete();
assert.equal(role.id, id);
});
});
});
after(async () => {
await Promise.all(ids.map(id => Role.delete(conn, id)));
await conn.close();
});
});
<file_sep>/src/extensions/scim/index.js
'use strict';
const Router = require('koa-router');
const users = require('./users');
const groups = require('./groups');
const e = require('./namespace');
class SCIMExtension extends Router {
constructor(config) {
super(config);
// set the config
this.config = config;
// Middleware
// ==========
// return a middleware that sets up the namespace
this.middleware = (ctx, next) => {
ctx[e] = this;
return next();
};
// add authx extention namespace context
this.use(this.middleware);
// Groups
// ======
this.post('/Groups', groups.post);
this.get('/Groups', groups.query);
this.get('/Groups/:role_id', groups.get);
this.patch('/Groups/:role_id', groups.patch);
this.put('/Groups/:role_id', groups.put);
this.del('/Groups/:role_id', groups.del);
// Users
// =====
this.post('/Users', users.post);
this.get('/Users', users.query);
this.get('/Users/:user_id', users.get);
this.patch('/Users/:user_id', users.patch);
this.put('/Users/:user_id', users.put);
this.del('/Users/:user_id', users.del);
}
}
module.exports = SCIMExtension;
<file_sep>/src/controllers/session.js
const qs = require('querystring');
const jwt = require('jsonwebtoken');
const errors = require('../errors');
const Authority = require('../models/Authority');
const x = require('../namespace');
module.exports = async (ctx, next) => {
ctx.status = 204;
try {
// get the authority
var authority = await Authority.get(ctx[x].conn, ctx.params.authority_id);
// get the strategy
var Strategy = ctx[x].authx.strategies[authority.strategy];
if (!Strategy)
throw new Error('Strategy "' + authority.strategy + '" not implemented.');
// instantiate the strategy
var strategy = new Strategy(ctx[x].conn, authority);
// pass the request to the strategy
var user = await strategy.authenticate(ctx, next);
if (user) {
// make sure the user is active
if (user.status !== 'active')
throw new errors.ForbiddenError('Your user account has been disabled.');
// generate token from user
let token = jwt.sign({}, ctx[x].authx.config.session_token.private_key, {
algorithm: ctx[x].authx.config.session_token.algorithm,
expiresIn: ctx[x].authx.config.session_token.expiresIn,
audience: ctx[x].authx.config.realm,
subject: user.id,
issuer: ctx[x].authx.config.realm
});
// set the session cookie
ctx.cookies.set('session', token);
ctx.status = 200;
ctx.body = {message: 'You have successfully logged in.'};
}
respond();
} catch (err) {
ctx.app.emit('error', err, ctx);
// set the status
ctx.status = err.status || 500;
// display an error
if(typeof err.expose === 'function')
ctx.body = err.expose();
else
ctx.body = {message: err.expose ? err.message : 'An unknown error has occurred' };
respond();
}
// This allows responses to be returned directly, or forwarded via an HTTP redirect. Because
// the redirect URL can be specified insecurely, it's absolutely required that the response
// body contains NO sensitive information.
function respond() {
if(ctx.redirect_to && (ctx.status < 300 || ctx.status >= 400)) {
let body = ctx.body;
let query = qs.stringify({
status: ctx.status,
body: JSON.stringify(body)
});
ctx.redirect(ctx.redirect_to + (ctx.redirect_to.includes('?') ? '&' : '?') + query);
ctx.body = body;
}
}
};
<file_sep>/fixtures/roles.js
'use strict';
module.exports = {
table: 'roles',
secondary_indexes: [
['assignments', function(row){
return row('assignments').coerceTo('array')
.filter(function(kv) { return kv.nth(1); })
.map(function(kv) { return kv.nth(0); });
}, {multi: true}],
['last_updated'],
['created']
],
data: [{
id: 'root',
name: 'Root',
assignments: {
'a6a0946d-eeb4-45cd-83c6-c7920f2272eb': true,
'dc396449-2c7d-4a23-a159-e6415ded71d2': false
},
scopes: [
'**:**:**'
],
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: 'default',
name: '<NAME>',
assignments: {
'a6a0946d-eeb4-45cd-83c6-c7920f2272eb': true,
'0cbd3783-0424-4f35-be51-b42f07a2a987': true,
'd0fc4c64-a3d6-4d97-9341-07de24439bb1': true,
'eaa9fa5e-088a-4ae2-a6ab-f120006b20a9': true,
'306eabbb-cc2b-4f88-be19-4bb6ec98e5c3': true,
'dc396449-2c7d-4a23-a159-e6415ded71d2': true,
'51192909-3664-44d5-be62-c6b45f0b0ee6': true,
'9ad4b34b-781d-44fe-ac39-9b7ac43dde21': true,
'1691f38d-92c8-4d86-9a89-da99528cfcb5': true
},
scopes: [
'AuthX:me:read',
'AuthX:me:update',
'AuthX:credential.*.me:*',
'AuthX:grant.*.me:*'
],
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: '<PASSWORD>-9c49-<PASSWORD>-9f44-da35c4420ef6',
name: '<NAME>',
assignments: {
'd0fc4c64-a3d6-4d97-9341-07de24439bb1': true,
'0cbd3783-0424-4f35-be51-b42f07a2a987': true,
'eaa9fa5e-088a-4ae2-a6ab-f120006b20a9': true
},
scopes: [
'website:sales:**'
],
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: 'e3e67ba0-626a-4fb6-ad86-6520d4acfaf6',
name: '<NAME>',
assignments: {
'51192909-3664-44d5-be62-c6b45f0b0ee6': true,
'9ad4b34b-781d-44fe-ac39-9b7ac43dde21': true
},
scopes: [
'website:shippments:**'
],
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: '08e2b39e-ba9f-4de2-8dca-aef460793566',
name: 'HR',
assignments: {
'306eabbb-cc2b-4f88-be19-4bb6ec98e5c3': true
},
scopes: [
'AuthX:user:**',
'AuthX:credential.*.user:**'
],
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}]
};
<file_sep>/fixtures/authorities.js
'use strict';
module.exports = {
table: 'authorities',
secondary_indexes: [
['last_updated'],
['created']
],
data: [{
id: 'email',
name: 'Email',
strategy: 'email',
details: {
expiresIn: 3600,
authentication_email_subject: 'Reset your password',
authentication_email_text: '{{{token}}}',
authentication_email_html: '<a href="{{url}}">reset</a>',
verification_email_subject: 'Verify your email',
verification_email_text: '{{{token}}}',
verification_email_html: '<a href="{{url}}">verify</a>',
mailer: {
transport: null,
auth: {},
defaults: {}
}
},
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: 'password',
name: 'Password',
strategy: 'password',
details: {
rounds: 4
},
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: 'secret',
name: 'Secret',
strategy: 'secret',
details: {
rounds: 4
},
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: 'google',
name: 'Google',
strategy: 'google',
details: {
client_id: '210657947312-8s9g76sc7g1goes6tu2h4jmp3t41i8pb.apps.googleusercontent.com',
client_secret: '<KEY>',
email_authority_id: 'email',
email_domains: null,
role_ids: [
'default'
]
},
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}]
};
<file_sep>/src/middleware/bearer.js
const jwt = require('jsonwebtoken');
const errors = require('../errors');
const x = require('../namespace');
let parser = /^Bearer\s+([^\s]+)\s*$/;
module.exports = async (ctx, next) => {
ctx[x].bearer = null;
// parse the authorization header
let parsed = ctx.headers.authorization ? ctx.headers.authorization.match(parser) : null;
// verify the JWT against all public keys
if (parsed && parsed [1] && !ctx[x].authx.config.access_token.public.some(pub => {
try {
return ctx[x].bearer = jwt.verify(parsed[1], pub.key, {
algorithms: [pub.algorithm],
issuer: ctx[x].authx.config.realm
});
} catch (err) { return; }
})) throw new errors.AuthenticationError('The supplied bearer token is invalid.');
return next();
};
<file_sep>/src/extensions/scim/groups.js
'use strict';
const Promise = require('bluebird');
const Filter = require('scim-query-filter-parser');
const json = require('../../util/json');
const { protect, can } = require('../../util/protect');
const errors = require('../../errors');
const Role = require('../../models/Role');
const x = require('../../namespace');
module.exports.post = async function post() {
throw new errors.NotImplementedError();
};
module.exports.query = async function query(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':role.*:read', false);
// parse the filter parameter
var filter;
if (ctx.query.filter) try {
filter = new Filter(ctx.query.filter);
} catch (err) {
throw new errors.ValidationError('Invalid `filter` parameter: ' + err.message);
}
// get all roles
var roles = await Role.query(ctx[x].conn);
// filter out those that are not viewable to this token
roles = await Promise.filter(roles, r => can(ctx, ctx[x].authx.config.realm + ':role.' + r.id + ':read'));
// map to SCIM format
roles = await Promise.all(roles.map(mapAuthXRoleToSCIMGroup));
// apply SCIM filters
if (filter)
roles = roles.filter(filter.test);
// TODO: support SCIM sorting
// support SCIM pagination
const limit = parseInt(ctx.query.count, 10) || 100;
const skip = (parseInt(ctx.query.startIndex) || 1) - 1;
const total = roles.length;
roles = roles.slice(skip, limit);
ctx.body = {
totalResults: total,
itemsPerPage: limit,
startIndex: skip + 1,
schemas: [
'urn:scim:schemas:core:1.0'
],
Resources: roles
};
};
module.exports.get = async function get(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':role.' + ctx.params.role_id + ':read');
const role = await Role.get(ctx[x].conn, ctx.params.role_id);
ctx.body = await mapAuthXRoleToSCIMGroup(role);
};
module.exports.patch = async function patch(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':role.' + ctx.params.role_id + ':update');
var data = await json(ctx.req);
console.log(data);
var assignments = {};
data.members.forEach((patch) => {
assignments[patch.value] = patch.operation === 'add';
});
await Role.update(ctx[x].conn, ctx.params.role_id, {assignments: assignments});
ctx.status = 204;
};
module.exports.put = async function put() {
throw new errors.NotImplementedError();
};
module.exports.del = async function del() {
throw new errors.NotImplementedError();
};
async function mapAuthXRoleToSCIMGroup (role) {
return {
schemas: ['urn:scim:schemas:core:1.0'],
id: role.id,
externalId: null, // TODO: what should we do here?
displayName: role.name,
members: (await role.users()).map((user) => ({
value: user.id,
display: user.profile.displayName
})),
meta: {
created: role.created,
lastModified: role.last_updated
},
};
}
<file_sep>/src/controllers/grants.js
const Promise = require('bluebird');
const json = require('../util/json');
const {protect, can} = require('../util/protect');
const Grant = require('../models/Grant');
const x = require('../namespace');
module.exports.post = async function post(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':grant:create');
var data = await json(ctx.req);
ctx.body = await Grant.create(ctx[x].conn, data);
ctx.status = 201;
};
module.exports.query = async function query(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':grant.*.*:read', false);
var grants = await Grant.query(ctx[x].conn, (await can(ctx, ctx[x].authx.config.realm + ':grant.*.user:read', false)) ? undefined : x => x.getAll(ctx.user.id, {index: 'user_id'}));
ctx.body = await Promise.filter(grants, g => can(ctx, ctx[x].authx.config.realm + ':grant.' + g.client_id + '.' +(ctx.user && ctx.user.id === g.user_id ? 'me' : 'user') + ':read'));
};
module.exports.get = async function get(ctx) {
var grant = await Grant.get(ctx[x].conn, ctx.params.grant_id);
await protect(ctx, ctx[x].authx.config.realm + ':grant.' + grant.client_id + '.' +(ctx.user && ctx.user.id === grant.user_id ? 'me' : 'user') + ':read');
ctx.body = grant;
};
module.exports.patch = async function patch(ctx) {
var data = await json(ctx.req);
var grant = await Grant.get(ctx[x].conn, ctx.params.grant_id);
await protect(ctx, ctx[x].authx.config.realm + ':grant.' + grant.client_id + '.' +(ctx.user && ctx.user.id === grant.user_id ? 'me' : 'user') + ':update');
ctx.body = await grant.update(data);
};
module.exports.del = async function del(ctx) {
var grant = await Grant.get(ctx[x].conn, ctx.params.grant_id);
await protect(ctx, ctx[x].authx.config.realm + ':grant.' + grant.client_id + '.' +(ctx.user && ctx.user.id === grant.user_id ? 'me' : 'user') + ':delete');
ctx.body = await Grant.delete(ctx[x].conn, ctx.params.grant_id);
};
<file_sep>/src/controllers/authorities.js
const Promise = require('bluebird');
const json = require('../util/json');
const { protect, can } = require('../util/protect');
const errors = require('../errors');
const Authority = require('../models/Authority');
const x = require('../namespace');
module.exports.post = async function post(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':authority:create');
var data = await json(ctx.req);
// make sure a strategy is set
if (!data.strategy)
throw new errors.ValidationError('A valid authority must be supplied.', {strategy: {required: true}});
// get the strategy
var Strategy = ctx[x].authx.strategies[data.strategy];
if (!Strategy)
throw new errors.ValidationError('Strategy "' + data.strategy + '" not implemented.', {strategy: {enum: Object.keys(ctx[x].authx.strategies)}});
// create the new authority
ctx.body = await Strategy.createAuthority(ctx[x].conn, data);
ctx.status = 201;
};
module.exports.query = async function query(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':authority.*:read', false);
var authorities = await Authority.query(ctx[x].conn);
ctx.body = await Promise.filter(authorities, a => can(ctx, ctx[x].authx.config.realm + ':authority.' + a.id + ':read'));
};
module.exports.get = async function get(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':authority.' + ctx.params.authority_id + ':read');
ctx.body = await Authority.get(ctx[x].conn, ctx.params.authority_id);
};
module.exports.patch = async function patch(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':authority.' + ctx.params.authority_id + ':update');
var data = await json(ctx.req);
// get the existing authority
var authority = await Authority.get(ctx[x].conn, ctx.params.authority_id);
// make sure the strategy is not changed
if (data.strategy && data.strategy !== authority.strategy)
throw new errors.ValidationError('An authority\'s strategy cannot be changed.');
// get the strategy
var Strategy = ctx[x].authx.strategies[authority.strategy];
if (!Strategy)
throw new Error('Strategy "' + authority.strategy + '" not implemented.');
// update the authority
ctx.body = await Strategy.updateAuthority(authority, data);
};
module.exports.del = async function del(ctx) {
await protect(ctx, ctx[x].authx.config.realm + ':authority.' + ctx.params.authority_id + ':delete');
// get the existing authority
var authority = await Authority.get(ctx[x].conn, ctx.params.authority_id);
// get the strategy
var Strategy = ctx[x].authx.strategies[authority.strategy];
if (!Strategy)
throw new Error('Strategy "' + authority.strategy + '" not implemented.');
// delete the authority
ctx.body = await Strategy.deleteAuthority(authority);
};
<file_sep>/src/util/form.js
const qs = require('querystring');
const parse = require('raw-body');
const errors = require('../errors');
module.exports = async function form(req) {
try {
var data = await parse(req, { encoding: 'utf8' });
return qs.parse(data);
} catch (e) {
throw new errors.ValidationError('The request body was invalid form data.');
}
};
<file_sep>/test/tests/models/Grant.js
'use strict';
const r = require('rethinkdb');
const {assert} = require('chai');
const errors = require('../../../src/errors');
const Client = require('../../../src/models/Client');
const Grant = require('../../../src/models/Grant');
const User = require('../../../src/models/User');
require('../../init.js');
var conn;
before(async () => {
conn = await r.connect(global.setup.config.db);
});
var ids = [];
describe('Grant', () => {
// Static Methods
// --------------
describe('(static methods)', () => {
describe('query', () => {
it('should return all objects', async () => {
var grants = await Grant.query(conn);
assert.isArray(grants);
assert.lengthOf(grants, 2);
});
it('accepts a query tranformation argument', async () => {
var grants = await Grant.query(conn, (q) => q.filter({nonce: 'd122298d-55d9-4eee-9c17-463113669007'}));
assert.isArray(grants);
assert.lengthOf(grants, 1);
});
});
describe('create', () => {
var time;
before(() => time = Date.now() / 1000);
it('should reject an invalid object', async () => {
try {
await Grant.create(conn, {foo: 'bar'});
} catch (err) {
assert.instanceOf(err, errors.ValidationError);
return;
}
throw new Error('Should throw an error.');
});
it('should create a new object', async () => {
var grant = await Grant.create(conn, {id: ['1691f38d-92c8-4d86-9a89-da99528cfcb5', 'dundermifflin-inventory'], scopes: ['a:b:c']});
assert.isArray(grant.id);
assert.deepEqual(grant.scopes, ['a:b:c']);
assert(grant.created >= time, 'Expected `created` timestamp to be after ' + time);
assert(grant.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
ids.push(grant.id);
});
});
describe('get', () => {
it('should fail to find a nonexistant object', async () => {
try {
await Grant.get(conn, 'i-dont-exist');
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should fetch the correct object', async () => {
var grant = await Grant.get(conn, ['a6a0946d-eeb4-45cd-83c6-c7920f2272eb', 'dundermifflin-inventory']);
assert.deepEqual(grant.id, ['a6a0946d-eeb4-45cd-83c6-c7920f2272eb', 'dundermifflin-inventory']);
});
});
describe('update', () => {
var time;
before(() => time = Date.now() / 1000);
it('should fail to find a nonexistant object', async () => {
try {
await Grant.update(conn, 'i-dont-exist', {});
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should update the correct object', async () => {
var grant = await Grant.update(conn, ids[0], {scopes: ['c:b:a']});
assert.deepEqual(grant.id, ids[0]);
assert.deepEqual(grant.scopes, ['c:b:a']);
assert(grant.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('delete', () => {
var id;
before(() => id = ids.shift() );
it('should fail to find a nonexistant object', async () => {
try {
await Grant.delete(conn, 'i-dont-exist');
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should delete the correct object', async () => {
var grant = await Grant.delete(conn, id);
assert.deepEqual(grant.id, id);
});
it('should fail to find a deleted object', async () => {
try {
await Grant.get(conn, id);
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
});
});
// Instance Methods
// ----------------
describe('(instance methods)', () => {
before(async () => {
var grant = await Grant.create(conn, {id: ['306eabbb-cc2b-4f88-be19-4bb6ec98e5c3', 'dundermifflin-inventory'], scopes: ['a:b:c']});
assert.isArray(grant.id);
ids.push(grant.id);
});
describe('user', () => {
it('should return the associated user', async () => {
var grant = await Grant.get(conn, ids[0]);
var user = await grant.user();
assert.instanceOf(user, User);
});
});
describe('client', () => {
it('should return the associated user', async () => {
var grant = await Grant.get(conn, ids[0]);
var client = await grant.client();
assert.instanceOf(client, Client);
});
});
describe('update', () => {
var time;
before(() => time = Date.now() / 1000);
it('should update the correct object', async () => {
var grant = await Grant.get(conn, ids[0]);
assert.deepEqual(grant.id, ids[0]);
assert.notDeepEqual(grant.scopes, ['c:b:a']);
grant = await grant.update({scopes: ['c:b:a']});
assert.deepEqual(grant.id, ids[0]);
assert.deepEqual(grant.scopes, ['c:b:a']);
assert(grant.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('delete', () => {
var id;
before(() => id = ids.shift() );
it('should update the correct object', async () => {
var grant = await Grant.get(conn, id);
assert.deepEqual(grant.id, id);
grant = await grant.delete();
assert.deepEqual(grant.id, id);
});
});
});
after(async () => {
await Promise.all(ids.map(id => Grant.delete(conn, id)));
await conn.close();
});
});
<file_sep>/test/tests/models/Client.js
'use strict';
const r = require('rethinkdb');
const {assert} = require('chai');
const errors = require('../../../src/errors');
const Client = require('../../../src/models/Client');
require('../../init.js');
var conn;
before(async () => {
conn = await r.connect(global.setup.config.db);
});
var ids = [];
describe('Client', () => {
// Static Methods
// --------------
describe('(static methods)', () => {
describe('query', () => {
it('should return all objects', async () => {
var clients = await Client.query(conn);
assert.isArray(clients);
assert.lengthOf(clients, 2);
});
it('accepts a query tranformation argument', async () => {
var clients = await Client.query(conn, (q) => q.filter({name: 'Dunder Mifflin Inventory Portal'}));
assert.isArray(clients);
assert.lengthOf(clients, 1);
});
});
describe('create', () => {
var time;
before(() => time = Date.now() / 1000);
it('should reject an invalid object', async () => {
try {
await Client.create(conn, {foo: 'bar'});
} catch (err) {
assert.instanceOf(err, errors.ValidationError);
return;
}
throw new Error('Should throw an error.');
});
it('should create a new object', async () => {
var client = await Client.create(conn, {name: 'Created Client', secret: '<KEY>'});
assert.isString(client.id);
assert.equal(client.name, 'Created Client');
assert(client.created >= time, 'Expected `created` timestamp to be after ' + time);
assert(client.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
ids.push(client.id);
});
});
describe('get', () => {
it('should fail to find a nonexistant object', async () => {
try {
await Client.get(conn, 'i-dont-exist');
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should fetch the correct object', async () => {
var client = await Client.get(conn, 'dundermifflin-inventory');
assert.equal(client.id, 'dundermifflin-inventory');
});
});
describe('save', () => {
var time;
before(() => time = Date.now() / 1000);
it('should reject an invalid object', async () => {
try {
await Client.save(conn, 'test-static-save', {foo: 'bar'});
} catch (err) {
assert.instanceOf(err, errors.ValidationError);
return;
}
throw new Error('Should throw an error.');
});
it('should save a new object', async () => {
var client = await Client.save(conn, 'test-static-save', {id: 'test-static-save', name: 'Saved New Client', secret: 'd240e3049355259b49b902e2d7559c572add7b6264378cddd231ad9ca3004500'});
assert.isString(client.id);
assert.equal(client.name, 'Saved New Client');
assert(client.created >= time, 'Expected `created` timestamp to be after ' + time);
assert(client.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
ids.push(client.id);
});
it('should save an existing object', async () => {
var client = await Client.save(conn, 'test-static-save', {id: 'test-static-save', name: 'Saved Existing Client', secret: '3eb7de2d16504aa4fcf19bc71082d6711ea2266316b16d9e5582b6a170430c0e'});
assert.equal(client.id, 'test-static-save');
assert.equal(client.name, 'Saved Existing Client');
assert(client.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('update', () => {
var time;
before(() => time = Date.now() / 1000);
it('should fail to find a nonexistant object', async () => {
try {
await Client.update(conn, 'i-dont-exist', {});
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should update the correct object', async () => {
var client = await Client.update(conn, ids[0], {name: 'Updated Client'});
assert.equal(client.id, ids[0]);
assert.equal(client.name, 'Updated Client');
assert(client.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('delete', () => {
var id;
before(() => id = ids.shift() );
it('should fail to find a nonexistant object', async () => {
try {
await Client.delete(conn, 'i-dont-exist');
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
it('should delete the correct object', async () => {
var client = await Client.delete(conn, id);
assert.equal(client.id, id);
});
it('should fail to find a deleted object', async () => {
try {
await Client.get(conn, id);
} catch (err) {
assert.instanceOf(err, errors.NotFoundError);
return;
}
throw new Error('Should throw an error.');
});
});
});
// Instance Methods
// ----------------
describe('(instance methods)', () => {
before(async () => {
var client = await Client.create(conn, {name: 'Created Client', secret: '<KEY>'});
assert.isString(client.id);
ids.push(client.id);
});
describe('update', () => {
var time;
before(() => time = Date.now() / 1000);
it('should update the correct object', async () => {
var client = await Client.get(conn, ids[0]);
assert.equal(client.id, ids[0]);
assert.notEqual(client.name, 'Updated Client');
client = await client.update({name: 'Updated Client'});
assert.equal(client.id, ids[0]);
assert.equal(client.name, 'Updated Client');
assert(client.last_updated >= time, 'Expected `last_updated` timestamp to be after ' + time);
});
});
describe('delete', () => {
var id;
before(() => id = ids.shift() );
it('should update the correct object', async () => {
var client = await Client.get(conn, id);
assert.equal(client.id, id);
client = await client.delete();
assert.equal(client.id, id);
});
});
});
after(async () => {
await Promise.all(ids.map(id => Client.delete(conn, id)));
await conn.close();
});
});
<file_sep>/src/index.js
const errors = require('./errors');
const scopes = require('scopeutils');
const Router = require('koa-router');
const { can } = require('./util/protect');
const Pool = require('./util/pool');
exports = {};
const x = require('./namespace');
Object.assign(exports, { namespace: x });
// strategies
const EmailStrategy = require('./strategies/email');
const GoogleStrategy = require('./strategies/google');
const PasswordStrategy = require('./strategies/password');
const SecretStrategy = require('./strategies/secret');
const InContactStrategy = require('./strategies/incontact');
const OneLoginStrategy = require('./strategies/onelogin');
Object.assign(exports, { EmailStrategy, GoogleStrategy, PasswordStrategy, SecretStrategy, InContactStrategy, OneLoginStrategy });
// extensions
const SCIMExtension = require('./extensions/scim');
Object.assign(exports, { SCIMExtension });
// models
const Authority = require('./models/Authority');
const Client = require('./models/Client');
const Credential = require('./models/Credential');
const Grant = require('./models/Grant');
const Role = require('./models/Role');
const User = require('./models/User');
Object.assign(exports, { Authority, Client, Credential, Grant, Role, User });
// middleware
const bearerMiddleware = require('./middleware/bearer');
const corsMiddleware = require('./middleware/cors');
const dbMiddleware = require('./middleware/db');
const errorMiddleware = require('./middleware/error');
const userMiddleware = require('./middleware/user');
Object.assign(exports, { bearerMiddleware, corsMiddleware, dbMiddleware, errorMiddleware, userMiddleware });
// controllers
const authorityController = require('./controllers/authorities');
const clientController = require('./controllers/clients');
const credentialController = require('./controllers/credentials');
const grantController = require('./controllers/grants');
const roleController = require('./controllers/roles');
const userController = require('./controllers/users');
const sessionController = require('./controllers/session');
const tokensController = require('./controllers/tokens');
class AuthX extends Router {
constructor(config, strategies) {
super(config);
// set the config
this.config = config;
// create a database pool
this.pool = new Pool(config.db, config.db.pool.max, config.db.pool.min, config.db.pool.timeout);
// attach the strategies
this.strategies = strategies;
// Middleware
// ----------
// return a middleware that sets up the namespace
this.middleware = (ctx, next) => {
ctx[x] = { authx: this };
return next();
};
// add authx namespace context
this.use(this.middleware);
// error handling
this.use(errorMiddleware);
// get a database connection
this.use(dbMiddleware);
// add CORS header if necessary
this.use(corsMiddleware);
// get the current bearer token
this.use(bearerMiddleware);
// get the current user
this.use(userMiddleware);
// Session
// =======
// These endpoints manage the user's active session, including logging in,
// logging out, and associating credentials.
this.get('/session/:authority_id', sessionController);
this.post('/session/:authority_id', sessionController);
this.del('/session', async (ctx) => {
ctx.cookies.set('session');
ctx.status = 204;
});
// Tokens
// ======
// These endpoints are used by clients wishing to authenticate/authorize
// a user with AuthX. They implement the OAuth 2.0 flow for "authorization
// code" grant types.
this.get('/tokens', tokensController);
this.post('/tokens', tokensController);
// Can
// ===
// This is a convenience endpoint for clients. It validates credentials and
// asserts that the token can access to the provided scope.
this.get('/can/:scope', async (ctx) => {
if (!ctx.params.scope || !scopes.validate(ctx.params.scope))
throw new errors.ValidationError();
if (!ctx.user)
throw new errors.AuthenticationError();
if (!await can(ctx, ctx.params.scope, ctx.query.strict !== 'false'))
throw new errors.ForbiddenError();
ctx.status = 204;
});
// Keys
// ====
// This outputs valid public keys and algorithms that can be used to verify
// access tokens by resource servers. The first key is always the most recent.
this.get('/keys', async (ctx) => {
ctx.body = this.config.access_token.public;
});
// Resources
// =========
// Authorities
// -----------
this.post('/authorities', authorityController.post);
this.get('/authorities', authorityController.query);
this.get('/authorities/:authority_id', authorityController.get);
this.patch('/authorities/:authority_id', authorityController.patch);
this.del('/authorities/:authority_id', authorityController.del);
// Clients
// -------
this.post('/clients', clientController.post);
this.get('/clients', clientController.query);
this.get('/clients/:client_id', clientController.get);
this.patch('/clients/:client_id', clientController.patch);
this.del('/clients/:client_id', clientController.del);
// Credentials
// ------------
this.post('/credentials', credentialController.post);
this.get('/credentials', credentialController.query);
this.get('/credentials/:credential_id_0/:credential_id_1', credentialController.get);
this.patch('/credentials/:credential_id_0/:credential_id_1', credentialController.patch);
this.del('/credentials/:credential_id_0/:credential_id_1', credentialController.del);
// Grants
// ------
this.post('/grants', grantController.post);
this.get('/grants', grantController.query);
this.get('/grants/:module_id', grantController.get);
this.patch('/grants/:module_id', grantController.patch);
this.del('/grants/:module_id', grantController.del);
// Roles
// -----
this.post('/roles', roleController.post);
this.get('/roles', roleController.query);
this.get('/roles/:role_id', roleController.get);
this.patch('/roles/:role_id', roleController.patch);
this.del('/roles/:role_id', roleController.del);
// Users
// -----
this.post('/users', userController.post);
this.get('/users', userController.query);
this.get('/users/:user_id', userController.get);
this.patch('/users/:user_id', userController.patch);
this.del('/users/:user_id', userController.del);
this.get('/me', userController.get);
this.patch('/me', userController.patch);
this.del('/me', userController.del);
}
}
AuthX.namespace = x;
module.exports = Object.assign(AuthX, exports);
<file_sep>/test/tests/strategies/secret.js
'use strict';
const chai = require('chai');
const url = require('url');
var assert = chai.assert;
require('../../init.js');
describe('Strategy: Password', () => {
it('should return 404 for nonexistant user', done => {
agent.post('/v1/session/secret')
.send({
user_id: 'this-does-not-exist',
secret: 'da8ad1c19e0f'
})
.expect(404)
.end(done);
});
it('should return 401 for an incorrect secret', done => {
agent.post('/v1/session/secret')
.send({
user_id: '1691f38d-92c8-4d86-9a89-da99528cfcb5',
secret: 'wrong'
})
.expect(401)
.end(done);
});
it('should return 200 upon successful login', done => {
agent.post('/v1/session/secret')
.send({
user_id: '1691f38d-92c8-4d86-9a89-da99528cfcb5',
secret: 'da8ad1c19e0f'
})
.expect(200)
.expect(res => {
assert.isString(res.body.access_token)
})
.end(done);
});
it('should accept a form-encoded body', done => {
agent.post('/v1/session/secret')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('secret=da8ad1c19e0f&user_id=1691f38d-92c8-4d86-9a89-da99528cfcb5')
.expect(200)
.end(done);
});
it('should accept HTTP basic credentials', done => {
agent.get('/v1/session/secret')
.set('Authorization', 'Basic MTY5MWYzOGQtOTJjOC00ZDg2LTlhODktZGE5OTUyOGNmY2I1OmRhOGFkMWMxOWUwZg==')
.expect(200)
.end(done);
});
});
<file_sep>/fixtures/grants.js
'use strict';
module.exports = {
table: 'grants',
secondary_indexes: [
['user_id', function(row) {
return row('id').nth(0);
}],
['client_id', function(row) {
return row('id').nth(1);
}],
['last_updated'],
['created']
],
data: [{
id: ['a6a0946d-eeb4-45cd-83c6-c7920f2272eb', 'dundermifflin-inventory'],
nonce: null,
scopes: [
'**:**:**'
],
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: ['51192909-3664-44d5-be62-c6b45f0b0ee6', 'dundermifflin-inventory'],
nonce: 'd122298d-55d9-4eee-9c17-463113669007',
scopes: [
'**:**:**'
],
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}]
};
<file_sep>/test/tests/endpoints/clients.js
'use strict';
var assert = require('chai').assert;
require('../../init.js');
describe('Clients', function() {
});
<file_sep>/src/extensions/scim/namespace.js
module.exports = Symbol('AuthX SCIM Extension');<file_sep>/fixtures/clients.js
'use strict';
module.exports = {
table: 'clients',
secondary_indexes: [
['base_urls', {multi: true}],
['last_updated'],
['created']
],
data: [{
id: 'AuthX',
name: '<NAME>',
secret: '<KEY>',
scopes: [
'**:**:**'
],
base_urls: [],
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}, {
id: 'dundermifflin-inventory',
name: '<NAME> Inventory Portal',
secret: '1f1bb71ebe4341418dbeab6e8e693ec27336425fb2c021219305593ad12043a2',
scopes: [],
base_urls: [
'https://www.dundermifflin.com',
'https://admin.dundermifflin.com'
],
last_updated: Date.now() / 1000,
created: Date.now() / 1000
}]
};
<file_sep>/test/tests/fixtures.js
'use strict';
const jjv = require('jjv');
var env = jjv();
const profile = require('../../schema/profile');
env.addSchema(profile);
const authority = require('../../schema/authority');
const authorities = require('../../fixtures/authorities');
env.addSchema(authority);
const client = require('../../schema/client');
const clients = require('../../fixtures/clients');
env.addSchema(client);
const credential = require('../../schema/credential');
const credentials = require('../../fixtures/credentials');
env.addSchema(credential);
const grant = require('../../schema/grant');
const grants = require('../../fixtures/grants');
env.addSchema(grant);
const role = require('../../schema/role');
const roles = require('../../fixtures/roles');
env.addSchema(role);
const user = require('../../schema/user');
const users = require('../../fixtures/users');
env.addSchema(user);
describe('Fixtures', () => {
it('(authorities) should env.validate', () => {
authorities.data.forEach(f => {
var err = env.validate('authority', f);
if (!err) return;
throw new Error(f.id + ' ' + JSON.stringify(err.validation, null, '\t'));
});
});
it('(clients) should env.validate', () => {
clients.data.forEach(f => {
var err = env.validate('client', f);
if (!err) return;
throw new Error(f.id + ' ' + JSON.stringify(err.validation, null, '\t'));
});
});
it('(credentials) should env.validate', () => {
credentials.data.forEach(f => {
var err = env.validate('credential', f);
if (!err) return;
throw new Error(f.id + ' ' + JSON.stringify(err.validation, null, '\t'));
});
});
it('(grants) should env.validate', () => {
grants.data.forEach(f => {
var err = env.validate('grant', f);
if (!err) return;
throw new Error(f.id + ' ' + JSON.stringify(err.validation, null, '\t'));
});
});
it('(roles) should env.validate', () => {
roles.data.forEach(f => {
var err = env.validate('role', f);
if (!err) return;
throw new Error(f.id + ' ' + JSON.stringify(err.validation, null, '\t'));
});
});
it('(users) should env.validate', () => {
users.data.forEach(f => {
var err = env.validate('user', f);
if (!err) return;
throw new Error(f.id + ' ' + JSON.stringify(err.validation, null, '\t'));
});
});
});
<file_sep>/src/util/bcrypt.js
const bcrypt = require('bcrypt');
module.exports.genSalt = async (a) => {
return new Promise((resolve, reject) => {
return bcrypt.genSalt(a, (err, res) => {
if(err) return reject(err);
return resolve(res);
});
});
};
module.exports.hash = async (plain, rounds) => {
return new Promise((resolve, reject) => {
return bcrypt.hash(plain, rounds, (err, res) => {
if(err) return reject(err);
return resolve(res);
});
});
};
module.exports.compare = async (a, b) => {
return new Promise((resolve, reject) => {
return bcrypt.compare(a, b, (err, res) => {
if(err) return reject(err);
return resolve(res);
});
});
};
<file_sep>/src/models/Role.js
const r = require('rethinkdb');
const Model = require('../Model');
const validate = require('../util/validator');
const scopes = require('scopeutils');
const errors = require('../errors');
const USERS = Symbol('users');
// this is used to get around limitations of circular dependancies in commonjs
const models = {};
module.exports = class Role extends Model {
static get table() {
return 'roles';
}
static async create(conn, data) {
var now = Date.now() / 1000;
data = Object.assign({}, data, {created: now, last_updated: now});
// validate data
var err = validate('role', data, {useDefault: true});
if (err) throw new errors.ValidationError('A valid role must be supplied.', err.validation);
// update the model (use super.create when babel.js supports it)
return Model.create.call(this, conn, data);
}
static async save(conn, id, data) {
var now = Date.now() / 1000;
data = Object.assign({id: id}, data, {created: now, last_updated: now});
// validate data
var err = validate('role', data, {useDefault: true});
if (err) throw new errors.ValidationError('A valid role must be supplied.', err.validation);
if (data.id !== id) throw new Error('The supplied `id` did not match the `id` in the data.');
// don't overwrite an existing `created` timestamp
data.created = r.row('created').default(data.created);
// save the model (use super.create when babel.js supports it)
return Model.save.call(this, conn, id, data);
}
static async update(conn, id, data) {
data = Object.assign({}, data, {last_updated: Date.now() / 1000});
// validate data
var err = validate('role', data, {checkRequired: false});
if (err) throw new errors.ValidationError('A valid role must be supplied.', err.validation);
// update the model (use super.update when babel.js supports it)
return Model.update.call(this, conn, id, data);
}
async users(refresh) {
// query the database for users
if (!this[USERS] || refresh) {
let assignments = Object.keys(this.assignments).filter(k => this.assignments[k]);
this[USERS] = models.User.query(this[Model.Symbols.CONN], q => q.getAll(r.args(assignments)));
}
return this[USERS];
}
can(scope, strict) {
return scopes.can(this.scopes, scope, strict);
}
};
models.User = require('./User');
| bf387f877b9874c35d05e23dd9d3a608d8c8b7e6 | [
"JavaScript",
"Markdown"
]
| 44 | JavaScript | SokratisVidros/authx | 0d37099c0622dcada1eb895662c0f4fe0b6a0a7e | aa36a7355cc546795b49ffae7fc88574bde2a92a |
refs/heads/main | <file_sep>This is our programing team.
The world Top 10 Programing also details and info and my programming budget are flow<file_sep>import React from 'react';
import './Header.css'
const Header = () => {
return (
<div className="container bg-primary text-white">
<h1>OUR PROGRAMMER TEAM</h1>
<h3>TOP 10 RICHEST SOFTWARE PROGRAMMERS</h3>
<h1>Total Budget in My Project:1000 Million </h1>
</div>
);
};
export default Header;<file_sep>
const array=[1,2,3,4,5,6]
let total=0;
for(let i=0;i<array.length;i++){
const elem= array[i]
total=total+elem
}
console.log(total);<file_sep>import React, { useEffect, useState } from "react";
import Cart from "../Cart/Cart";
import Person from "../Person/Person";
const Shop = () => {
const [persons, setPersons] = useState([]);
const [ cart , setCart ] = useState([]);
const handleAddProduct=(persons)=>{
const newCart=[ ...cart , persons ]
setCart(newCart)
}
useEffect(() => {
fetch("/data.json")
.then((res) => res.json())
.then((data) => setPersons(data));
}, []);
return (
<div className="row">
<div className="col-md-9">
<div className="row">
{
persons.map(person=>
<Person
key={person.key}
person={person}
handleAddProduct={handleAddProduct}
>
</Person>)
}
</div>
</div>
<div className="col-md-3">
<Cart
cart={cart}
>
</Cart>
</div>
</div>
);
};
export default Shop;
<file_sep>import React from 'react';
import './Person.css'
const Person = (props) => {
const {Name,img,Occupation,Nationality,Born,Salery }=props.person || {}
return (
<div className="col-md-6 col-lg-6 col-12 person">
<div class="person-photo">
<img src={img} className="image img-fluid mx-auto" alt="..."/>
</div>
<h4>Name:<small>{Name}</small></h4>
<h4>Occupation:{Occupation}</h4>
<h4>Nationality:{Nationality}</h4>
<h4>Born:{Born}</h4>
<h4>Salery:{Salery}</h4>
<button
onClick={ ()=> props.handleAddProduct(props.person)}
className="btn btn-primary mx-auto p-8 button" > <i class="fas fa-shopping-cart"></i>
Add to Cart</button>
</div>
);
};
export default Person;<file_sep>import React, { useEffect, useState } from "react";
import Cart from "../Cart/Cart";
import Product from "../Product/Product";
const Shop = () => {
const [products, setProducts] = useState([]);
// cart e product rakhar jnne state
const [ cart , setCart ] = useState([]);
// jekhanei state shekanei event handler declare korbo
const handleAddProduct=(product)=>{
const newCart=[ ...cart , product ]
setCart(newCart)
}
useEffect(() => {
fetch()
.then((res) => res.json())
.then((data) => setProducts(data));
}, []);
return (
<div>
<div className="row">
<div className="col-md-9">
{/* productsgulu load korbo */}
<div className="row">
{
products.map(product=>
<Product
product={product}
handleAddProduct={handleAddProduct}
>
</Product>)
}
</div>
</div>
<div className="col-md-3">
{/* ekhane amra cart calculation korbo */}
<Cart
cart={cart}
>
</Cart>
</div>
</div>
</div>
);
};
export default Shop;
<file_sep>import React from 'react';
const Product = (props) => {
const {name , img ,category,price,stock}=props.product || {}
return (
<div className="col-md-6">
<div class="card mb-3" style={ {"max-width": "540px"}}>
<div class="row g-0">
<div class="col-md-5">
<img src={img} class="img-fluid rounded-start" alt="..."/>
</div>
<div class="col-md-7">
<div class="card-body">
<h5 class="card-title"><small>{name}</small></h5>
<p class="card-text">
<small>$ {price}</small>
</p>
<p class="card-text">
<small> {stock} left</small>
</p>
<button
onClick={ ()=> props.handleAddProduct(props.product)}
className="btn btn-primary">
Add Product</button>
</div>
</div>
</div>
</div>
</div>
);
};
export default Product; | ce0d527032cd8deadc6a887e243c4191c49b81b4 | [
"Markdown",
"JavaScript"
]
| 7 | Markdown | MD-ABUSUFIAN/programmer-team-project | 6db8ff9a959e1af81fb080ee2bc7c0b19f8d7253 | 589a1515bd206ad2b8858e6c9ac54292efea29e3 |
refs/heads/master | <repo_name>abc549825/jdk7features<file_sep>/README.md
# jdk7features
## 简单介绍JDK7新特性
<file_sep>/src/test/java/ForkJoinTest.java
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.*;
import static org.junit.Assert.assertTrue;
/**
* Created by abc54_000 on 2015/3/17.
*/
public class ForkJoinTest {
@Test
public void testSort() throws Exception {
Random rand = new Random();
long[] array = new long[16];
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextLong() % 100;
}
System.out.println("Initial Array: " + Arrays.toString(array));
ForkJoinTask sort = new SortTask(array);
ForkJoinPool fjpool = new ForkJoinPool();
fjpool.submit(sort);
fjpool.shutdown();
fjpool.awaitTermination(30, TimeUnit.SECONDS);
assertTrue(checkSorted(array));
}
boolean checkSorted(long[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > (a[i + 1])) {
return false;
}
}
return true;
}
@Test
public void testFactorial() throws InterruptedException, ExecutionException {
ForkJoinTask<Long> fjt = new Factorial(1, 10);
ForkJoinPool fjpool = new ForkJoinPool();
Future<Long> result = fjpool.submit(fjt);
// do something
System.out.println(result.get());
}
@Test
public void testException(){
ForkJoinTask<Long> fjt = new Factorial(1, 100);
ForkJoinPool fjpool = new ForkJoinPool();
Future<Long> result = fjpool.submit(fjt);
// do something
try {
System.out.println(result.get());
} catch (InterruptedException|ExecutionException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/Factorial.java
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
/**
* Created by abc54_000 on 2015/3/17.
*/
public class Factorial extends RecursiveTask<Long> {
final int start;
final int end;
final int THRESHOLD = 3;
Factorial(int start, int end) {
this.start = start;
this.end = end;
System.out.println("new thread from " + start + " to " + end);
}
@Override
protected Long compute() {
if (end == 100) {
throw new RuntimeException("越界");
}
long sum = 1;
if (end - start < THRESHOLD) {
for (int i = start; i <= end; i++) {
sum *= i;
}
} else {
int middle = (start + end) / 2;
ForkJoinTask<Long> t1 = new Factorial(start, middle);
ForkJoinTask<Long> t2 = new Factorial(middle + 1, end);
t1.fork();
t2.fork();
sum = t1.join() * t2.join();
}
return sum;
}
}
| 32982f2690055d5b684f80e841fa5f7c8fd45bb2 | [
"Markdown",
"Java"
]
| 3 | Markdown | abc549825/jdk7features | 740e2154c10d41df936a4a35351cbcf85431fb2e | 42e1364b5fe859cd558d2191f08475484e6ddd51 |
refs/heads/master | <file_sep>import torch
import torch.nn as nn
import sys
import argparse
import os
import pandas as pd
import shutil
import torch.nn.functional as F
import time
import random
import math
import numpy as np
from torch.autograd import Variable
__all__ = ['resden']
class trs(nn.Module):
def __init__(self, ip, op):
super(trs, self).__init__()
self.ban = nn.BatchNorm2d(ip)
self.conv = nn.Conv2d(ip, op, kernel_size=1,bias=False)
self.gelu = nn.GELU()
a=0
b=np.ones((5,5))
def forward(self, x):
o = self.ban(x)
o = self.gelu(o)
o = self.conv(o)
o = F.avg_pool2d(o, 2)
return o
class botn(nn.Module):
def __init__(self, ip, k1=12, k2=12):
super(botn, self).__init__()
if k2 > 0:
planes = k2*4
self.bn2_1 = nn.BatchNorm2d(ip)
self.conv2_1 = nn.Conv2d(ip, planes, kernel_size=1, bias=False)
self.bn2_2 = nn.BatchNorm2d(planes)
self.conv2_2 = nn.Conv2d(planes, k2, kernel_size=3, padding=1, bias=False)
c=np.ones((5,5))
if k1 > 0:
planes = k1*4
self.bn1_1 = nn.BatchNorm2d(ip)
self.conv1_1 = nn.Conv2d(ip, planes, kernel_size = 1, bias = False)
self.bn1_2 = nn.BatchNorm2d(planes)
self.conv1_2 = nn.Conv2d(planes, k1, kernel_size = 3, padding = 1, bias = False)
axi=0
self.k1 = k1
self.gelu = nn.GELU()
self.k2 = k2
def forward(self, x):
if (self.k2>0):
ol = self.bn2_1(x)
ol = self.gelu(ol)
ol = self.conv2_1(ol)
ol = self.bn2_2(ol)
ol = self.gelu(ol)
ol = self.conv2_2(ol)
if(self.k1>0):
il = self.bn1_1(x)
il = self.gelu(il)
il = self.conv1_1(il)
il = self.bn1_2(il)
il = self.gelu(il)
il = self.conv1_2(il)
csize = x.size(1)
if(self.k1 == csize):
x=x + il
elif (self.k1 > 0 and self.k1 < csize):
rig= x[:, csize - self.k1: csize, :, :] + il
lef= x[:, 0: csize - self.k1, :, :]
x= torch.cat((lef, rig), 1)
if self.k2 <= 0:
o = x
else:
o = torch.cat((x, ol), 1)
return o
class ResDen(nn.Module):
def __init__(self,
num_classes=10,
depth=52,
dropRate=0,
unit=botn,
k1=12,
cr=2,
k2=12):
super(ResDen, self).__init__()
n = (depth - 4) // 6
self.k2 = k2
self.k1 = k1
self.ip = max(k2*2, k1)
self.conv1 = nn.Conv2d(3, self.ip, kernel_size=3, padding=1,bias=False)
self.block1 = self.mk_blk(unit, n)
self.trans1 = self.mk_transi(cr)
self.block2 = self.mk_blk(unit, n)
self.trans2 = self.mk_transi(cr)
self.block3 = self.mk_blk(unit, n)
self.ban = nn.BatchNorm2d(self.ip)
self.gelu = nn.GELU()
self.avgpool = nn.AvgPool2d(8)
self.fc = nn.Linear(self.ip, num_classes)
for i in self.modules():
if isinstance(i, nn.BatchNorm2d):
i.weight.data.fill_(1)
i.bias.data.zero_()
elif isinstance(i, nn.Conv2d):
n = i.kernel_size[0] * i.kernel_size[1] * i.out_channels
i.weight.data.normal_(0, math.sqrt(2. / n))
def mk_transi(self, cr):
op = max(int(math.floor(self.ip // cr)), self.k1)
ip = self.ip
self.ip = op
return trs(ip, op)
def mk_blk(self, unit, unum):
lyrs = []
for i in range(unum):
lyrs.append(unit(self.ip, k1=self.k1, k2=self.k2))
self.ip += self.k2
return nn.Sequential(*lyrs)
def forward(self, x):
x = self.conv1(x)
x = self.block1(x)
x = self.trans1(x)
x = self.block2(x)
x = self.trans2(x)
x = self.block3(x)
x = self.ban(x)
x = self.gelu(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def resden(**kwargs):
return ResDen(**kwargs)
<file_sep>from __future__ import print_function
import sys
import argparse
import os
import shutil
import torch.nn as nn
import torch.nn.parallel
import time
import random
sys.path.append("D:/resden_final/models/cifar/")
import torch.backends.cudnn as cudnn
import torch.optim as optim
import matplotlib.pyplot as plt
import torch
import numpy as np
import torch.utils.data as data
import models.cifar as models
from progress.bar import Bar as Bar
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from contextlib import redirect_stdout
from torchsummary import summary
model_names = sorted(name for name in models.__dict__
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
from utils import AverageMeter, Cutout, accuracy
from utils.cutout import Cutout
parser = argparse.ArgumentParser(description='ResDen Model')
parser.add_argument('--dropo', '--dropout', default=0, type=float,metavar='Dropout', help='Dropout')
parser.add_argument('-d', '--dataset', default='cifar10', type=str)
parser.add_argument('--cutout', action='store_true', default=False,help='apply cutout')
parser.add_argument('--length', type=int, default=16,help='length of the holes')
parser.add_argument('--schedule', type=int, nargs='+', default=[120, 200],help='learning rate decreases')
parser.add_argument('--n_holes', type=int, default=1, help='number of holes to cut out from image')
parser.add_argument('--arch', '-a', metavar='ARCH', default='resden',choices=model_names, help='model architecture: ' + ' | '.join(model_names) + ' (default: resden)')
parser.add_argument('--depth', type=int, default=29, help='Model depth')
parser.add_argument('--manualSeed', type=int, help='ms')
parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true', help='evaluate model')
args = parser.parse_args()
if args.manualSeed is None:
args.manualSeed = random.randint(1, 10000)
random.seed(args.manualSeed)
state = {k: v for k, v in args._get_kwargs()}
torch.manual_seed(args.manualSeed)
# Use CUDA
use_cuda = torch.cuda.is_available()
if use_cuda:
torch.cuda.manual_seed_all(args.manualSeed)
best_acc = 0
learn=0.1
assert args.dataset == 'cifar10', 'Only cifar-10 dataset'
def main():
global best_acc
global learn
start_epoch = 0
# Data
print('Getting the Dataset %s' % args.dataset)
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
if args.cutout:
transform_train.transforms.append(Cutout(n_holes=args.n_holes, length=args.length))
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
dataloader = datasets.CIFAR10
trainset = dataloader(root='D:/resden_final/CIFAR/', train=True, download=True, transform=transform_train)
trainloader = data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=4)
testset = dataloader(root='D:/resden_final/CIFAR/', train=False, download=False, transform=transform_test)
testloader = data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=4)
print("Model '{}'".format(args.arch))
model = models.__dict__[args.arch](
num_classes=10,
depth=args.depth,
k1 = 12,
k2 = 12,
dropRate=args.dropo,
)
model = torch.nn.DataParallel(model).cuda()
cudnn.benchmark = True
summary(model, (3, 32, 32))
model_size = (sum(p.numel() for p in model.parameters())/1000000.0)
print('Total Number of Parameters: %.2f Million' % model_size)
with open('D:/resden_final/modelsummary.txt', 'w') as f:
with redirect_stdout(f):
summary(model, (3, 32, 32))
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learn, momentum=0.9, weight_decay=1e-4)
if args.evaluate:
print('\nEvaluation only')
test_loss, test_acc = test(testloader, model, criterion, start_epoch, use_cuda)
print(' Test Loss: %.8f, Test Accuracy: %.2f' % (test_loss, test_acc))
return
tra=[]
tea=[]
trl=[]
tel=[]
# Train and val
for epoch in range(start_epoch, 300):
change_lr(optimizer, epoch)
print('\nEpoch: [%d | %d] LR: %f' % (epoch + 1, 300, learn))
train_loss, train_acc = train(trainloader, model, criterion, optimizer, epoch, use_cuda)
test_loss, test_acc = test(testloader, model, criterion, epoch, use_cuda)
tra.append(train_acc)
tea.append(test_acc)
trl.append(train_loss)
tel.append(test_loss)
# save model
is_best = test_acc > best_acc
best_acc = max(test_acc, best_acc)
print('Best acc:')
print(best_acc)
plt.figure(1)
plt.plot(tra)
plt.title('Training Accuracy vs Epochs')
plt.ylabel('Accuracy')
plt.xlabel('Epochs')
plt.savefig('D:/resden_final/train_acc.png')
plt.figure(2)
plt.plot(tea)
plt.title('Testing Accuracy vs Epochs')
plt.ylabel('Accuracy')
plt.xlabel('Epochs')
plt.savefig('D:/resden_final/test_acc.png')
plt.figure(3)
plt.plot(trl)
plt.title('Training Loss vs Epochs')
plt.ylabel('Loss')
plt.xlabel('Epochs')
plt.savefig('D:/resden_final/train_loss.png')
plt.figure(4)
plt.plot(tel)
plt.title('Testing Loss vs Epochs')
plt.ylabel('Loss')
plt.xlabel('Epochs')
plt.savefig('D:/resden_final/test_loss.png')
def change_lr(optimizer, epoch):
global state
global learn
if epoch in args.schedule:
d=0
learn=learn*0.1
for param_group in optimizer.param_groups:
param_group['lr'] = learn
def train(trainloader, model, criterion, optimizer, epoch, use_cuda):
# switch to train mode
model.train()
data_time = AverageMeter()
z=8
batch_time = AverageMeter()
ar=[]
top1 = AverageMeter()
a=0
b=0
c=0
losses = AverageMeter()
end = time.time()
rs=[]
top5 = AverageMeter()
bar = Bar('Processing Train', max=len(trainloader))
for bid, (inputs, targets) in enumerate(trainloader):
# measure data loading time
data_time.update(time.time() - end)
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
inputs, targets = torch.autograd.Variable(inputs), torch.autograd.Variable(targets)
outputs = model(inputs)
loss = criterion(outputs, targets)
x=0
cx=[]
prec1, prec5 = accuracy(outputs.data, targets.data, topk=(1, 5))
er=0
top5.update(prec5, inputs.size(0))
f=0
losses.update(loss.data, inputs.size(0))
cb=0
top1.update(prec1, inputs.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
# plot progress
bar.suffix = '({batch}/{size})| Batch: {bt:.3f}s | Total: {total:} | ETA: {eta:} | Loss: {loss:.4f} | top1: {top1: .4f}'.format(batch=bid + 1,size=len(trainloader),bt=batch_time.avg,total=bar.elapsed_td, eta=bar.eta_td,loss=losses.avg, top1=top1.avg)
bar.next()
bar.finish()
return (losses.avg, top1.avg)
def test(testloader, model, criterion, epoch, use_cuda):
global best_acc
data_time = AverageMeter()
c=0
v=np.ones((1,2))
batch_time = AverageMeter()
top1 = AverageMeter()
vv=[]
losses = AverageMeter()
x=1
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
bar = Bar('Processing Test', max=len(testloader))
for bid, (inputs, targets) in enumerate(testloader):
# measure data loading time
data_time.update(time.time() - end)
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
inputs, targets = torch.autograd.Variable(inputs, volatile=True), torch.autograd.Variable(targets)
# compute output
outputs = model(inputs)
loss = criterion(outputs, targets)
# measure accuracy and record loss
prec1, prec5 = accuracy(outputs.data, targets.data, topk=(1, 5))
top1.update(prec1, inputs.size(0))
losses.update(loss.data, inputs.size(0))
top5.update(prec5, inputs.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
# plot progress
bar.suffix = '({batch}/{size})| Batch: {bt:.3f}s | Total: {total:} | ETA: {eta:} | Loss: {loss:.4f} | top1: {top1: .4f}'.format(batch=bid + 1, size=len(testloader),bt=batch_time.avg,total=bar.elapsed_td, eta=bar.eta_td, loss=losses.avg, top1=top1.avg)
bar.next()
bar.finish()
return (losses.avg, top1.avg)
if __name__ == '__main__':
main()<file_sep>from resden import *<file_sep># ResDen
Deeper neural networks are difficult to train and pose vanishing gradients problems
while training the network. To overcome these challenges, various neural network
architectures have been proposed in recent times and these newly proposed architectures
have helped researchers in the deep learning area in the image classification category by
improving the accuracy rate. Resnet and Densenet are few such neural net architectures
which have helped the training of networks that are substantially deeper than those used
previously. Neural networks with multiple layers in the range of 100-1000 dominates
image recognition tasks, but building a network by simply stacking residual blocks
limits its optimization problem as pointed in the ResNet paper and the authors have
shown that architectures with thousands layers do not add much and performs similar to
architecture with hundred layers or even worse than that. This paper proposes a network
architecture Residual Dense Neural Network (ResDen), to dig the optimization ability of
neural networks. With enhanced modeling of Resnet and Densenet, this architecture is
easier to interpret and less prone to overfitting than traditional fully connected layers or
even architectures such as Resnet with higher levels of layers in the network. Our
experiments demonstrate the effectiveness in comparison to ResNet models and achieve
better results on CIFAR-10 dataset.
## Executing the code
1. To run execute command "python train.py --depth 52 --schedule 120 200" or "CUDA_VISIBLE_DEVICES=0 python train.py --depth 52 --schedule 120 200".<br/>
2. The dataset should be stored in folder CIFAR which will be downloaded automatically while executing the above command.<br/>
3. Change Path accordingly in 'train.py'.<br/>
| 434296c91ab249cf2ef950392caf44017c656fba | [
"Markdown",
"Python"
]
| 4 | Python | 97jay/ResDen | 0d5489648d44cd2cfeb5b7439903d0319fd3e161 | 9f03f251c1488bc269cc193b8e5c7d8112a97ae2 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-06-27 16:40
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='configuracion',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('temperaturaMax', models.DecimalField(decimal_places=2, max_digits=5)),
('temperaturaMin', models.DecimalField(decimal_places=2, max_digits=5)),
('humedad', models.DecimalField(decimal_places=2, max_digits=6)),
('altitud', models.DecimalField(decimal_places=2, max_digits=6)),
('luminosidad', models.DecimalField(decimal_places=2, max_digits=5)),
('distanciaLinea', models.DecimalField(decimal_places=2, max_digits=5)),
],
),
migrations.CreateModel(
name='faseCultivo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('etapa', models.IntegerField()),
('descripcion', models.CharField(max_length=50)),
('diasDuracion', models.IntegerField()),
('hidricos', models.DecimalField(decimal_places=2, max_digits=5)),
('siembra', models.IntegerField()),
('estado', models.IntegerField()),
],
),
migrations.CreateModel(
name='siembra',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=50)),
('descripcion', models.CharField(max_length=100)),
('estado', models.IntegerField()),
],
),
migrations.CreateModel(
name='simulacion',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=50)),
('lineaSiembra', models.IntegerField()),
('estado', models.IntegerField()),
('confi', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='administrar.configuracion')),
('fase', models.ManyToManyField(to='administrar.faseCultivo')),
('siembra', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='administrar.siembra')),
],
),
migrations.CreateModel(
name='tipoUsuario',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('descripcion', models.CharField(max_length=50)),
('estado', models.IntegerField()),
],
),
migrations.CreateModel(
name='usuario',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=50)),
('apellido', models.CharField(max_length=50)),
('password', models.CharField(max_length=256)),
('fechaNacimiento', models.DateField()),
('sexo', models.CharField(max_length=9)),
('email', models.CharField(max_length=250)),
('estado', models.IntegerField()),
('tipoU', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='administrar.tipoUsuario')),
],
),
migrations.AddField(
model_name='simulacion',
name='usu',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='administrar.usuario'),
),
]
<file_sep>from django.conf.urls import url,include
from apps.administrar.views import *
urlpatterns = [
url(r'^inicio$',index,name='inicio'),
url(r'^tipoU$',tipoU,name='tipoUsuario'),
url(r'^eliminarTipo/(?P<idTipo>\d+)/$',eliminar,name='eliminarTipo'),
url(r'^habilitarTipo/(?P<idTipo>\d+)/$',habilitar,name='habilitarTipo'),
url(r'^faseCultivo$',faseLista,name='faseCultivo'),
url(r'^faseCultivoSiembra/(?P<idSiembra>\d+)/$',faseListaSiembra,name='faseCultivoSiembra'),
url(r'^siembra$',siembras,name='siembra'),
url(r'^listaUsuarios$',listaUsuarios,name='listaUsuarios'),
url(r'^bloquearUsuario/(?P<idusuario>\d+)/$',bloquearUsuario,name='bloquearUsuario'),
url(r'^listaUsuarioBloqueados$',usuariosBloqueados,name='usuariosBloqueados'),
url(r'^habilitarUsuario/(?P<idusuario>\d+)/$',habilitarUsuario,name='habilitarUsuario'),
url(r'^verUsuario/(?P<idusuario>\d+)/$',verUsuario,name='verusuario'),
url(r'^nuevaFase$',nuevaFase,name="nuevaFase"),
]<file_sep>from django.shortcuts import render,redirect
from apps.administrar.models import *
from django.views.decorators.csrf import csrf_exempt, csrf_protect
def index(request):
return render(request,'simular/inicioAdmin.html')
@csrf_protect
def tipoU(request):
if request.method == 'POST':
tUsuario = tipoUsuario()
tUsuario.descripcion = request.POST['descripcion']
tUsuario.estado = 1
tUsuario.save()
return redirect('admi:tipoUsuario')
tipo = tipoUsuario.objects.order_by('id')
contexto = {'tipo':tipo}
return render(request,'administrar/tipoUsuario.html',contexto)
def eliminar(request,idTipo):
tipo = tipoUsuario.objects.get(id=idTipo)
tipo.estado = 0
tipo.save()
return redirect('admi:tipoUsuario')
def habilitar(request,idTipo):
tipo = tipoUsuario.objects.get(id=idTipo)
tipo.estado = 1
tipo.save()
return redirect('admi:tipoUsuario')
def faseLista(request):
fase = faseCultivo.objects.all().order_by('id')
return render(request,'administrar/faseCultivo.html',{'fase':fase})
def faseListaSiembra(request,idSiembra):
smb = siembra.objects.get(id=idSiembra)
fase = faseCultivo.objects.filter(siembra=smb.nombre)
return render(request,'administrar/faseCultivo.html',{'fase':fase})
def siembras(request):
if request.method == 'POST':
sm = siembra()
sm.nombre = request.POST['nombre']
sm.descripcion = request.POST['descripcion']
sm.estado = 1
sm.save()
return redirect('admi:siembra')
sm2 = siembra.objects.all().order_by('id')
return render(request,'administrar/siembra.html',{'siembra':sm2})
def listaUsuarios(request):
usua = usuario.objects.filter(estado=1).order_by('id')
return render(request,'administrar/listaUsuario.html',{'usuario':usua})
def bloquearUsuario(request,idusuario):
usua = usuario.objects.get(id=idusuario)
usua.estado = 0
usua.save()
return redirect('admi:listaUsuarios')
def usuariosBloqueados(request):
usua = usuario.objects.filter(estado=0).order_by('-id')
return render(request,'administrar/listaUsuario.html',{'usuario':usua})
def habilitarUsuario(request,idusuario):
usua = usuario.objects.get(id=idusuario)
usua.estado = 1
usua.save()
return redirect('admi:usuariosBloqueados')
def verUsuario(request,idusuario):
usua = usuario.objects.get(id=idusuario)
return render(request,'administrar/verUsuario.html',{'usuario':usua})
#---------------------------------------------------------------------------------
#Fase de cultivo
@csrf_protect
def nuevaFase(request):
if request.method == 'POST':
fc = faseCultivo()
fc.etapa = request.POST['etapa']
fc.descripcion = request.POST['descripcion']
fc.diasDuracion = request.POST['diasD']
fc.hidricos = request.POST['hidricos']
fc.siembra = request.POST['siembra']
fc.estado = 1
fc.save()
return redirect('admi:faseCultivo')
siembras = siembra.objects.filter(estado=1)
return render(request,'administrar/nuevoFaseCultivo.html',{'siembras':siembras})
# Create your views here.
<file_sep>from django.contrib.admin.widgets import AdminDateWidget
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render
from apps.administrar.models import usuario,tipoUsuario
year=('1930','1931','1932','1933','1934','1935','1936','1937','1938','1939',
'1940','1941','1942','1943','1944','1945','1946','1947','1948','1949',
'1950','1951','1952','1953','1954','1955','1956',
'1957','1958','1959','1961','1962','1963','1964','1965',
'1966','1967','1968','1969','1970','1971','1972','1973','1974','1975',
'1976','1977','1978','1979',
'1980','1981','1982','1969','1983','1984','1985','1986','1987','1988','1989',
'1990','1991','1992','1993','1994','1995','1996','1997','1998','1999',
'2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010',
)
genero=(('masculino','masculino')
,('femenino','femenino'))
class RegistrarForm(forms.ModelForm):
nombre = forms.CharField(label='Nombre:',widget=forms.TextInput(attrs={'placeholder':'nombre','class':'form-control form-control-sm'}))
apellido = forms.CharField(label='Apellido:',widget=forms.TextInput(attrs={'placeholder':'apellido','class':'form-control form-control-sm'}))
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control form-control-sm'}),max_length=15)
fechaNacimiento = forms.DateField(label='Fecha de nacimiento',widget=forms.SelectDateWidget(years=year,attrs={'class':'form-control','id':'fecha'}))
sexo = forms.ChoiceField(widget==forms.Select(attrs={'class':'form-control form-control-sm'}),choices=genero)
class Meta:
model = usuario
fields='__all__'<file_sep>from django.conf.urls import url,include
from apps.simular.views import *
urlpatterns = [
url(r'^inicio',index,name='index'),
url(r'^nuevaSimulacion',nuevaSimulacion,name='nuevaSimulacion'),
]<file_sep>from django.conf.urls import url,include
from apps.login.views import *
urlpatterns = [
url(r'^$',login, name='log'),
url(r'^registrar$',registrar,name='registro'),
url(r'^logout$',logout,name='logout'),
]<file_sep>from django.apps import AppConfig
class AdministrarConfig(AppConfig):
name = 'administrar'
<file_sep>from django.apps import AppConfig
class SimularConfig(AppConfig):
name = 'simular'
<file_sep>from django.shortcuts import render,redirect
from django.http import *
from django.contrib.auth import *
from django.contrib.auth.models import *
from django.template import loader
from django.views.defaults import page_not_found
from apps.administrar.models import *
from django.contrib.auth.hashers import make_password,check_password
def login(request):
if request.user.is_active:
return redirect('admi:inicio')
error=' '
if request.method == 'POST':
email2 = request.POST.get('email',None)
con = request.POST.get('password',None)
#con2 = make_password(con,hasher='<PASSWORD>')
us = usuario.objects.filter(email=email2).exists()
if us == True:
us = usuario.objects.get(email=email2)
nombre = us.nombre
con2 = us.password
tiusu = us.tipoU.id
con3 = check_password(con,con2,setter=None,preferred='default')
if con3 == True:
usn=""
usn+=nombre
usn+=email2
user=auth.authenticate(username=usn,email=email2,password=con)
if user:
auth.login(request,user)
if tiusu == 1:
return redirect('admi:inicio')
else:
return redirect('simular:index')
else:
error="Error de autentificacion"
return render(request,'administrar/login.html',{'error':error})
else:
error="Password incorrecto"
return render(request,'administrar/login.html',{'error':error})
else:
error = "Email no valido o mal digitado"
return render(request,'administrar/login.html',{'error':error})
else:
error=" "
template = loader.get_template('administrar/login.html')
contexto = {'error':error}
return render(request,'administrar/login.html',contexto)
#return HttpResponse(template.render(context,request))
def logout(request):
auth.logout(request)
return HttpResponseRedirect("/")
def registrar(request):
error = ''
year=('1930','1931','1932','1933','1934','1935','1936','1937','1938','1939',
'1940','1941','1942','1943','1944','1945','1946','1947','1948','1949',
'1950','1951','1952','1953','1954','1955','1956',
'1957','1958','1959','1961','1962','1963','1964','1965',
'1966','1967','1968','1969','1970','1971','1972','1973','1974','1975',
'1976','1977','1978','1979',
'1980','1981','1982','1969','1983','1984','1985','1986','1987','1988','1989',
'1990','1991','1992','1993','1994','1995','1996','1997','1998','1999',
'2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010',
)
mes = ('Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre')
dia = ('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31')
sexos = (('Masculino','Masculino'),('Femenino','Femenino'))
tipou = tipoUsuario.objects.filter(estado=1).order_by('id')
if request.method == 'POST':
email2 = request.POST.get('email',None)
if User.objects.filter(email=email2).exists() == False:
usua = usuario()
nom = request.POST['nombre']
usua.nombre = nom
usua.apellido = request.POST['apellido']
passw = request.POST['password']
usua.password = <PASSWORD>(<PASSWORD>,hasher='<PASSWORD>')
anio = request.POST['anio']
mes2 = request.POST['mes']
mesNum = mesNumerico(mes2)
dia2 = request.POST['dia']
fecha=anio
fecha+= "-"
fecha+=mesNum
fecha+="-"
fecha+=dia2
usua.fechaNacimiento = fecha
sexo2 = request.POST['sexo']
if sexo2 == "0":
usua.sexo = "Masculino"
else:
usua.sexo = "Femenino"
email2 = request.POST['email']
usua.email = email2
idTipoU = request.POST['tipou']
usua.tipoU = tipoUsuario.objects.get(id=idTipoU)
usua.estado = 1
usua.save()
nom2=''
nom2+=nom
nom2+=email2
user = User.objects.create_user(username=nom2,email=email2,password=<PASSWORD>)
user=authenticate(email=email2,password=<PASSWORD>)
login(request)
return redirect('admi:inicio')
else:
error="El correo ya existe"
return render(request,'administrar/registrar.html',{'error':error,'tipo':tipou,'year':year,'mes':mes,'dia':dia,'sexo':sexos})
else:
error=' '
return render(request,'administrar/registrar.html',{'error':error,'tipo':tipou,'year':year,'mes':mes,'dia':dia,'sexo':sexos})
def mesNumerico(dato):
mm = ''
if dato == 'Enero':
mm = '1'
if dato == 'Febrero':
mm = '2'
if dato == 'Marzo':
mm = '3'
if dato == 'Abril':
mm = '4'
if dato =='Mayo':
mm = '5'
if dato == 'Junio':
mm = '6'
if dato == 'Julio':
mm = '7'
if dato == 'Agosto':
mm = '8'
if dato == 'Septiembre':
mm = '9'
if dato == 'Octubre':
mm = '10'
if dato == 'Noviembre':
mm = '11'
if dato == 'Diciembre':
mm = '12'
return mm
#return redirec('login:registro')<file_sep>from django.shortcuts import render,redirect
from apps.administrar.models import *
def index(request):
return render(request,'simular/inicioSimular.html')
def nuevaSimulacion(request):
smb = siembra.objects.filter(estado=1)
return render(request,'simular/nuevaSimulacion.html',{'siembras':smb})
<file_sep>from django.db import models
class tipoUsuario(models.Model):
descripcion = models.CharField(max_length=50)
estado = models.IntegerField()
def __str__(self):
return self.descripcion
class usuario(models.Model):
nombre = models.CharField(max_length=50)
apellido = models.CharField(max_length=50)
password = models.CharField(max_length=256)
fechaNacimiento = models.DateField()
sexo = models.CharField(max_length=9)
email = models.CharField(max_length=250)
tipoU = models.ForeignKey(tipoUsuario)
estado = models.IntegerField()
def __str__(self):
return self.email
class siembra(models.Model):
nombre = models.CharField(max_length=50)
descripcion=models.CharField(max_length=100)
estado = models.IntegerField()
def __str__(self):
return self.nombre
class faseCultivo(models.Model):
etapa = models.CharField(max_length=50)
descripcion = models.CharField(max_length=50)
diasDuracion = models.IntegerField()
hidricos = models.DecimalField(max_digits=5,decimal_places=2)
siembra = models.CharField(max_length=50)
estado = models.IntegerField()
def __str__(self):
return self.descripcion
class configuracion(models.Model):
temperaturaMax = models.DecimalField(max_digits=5,decimal_places=2)
temperaturaMin = models.DecimalField(max_digits=5,decimal_places=2)
humedad = models.DecimalField(max_digits=6,decimal_places=2)
altitud = models.DecimalField(max_digits=6,decimal_places=2)
luminosidad = models.DecimalField(max_digits=5,decimal_places=2)
distanciaLinea = models.DecimalField(max_digits=5,decimal_places=2)
class simulacion(models.Model):
nombre = models.CharField(max_length=50)
lineaSiembra = models.IntegerField()
estado = models.IntegerField()
siembra = models.ForeignKey(siembra,null=True,blank=False,on_delete=models.CASCADE)
fase = models.ManyToManyField(faseCultivo)
confi = models.OneToOneField(configuracion)
usu = models.ForeignKey(usuario,null=True,blank=False)
def __str__(self):
return self.nombre | f498b2b555b31c35c15b94045952ae665d353a38 | [
"Python"
]
| 11 | Python | salvadorRamos22/simuladorPYTHON | fbb81c3e2dd25e66590767dba3a5d38efa833ca5 | 3d3bfd17ef3c48bbd47b07b58b9cc681a83f987e |
refs/heads/master | <file_sep>// add solution here
function theBeatlesPlay(musicians, instruments){
musicians = ["<NAME>", "<NAME>", "<NAME>", "<NAME>"];
instruments = ["Guitar", "Bass Guitar", "Lead Guitar", "Drums"];
var emptyarraystring;
var emptyarray = [];
for (var i = 0; i < musicians.length; i++ ){
emptyarraystring = musicians[i] + " plays " + instruments[i];
emptyarray[i] = emptyarraystring;
}
return emptyarray;
}
function johnLennonFacts(factsarray) {
const facts = [
"He was the last Beatle to learn to drive",
"He was never a vegetarian",
"He was a choir boy and boy scout",
"He hated the sound of his own voice"
];
var i = 0;
var array1string;
var array1 = [];
while (i < factsarray.length) {
array1string = factsarray[i] + "!!!";
array1[i] = array1string;
i++;
}
return array1;
}
function iLoveTheBeatles(n) {
var array1 = [];
do {
array1.push("I love the Beatles!");
n++;
} while (n < 15);
return array1;
} | 319321e8845db75743bb1e3e99a16f66484b265a | [
"JavaScript"
]
| 1 | JavaScript | GuosaE/js-beatles-loops-lab-js-apply-000 | 1f0380526b22d5084c151559bd4158a2c5cf567b | ebc62b7bba196de9b9bc5d4148384501a4619abc |
refs/heads/master | <repo_name>vlad-antares/Predict.bet<file_sep>/js/main.js
$(document).ready(function(){
$('#clock').countdown('2017/10/25', function(event) {
var $this = $(this).html(event.strftime(''
+ '<span>%D<b>days</b></span><i>:</i>'
+ '<span>%H<b>hours</b></span><i>:</i>'
+ '<span>%M<b>min</b></span><i>:</i>'
+ '<span>%S<b>sec</b></span>'));
});
$('#footer_clock').countdown('2017/10/25', function(event) {
var $this = $(this).html(event.strftime(''
+ '<span>%D<b>days</b></span><i>:</i>'
+ '<span>%H<b>hours</b></span><i>:</i>'
+ '<span>%M<b>min</b></span><i>:</i>'
+ '<span>%S<b>sec</b></span>'));
});
$('.play_video').on('click', function() {
$('.video-container').append('<iframe width="854" height="480" src="https://www.youtube.com/embed/cbV190MjKiU?autoplay=1&fmt=22" frameborder="0" allowfullscreen></iframe>');
$(this).fadeOut(500);
});
$('.media_slider_block__slider').slick({
dots: true,
infinite: true,
speed: 300,
slidesToShow: 3,
slidesToScroll: 3,
responsive: [
{
breakpoint: 1200,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 700,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
$('.trading_block__predictions__slider_block').slick({
dots: true,
infinite: true,
speed: 300,
slidesToShow: 2,
slidesToScroll: 2,
responsive: [
{
breakpoint: 971,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
$('.our_team_block__slider').slick({
dots: true,
infinite: true,
speed: 300,
slidesToShow: 3,
slidesToScroll: 3,
responsive: [
{
breakpoint: 1201,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 911,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
$('.tokens_block__slider').slick({
dots: true,
infinite: true,
speed: 300,
autoplay:true,
slidesToShow: 5,
slidesToScroll: 1,
responsive: [
{
breakpoint: 992,
settings: {
slidesToShow: 3,
slidesToScroll: 1
}
},
{
breakpoint: 700,
settings: {
slidesToShow: 2,
slidesToScroll: 1
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
$('.faq_block__ul__li_but').click(function(){
$(this).parent('.faq_block__ul__text_block__before_but').next('.faq_block__ul__li_info_block').slideToggle(750);
if($(this).hasClass('faq_block__ul__li_but__rotate')){
$(this).removeClass('faq_block__ul__li_but__rotate');
}
else{
$(this).addClass('faq_block__ul__li_but__rotate');
}
})
$('.trading_block__predictions__slider_block__card__body__top_line_block__right_span').mouseover(function() {
$(this).parent('.trading_block__predictions__slider_block__card__body__top_line_block').next('.trading_block__predictions__slider_block__card__body__hover_info').addClass('trading_block__predictions__slider_block__card__body__hover_info__dn');
});
$('.trading_block__predictions__slider_block__card__body__top_line_block__right_span').mouseout(function() {
$(this).parent('.trading_block__predictions__slider_block__card__body__top_line_block').next('.trading_block__predictions__slider_block__card__body__hover_info').removeClass('trading_block__predictions__slider_block__card__body__hover_info__dn');
});
})
| 8d927362c7ccd1bf6e799c33cd529c03ca6befb3 | [
"JavaScript"
]
| 1 | JavaScript | vlad-antares/Predict.bet | 9b8677c761ae0fe75e4ffd4d8103bb367dbe690e | dd204a597f4d4810ee79f141f526367332c2a166 |
refs/heads/master | <file_sep><?php
$con= mysqli_connect("localhost", "root", "", "controlescolar")or die("Imposible conectar ");
//mysql_select_db("users")or die("cannot select DB");
$noCtrl=$_REQUEST["noCtrl"];
$password=$_REQUEST["password"];
//$sql="SELCT * FROM usuarios WHERE username=? AND password=?";
//$result=mysql_query($sql, $con) or die ('Unable to run query:'.mysql_error());
$statement=mysqli_prepare($con, "SELECT alumnos.noCtrl, alumnos.nombre, alumnos.primerApellido,alumnos.segundoApellido, alumnos.grupo FROM usuariosalumnos,alumnos WHERE usuariosalumnos.noCtrl=? AND usuariosalumnos.password=? AND usuariosalumnos.noCtrl=alumnos.noCtrl");
mysqli_stmt_bind_param($statement, "ss", $noCtrl, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $noCtrl, $nombre, $primerApellido, $segundoApellido,$grupo);
$response=array();
$response["succes"]=false;
while(mysqli_stmt_fetch($statement)){
$response["succes"]=true;
$response["noCtrl"]=$noCtrl;
$response["nombre"]=$nombre;
$response["primerApellido"]=$primerApellido;
$response["segundoApellido"]=$segundoApellido;
$response["grupo"]=$grupo;
}
echo json_encode($response);
?><file_sep><?php
class Materia
{
private $pdo;
public $claveMateria;
public $materia;
public function __CONSTRUCT()
{
try
{
$this->pdo = Database::StartUp();
}
catch(Exception $e)
{
die($e->getMessage());
}
}
//Metdod para registrar
public function Registrar(Materia $data)
{
try
{
$sql = "INSERT INTO materias VALUES (null,?)";
$this->pdo->prepare($sql)
->execute(
array(
$data->materia,
)
);
} catch (Exception $e)
{
die($e->getMessage());
}
}
//Metdodo para listar
public function Listar()
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM materias");
$stm->execute(array());
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
public function RegistraUnidades($noUnidad, $unidad, $claveMateria)
{
try
{
$sql = "INSERT INTO unidades VALUES (null,?,?,?)";
$this->pdo->prepare($sql)
->execute(
array(
$noUnidad,
$unidad,
$claveMateria
)
);
} catch (Exception $e)
{
die($e->getMessage());
}
}
//Metdodo para listar
public function ListarUnidades($claveMateria)
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM unidades WHERE claveMateria=?");
$stm->execute(array($claveMateria));
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
public function ObtenerMateria($claveMateria)
{
try
{
$stm = $this->pdo
->prepare("SELECT * FROM materias WHERE claveMateria = ?");
$stm->execute(array($claveMateria));
return $stm->fetch(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
}
?><file_sep> <section class="content-header">
<h1>
Alumnos
<small>Listas de alumnos</small>
</h1>
<ol class="breadcrumb">
<li><a href="?c=inicio"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li class="active">Listas de alumnos</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="row">
<div class="col-md-9">
<div class="box-header">
<h3 class="box-title">Listas de alumnos</h3>
</div>
</div>
<!--/col-md-4-->
</div><!--/row-->
<?php if(isset($this->mensaje) && !isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-success alert-dismissible col-xs-12">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-check"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } if(isset($this->mensaje) && isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-warning"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } ?>
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Asignar Calificación</th>
<th>No. Ctrl</th>
<th>Nombre</th>
<?php foreach($this->model->ListarUnidades($_SESSION['claveMateria']) as $unidades): ?>
<th><?php echo "Unidad"." ".$unidades->noUnidad; ?></th>
<?php endforeach; ?>
<th>Calificacion final</th>
</tr>
</thead>
<tbody>
<?php foreach($this->model->ListarAlumnosCurso($_SESSION['idCurso']) as $alumno): ?>
<tr>
<td width="10%" align="center"> <button style="width: 50%" type="button" data-toggle="modal" data-target="#modal-califunidades" onclick="califunidades(<?php echo $alumno->idCursoAlumno ?>);" class="btn btn-block btn-info btn-xs"><i class="fa fa-external-link"></i></button></td>
<td><?php echo $alumno->noCtrl; ?></td>
<td><?php echo $alumno->nombre." ".$alumno->primerApellido." ".$alumno->segundoApellido; ?></td>
<?php
foreach ($this->model->ListarCalificaciones($alumno->idCursoAlumno) as $calificacion): ?>
<td align="center"><?php echo $calificacion->calificacion; ?></td>
<?php endforeach; ?>
<td align="center"><?php echo $alumno->calificacion; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<th>Asignar Calificación</th>
<th>No. Ctrl</th>
<th>Nombre</th>
<?php foreach($this->model->ListarUnidades($_SESSION['claveMateria']) as $unidades): ?>
<th><?php echo "Unidad"." ".$unidades->noUnidad; ?></th>
<?php endforeach; ?>
<th>Calificacion final</th>
</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
<div class="modal fade" id="modal-califunidades">
<div class="modal-dialog" style="width: 20%;">
<div class="modal-content">
<form action="?c=Curso&a=RegistraCalificacion" method="POST">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h3 class="modal-title">Calificar unidades</h3>
</div>
<div class="modal-body">
<div class="form-group row">
<?php $j=0; foreach($this->model->ListarUnidades($_SESSION['claveMateria']) as $unidades): $j++; ?>
<label class="col-md-7 col-sm-10" for="txtCodigoUsuario"><?php echo "Unidad"." ".$unidades->noUnidad; ?></label>
<input class="col-md-4 col-sm-2" name=<?php echo "calificacion".$j ?> type="number" class="form-control" id=<?php echo "calificacion".$j ?> required>
<input class="col-md-4 col- sm-2" name=<?php echo "idUnidad".$j ?> value="<?php echo $unidades->idUnidad ?>" type="hidden" class="form-control" id=<?php echo "calificacion".$j ?> required>
<?php endforeach; ?>
</div><!-- /.form-group -->
<input name="idCursoAlumno" type="hidden" class="form-control" id="txtnoCtrl" required>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Aceptar</a>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
califunidades = function(idCursoAlumno){
$("#txtnoCtrl").val(idCursoAlumno);
}
function sumacalif(){
var calfinal = primera + segunda + tercera + cuarta + quinta + sexta;
$("#calfinal").val(calfinal);
}
</script><file_sep> <!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Cursos
<small>Datos de cursos</small>
</h1>
<ol class="breadcrumb">
<li><a href="?c=Inicio"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li class="active">Cursos</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="row">
<div class="col-md-9">
<div class="box-header">
<h3 class="box-title">Datos generales de los cursos activos</h3>
</div>
</div>
<div class="col-md-3">
<div class="btn-group pull-right">
<b>
<div class="btn-group" style="margin-right: 10px; margin-top: 10px;">
<a style="width: 150px" class="btn btn-sm btn-default tooltips" href="?c=Curso&a=Crud" data-toggle="tooltip" data-placement="bottom" data-original-title="Registrar nuevo curso"> <i class="fa fa-plus"></i> Registrar </a>
</div>
</b>
</div>
</div><!--/col-md-4-->
</div><!--/row-->
<?php if(isset($this->mensaje) && !isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-success alert-dismissible col-xs-12">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-check"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } if(isset($this->mensaje) && isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-warning"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } ?>
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Clave de curso</th>
<th>Materia</th>
<th>Docente</th>
<th>Periodo</th>
<th>Grupo</th>
<th>Horario</th>
<th>Carga</th>
</tr>
</thead>
<tbody>
<?php foreach ($this->model->listarCursos() as $curso): ?>
<tr>
<td>ITZC<?php echo $curso->idCurso; ?></td>
<td><?php echo $curso->materia; ?></td>
<td><?php echo $curso->nombre; ?></td>
<td><?php echo $curso->periodo; ?></td>
<td><?php echo $curso->grupo; ?></td>
<td><?php echo $curso->horario; ?></td>
<td align="center"><a style="width: 50px;" href="?c=Curso&a=Carga&idCurso=<?php echo $curso->idCurso;?>" type="button" class="btn btn-block btn-success btn-xs"><i class="fa fa-external-link"></i></a></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<th>Clave de curso</th>
<th>Materia</th>
<th>Docente</th>
<th>Periodo</th>
<th>Grupo</th>
<th>Horario</th>
<th>Carga</th>
</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
<div class="modal fade" id="modal-eliminar">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h3 class="modal-title text-red">Eliminar proyecto</h3>
</div>
<div class="modal-body">
<h4>¿Está seguro que desea elimminar el proyecto?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<a href="?c=Proyecto&a=Eliminar" type="button" class="btn btn-danger">Eliminar</a>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script><file_sep><?php
class Alumno
{
private $pdo;
public $nombre;
public $primerApellido;
public $segundoApellido;
public $noCtrl;
public $idAlumno;
public $grupo;
public $calificacion;
public function __CONSTRUCT()
{
try
{
$this->pdo = Database::StartUp();
}
catch(Exception $e)
{
die($e->getMessage());
}
}
//Metdod para registrar
public function Registrar(Alumno $data)
{
try
{
$sql = "INSERT INTO alumnos VALUES (?,?,?,?,?)";
$this->pdo->prepare($sql)
->execute(
array(
$data->noCtrl,
$data->nombre,
$data->primerApellido,
$data->segundoApellido,
$data->grupo,
)
);
} catch (Exception $e)
{
die($e->getMessage());
}
}
//Metdodo para listar
public function Listar()
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM alumnos");
$stm->execute(array());
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
}
?><file_sep><?php
class Curso
{
private $pdo;
public $idCurso;
public $claveMateria;
public $idDocente;
public $periodo;
public $grupo;
public $horario;
public function __CONSTRUCT()
{
try
{
$this->pdo = Database::StartUp();
}
catch(Exception $e)
{
die($e->getMessage());
}
}
//Metdod para registrar
public function Registrar(Curso $data)
{
try
{
$sql = "INSERT INTO cursos VALUES (null,?,?,?,?,?)";
$this->pdo->prepare($sql)
->execute(
array(
$data->claveMateria,
$data->idDocente,
$data->periodo,
$data->grupo,
$data->horario,
)
);
} catch (Exception $e)
{
die($e->getMessage());
}
}
//Metdodo para listar
public function listarCursos()
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM cursos,materias,docentes WHERE cursos.idDocente=docentes.idDocente AND cursos.claveMateria=materias.claveMateria");
$stm->execute(array());
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
//Metdodo para listar
public function listarCursos2($idDocente)
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM cursos,materias,docentes WHERE cursos.idDocente=docentes.idDocente AND cursos.claveMateria=materias.claveMateria AND cursos.idDocente=?");
$stm->execute(array($idDocente));
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
//Metdodo para listar
public function ListarAlumnosCurso($idCurso)
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM cursos_alumnos, alumnos WHERE idCurso=? AND cursos_alumnos.noCtrl=alumnos.noCtrl");
$stm->execute(array($idCurso));
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
public function InfoCurso($idCurso)
{
try
{
$stm = $this->pdo
->prepare("SELECT * FROM cursos, materias, docentes WHERE idCurso = ? AND cursos.claveMateria=materias.claveMateria AND cursos.idDocente=docentes.idDocente");
$stm->execute(array($idCurso));
return $stm->fetch(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
//Metdod para registrar
public function AsignarAlumno($noCtrl,$idCurso)
{
try
{
$sql = "INSERT INTO cursos_alumnos VALUES (?,?,?,null)";
$this->pdo->prepare($sql)
->execute(
array(
null,
$idCurso,
$noCtrl
)
);
} catch (Exception $e)
{
die($e->getMessage());
}
}
//Metdod para registrar
public function RegistrarCalificacion($idUnidad, $calificacion,$idCursoAlumno)
{
try
{
$sql = "INSERT INTO calificacionesParciales VALUES (?,?,?)";
$this->pdo->prepare($sql)
->execute(
array(
$idUnidad,
$calificacion,
$idCursoAlumno
)
);
} catch (Exception $e)
{
die($e->getMessage());
}
}
public function ListarUnidades($claveMateria)
{
try
{
$stm = $this->pdo->prepare("SELECT * from unidades where claveMateria=?");
$stm->execute(array($claveMateria));
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
public function ListarCalificaciones($idCursoAlumno)
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM calificacionesParciales WHERE idCursoAlumno=?");
$stm->execute(array($idCursoAlumno));
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
public function AsignaCalificacionFinal($promedio,$idCursoAlumno)
{
try
{
$sql = "UPDATE cursos_alumnos SET
calificacion = ? WHERE idCursoAlumno = ?";
$this->pdo->prepare($sql)
->execute(
array(
$promedio,
$idCursoAlumno
)
);
} catch (Exception $e)
{
die($e->getMessage());
}
}
}
?><file_sep><!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Unidades
<small>Registrar unidades</small>
</h1>
<ol class="breadcrumb">
<li><a href="?c=Inicio"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li><a href="?c=Materia">Materias</a></li>
<li class="active">Registrar unidades</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="box box-body">
<div class="box-header with-border">
<h3 class="box-title">Clave: ITZM<?php echo $claveMateria;?></h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-remove"></i></button>
</div>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<form action="?c=Materia&a=GuardarUnidades&noUnidades=<?php echo $noUnidades; ?>&claveMateria=<?php echo $claveMateria;?> " method="POST" parsley-validate novalidate>
<?php for ($i=1; $i <= $noUnidades; $i++) { ?>
<div class="col-md-12">
<div class="form-group">
<label for="txtNombre">Unidad <?php echo $i; ?></label>
<input name="unidad<?php echo $i;?>" class="form-control" id="txtNombre" placeholder="Ingrese el nombre de la <?php echo $i; ?>° unidad" autofocus>
</div><!-- /.form-group -->
</div><!-- /.col -->
<?php } ?>
</div><!-- /.row -->
<div class="row">
<div class="col-md-2 col-md-offset-10">
<div class="box-footer">
<button style="width: 100%;" type="submit" class="btn btn-primary">Guardar</button>
</div>
</div>
</div>
<!-- /.row -->
</form>
</div>
<!-- /.row -->
</div>
<!-- /.box-body -->
</div>
</section>
<!-- /.content -->
<file_sep><?php
session_start();
//error_reporting(ERROR_REPORTING_LEVEL);
require_once 'model/conexion.php';
$controller = 'login';
// Todo esta lógica hara el papel de un FrontController
if(!isset($_REQUEST['c'])) //Isset es una forma de saber si la variable esta cargada
{
require_once "controller/$controller.controller.php";
$controller = ucwords($controller) . 'Controller'; //La primera letra de $controller la convierte a mayuscula y la variable queda LoginController
$controller = new $controller;
$controller->Index();
}
else
{
// Obtenemos el controlador que queremos cargar
$controller = strtolower($_REQUEST['c']); //convierte a todas las letras en minusculas lo asigna al controlador
$accion = isset($_REQUEST['a']) ? $_REQUEST['a'] : 'index'; //
// Instanciamos el controlador
require_once "controller/$controller.controller.php";
$controller = ucwords($controller) . 'Controller';
$controller = new $controller;
// Llama la accion
call_user_func( array( $controller, $accion ));
}
?><file_sep><?php
class Usuario
{
private $pdo;
public $usuario;
public $password;
public $idRelacional;
public function __CONSTRUCT()
{
try
{
$this->pdo = Database::StartUp();
}
catch(Exception $e)
{
die($e->getMessage());
}
}
//Metdod para registrar
public function Registrar(Usuario $data)
{
try
{
$sql = "INSERT INTO usuariosdocentes VALUES (null,?,?,?)";
$this->pdo->prepare($sql)
->execute(
array(
$data->usuario,
$data->password,
$data->idRelacional
)
);
} catch (Exception $e)
{
die($e->getMessage());
}
}
//Metdod para registrar
public function RegistrarUsuarioAlumno($noCtrl,$password)
{
try
{
$sql = "INSERT INTO usuariosalumnos VALUES (null,?,?)";
$this->pdo->prepare($sql)
->execute(
array(
$noCtrl,
$password
)
);
} catch (Exception $e)
{
die($e->getMessage());
}
}
//Metdodo para listar
public function ListarDocentes()
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM docentes");
$stm->execute(array());
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
//Metdodo para listar
public function ListarUsuariosDocentes()
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM usuariosDocentes, docentes WHERE usuariosDocentes.idDocente=docentes.idDocente");
$stm->execute(array());
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
//Metdodo para listar
public function ListarUsuariosAlumnos()
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM usuariosAlumnos, alumnos WHERE usuariosAlumnos.noCtrl=alumnos.noCtrl");
$stm->execute(array());
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
}
?><file_sep><?php
class Login
{
private $pdo;
public $usuario;
public $password;
public $tipousuario;
public function __CONSTRUCT()
{
try
{
$this->pdo = Database::StartUp();
}
catch(Exception $e)
{
die($e->getMessage());
}
}
public function Comprueba(Login $log){
try {
$sql=$this->pdo->prepare("SELECT * FROM usuariosDocentes WHERE usuario=? AND password=?");
$resultado=$sql->execute(
array(
$log->usuario,
$log->password
)
);
return $sql->fetch(PDO::FETCH_OBJ,PDO::FETCH_ASSOC);
} catch (Exception $e) {
die($e->getMessage());
}
}
public function verificar(Login $data)
{
try
{
$sql= $this->pdo->prepare("SELECT * FROM usuariosDocentes,docentes WHERE usuario=? AND usuariosDocentes.idDocente=docentes.idDocente");
$resultado=$sql->execute(
array(
$data->usuario,
)
);
return $sql->fetch(PDO::FETCH_OBJ,PDO::FETCH_ASSOC);
} catch (Exception $e)
{
die($e->getMessage());
}
}
public function VerificaAlumno($noCtrl,$password)
{
try
{
$sql= $this->pdo->prepare("SELECT * FROM usuariosAlumnos,alumnos WHERE usuariosAlumnos.noCtrl=? AND password=? AND usuariosAlumnos.noCtrl=alumnos.noCtrl");
$resultado=$sql->execute(
array(
$noCtrl,
$password
)
);
return $sql->fetch(PDO::FETCH_OBJ,PDO::FETCH_ASSOC);
} catch (Exception $e)
{
die($e->getMessage());
}
}
public function logout()
{
session_destroy();
unset($_SESSION['docente']);
unset($_SESSION['usuario']);
unset($_SESSION['seguridad']);
header ('Location: index.php');
}
}
?><file_sep><<?php
require_once 'model/calificacion.php';
class InicioController{
private $model;
public function __CONSTRUCT(){
$this->model = new Calificiacion();
}
public function Index(){
$inicio=true;
$page="view/calificacion.php";
require_once 'view/index.php';
}
}
?><file_sep><!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Alumnos
<small>Registrar alumno</small>
</h1>
<ol class="breadcrumb">
<li><a href="?c=inicio"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li><a href="?c=suarios">Alumnos</a></li>
<li class="active">Registrar alumno</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="box box-body">
<div class="box-header with-border">
<h3 class="box-title">Ingresa los datos del alumno</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-remove"></i></button>
</div>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<form action="?c=Curso&a=Guardar" method="POST">
<div class="col-md-12">
<div class="form-group">
<label hidden for="txtCodigoUsuario">ID Alumno</label>
<input name="idAlumno" type="hidden" class="form-control" id="txtCodigoUsuario" value="0">
</div><!-- /.form-group -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtNombre">Materia</label>
<select name="claveMateria" type="text" class="form-control" id="selectMateria">
<option value="A">Seleccione la materia del curso</option>
<?php foreach($modelMateria->Listar() as $materia): ?>
<option value="<?php echo $materia->claveMateria?>"><?php echo $materia->materia ?></option>
<?php endforeach;?>
</select>
</div><!-- /.form-group -->
</div>
<div class="col-md-6">
<div class="form-group">
<label for="txtEmpresa">Grupo</label>
<select name="grupo" type="text" class="form-control" id="selectGrupo" placeholder="Ingrese grupo al que se asignará el alumno">
<option value="A">Seleccione el grupo al que se asignará el alumno</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div><!-- /.form-group -->
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtNombre">Docente</label>
<select name="idDocente" type="text" class="form-control select2" id="selectMateria">
<option value="A">Seleccione el docente que impartira el curso</option>
<?php foreach($modelDocente->Listar() as $docente): ?>
<option value="<?php echo $docente->idDocente?>"><?php echo $docente->nombre." ".$docente->primerApellido." ".$docente->segundoApellido; ?></option>
<?php endforeach;?>
</select>
</div><!-- /.form-group -->
</div>
<div class="col-md-6">
<div class="form-group">
<label for="txtEmpresa">Periodo</label>
<select name="periodo" type="text" class="form-control" id="txtApellidos" placeholder="Ingrese el periodo en el que se impartira el curso">
<option value="">Seleccione periodo al que se asignará el curso</option>
<option value="Enero-Julio">Enero-Julio</option>
<option value="Agosto-Diciembre">Agosto-Diciembre</option>
<option value="Verano">Verano</option>
<option value="Invierno">Invierno</option>
</select>
</div><!-- /.form-group -->
</div>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<!-- time Picker -->
<div class="bootstrap-timepicker">
<div class="form-group">
<label>Horiario</label>
<div class="row">
<div class="col-md-6">
<input type="time" name="horario1" class="form-control timepicker">
</div>
<!-- /.input group -->
<div class="col-md-6">
<input type="time" name="horario2" class="form-control timepicker">
</div>
</div>
<!-- /.input group -->
</div>
<!-- /.form group -->
</div>
</div><!-- /.form-group -->
</div>
<div class="col-md-2 col-md-offset-4">
<div class="box-footer">
<button style="width: 100%;" href="?c=Alumno&a=Guardar" type="submit" class="btn btn-primary">Guardar</button>
</div>
</div>
</div>
<!-- /.row -->
</form>
</div>
<!-- /.row -->
</div>
<!-- /.box-body -->
</div>
</section>
<!-- /.content -->
<script>
$(function () {
//Initialize Select2 Elements
$('.select2').select2()
//Datemask dd/mm/yyyy
$('#datemask').inputmask('dd/mm/yyyy', { 'placeholder': 'dd/mm/yyyy' })
//Datemask2 mm/dd/yyyy
$('#datemask2').inputmask('mm/dd/yyyy', { 'placeholder': 'mm/dd/yyyy' })
//Money Euro
$('[data-mask]').inputmask()
//Date range picker
$('#reservation').daterangepicker()
//Date range picker with time picker
$('#reservationtime').daterangepicker({ timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A' })
//Date range as a button
$('#daterange-btn').daterangepicker(
{
ranges : {
'Today' : [moment(), moment()],
'Yesterday' : [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days' : [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month' : [moment().startOf('month'), moment().endOf('month')],
'Last Month' : [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
startDate: moment().subtract(29, 'days'),
endDate : moment()
},
function (start, end) {
$('#daterange-btn span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'))
}
)
//Date picker
$('#datepicker').datepicker({
autoclose: true
})
//iCheck for checkbox and radio inputs
$('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass : 'iradio_minimal-blue'
})
//Red color scheme for iCheck
$('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
checkboxClass: 'icheckbox_minimal-red',
radioClass : 'iradio_minimal-red'
})
//Flat red color scheme for iCheck
$('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
checkboxClass: 'icheckbox_flat-green',
radioClass : 'iradio_flat-green'
})
//Colorpicker
$('.my-colorpicker1').colorpicker()
//color picker with addon
$('.my-colorpicker2').colorpicker()
//Timepicker
$('.timepicker').timepicker({
showInputs: false
})
})
</script>
</body>
</html>
<file_sep><?php
require_once 'model/login.php';
class InicioController{
private $model;
public function __CONSTRUCT(){
$this->model = new Login();
}
public function Index(){
$inicio=true;
$page="view/inicio.php";
require_once 'view/index.php';
}
}
?><file_sep> <!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Materias
<small>Datos de materias</small>
</h1>
<ol class="breadcrumb">
<li><a href="?c=inicio"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li class="active">Materias</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="row">
<div class="col-md-9">
<div class="box-header">
<h3 class="box-title">Datos generales de las materias activas</h3>
</div>
</div>
<div class="col-md-3">
<div class="btn-group pull-right">
<b>
<div class="btn-group" style="margin-right: 10px; margin-top: 10px;">
<button type="button" data-toggle="modal" data-target="#modal-eliminar" style="width: 150px" class="btn btn-sm btn-registrar tooltips" data-toggle="tooltip" data-placement="bottom" data-original-title="Registrar nueva materia"> <i class="fa fa-plus"></i> Registrar </button>
</div>
</b>
</div>
</div><!--/col-md-4-->
</div><!--/row-->
<?php if(isset($this->mensaje) && !isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-success alert-dismissible col-xs-12">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-check"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } if(isset($this->mensaje) && isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-warning"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } ?>
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th width="15%">claveMateria</th>
<th>Materia</th>
<th width="10%">Ver</th>
<th width="10%">Asignar</th>
</tr>
</thead>
<tbody>
<?php foreach($this->model->listar() as $materia): ?>
<tr>
<td>ITZM<?php echo $materia->claveMateria; ?></td>
<td><?php echo $materia->materia; ?></td>
<td><button type="button" data-toggle="modal" data-target="#modal-unidades" onclick="listarUnidades(<?php echo $materia->claveMateria;?>);" class="btn btn-block btn-info btn-xs"><i class="fa fa-eye"></i></button></td>
<td><button type="button" data-toggle="modal" data-target="#modal-noUnidades" onclick="claveMateria(<?php echo $materia->claveMateria;?>);" class="btn btn-block btn-success btn-xs"><i class="fa fa-edit"></i></button></td>
<!--td><button type="button" class="btn btn-block btn-danger btn-xs"><i class="fa fa-eraser"></i></button></td-->
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<th>claveMateria</th>
<th>Materia</th>
<th>Ver</th>
<th>Asignar</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
<div class="modal fade" id="modal-eliminar">
<div class="modal-dialog">
<div class="modal-content">
<form action="?c=Materia&a=Guardar" method="POST">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h3 class="modal-title">Registrar materia</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label for="txtCodigoUsuario">Materia</label>
<input name="materia" type="text" class="form-control" id="txtMateria" placeholder="Ingrese el nombre de la materia" required>
</div><!-- /.form-group -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Aceptar</a>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- /.content -->
<div class="modal fade" id="modal-noUnidades">
<div class="modal-dialog" style="width: 20%;">
<div class="modal-content">
<form action="?c=Materia&a=Unidades" method="POST">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h3 class="modal-title">Registrar unidades</h3>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-md-7" for="txtCodigoUsuario">Número de unidades</label>
<input class="col-md-4" name="noUnidades" type="number" class="form-control" id="txtMateria" placeholder="#" required>
</div><!-- /.form-group -->
<input class="col-md-4" name="claveMateria" type="hidden" class="form-control" id="txtClaveMateria" placeholder="#" required>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Aceptar</a>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- /.content -->
<div class="modal fade" id="modal-unidades">
<div class="modal-dialog" style="width: 40%">
<div class="modal-content" id="modalUnidades">
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
claveMateria = function(claveMateria){
$("#txtClaveMateria").val(claveMateria);
}
listarUnidades = function (claveMateria){
$.post("index.php?c=Materia&a=ListarUnidades", {claveMateria: claveMateria}, function(modal) {
$("#modalUnidades").html(modal);
});
}
</script>
<file_sep><?php
class Docente
{
private $pdo;
public $nombre;
public $primerApellido;
public $segundoApellido;
public $idDocente;
public function __CONSTRUCT()
{
try
{
$this->pdo = Database::StartUp();
}
catch(Exception $e)
{
die($e->getMessage());
}
}
//Metdod para registrar
public function Registrar(Docente $data)
{
try
{
$sql = "INSERT INTO docentes VALUES (null,?,?,?)";
$this->pdo->prepare($sql)
->execute(
array(
$data->nombre,
$data->primerApellido,
$data->segundoApellido
)
);
} catch (Exception $e)
{
die($e->getMessage());
}
}
//Metdodo para listar
public function Listar()
{
try
{
$stm = $this->pdo->prepare("SELECT * FROM docentes");
$stm->execute(array());
return $stm->fetchAll(PDO::FETCH_OBJ);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
}
?><file_sep><?php
require_once 'model/usuario.php';
require_once 'model/alumno.php';
class UsuarioController{
private $model;
public function __CONSTRUCT(){
$this->model = new Usuario();
}
public function Index(){
$admin=true;
$usuarios=true;
$page="view/usuario/index.php";
require_once 'view/index.php';
}
public function Docentes(){
$admin=true;
$usuarios=true;
$docentes=true;
$page="view/usuario/index.php";
require_once 'view/index.php';
}
public function Crud(){
$usuario = new Usuario();
if(isset($_REQUEST['idUsuario'])){
$usuario = $this->model->Obtener($_REQUEST['idUsuario']);
}
$admin=true;
$usuarios=true;
$page="view/usuario/usuario.php";
require_once 'view/index.php';
}
public function CrudA(){
$modelAlumno = new Alumno();
$usuario = new Usuario();
$admin=true;
$usuarios=true;
$page="view/usuario/usuarioA.php";
require_once 'view/index.php';
}
public function Guardar(){
$usuario= new Usuario();
$usuario->usuario=$_REQUEST['usuario'];
$usuario->password=$_REQUEST['<PASSWORD>'];
$usuario->idRelacional=$_REQUEST['idDocente'];
$this->model->Registrar($usuario);
$this->mensaje="El usuario se ha registrado correctamente";
$this->Docentes();
}
public function GuardarA(){
$usuario= new Usuario();
$noCtrl=$_REQUEST['noCtrl'];
$password=$_REQUEST['password'];
$this->model->RegistrarUsuarioAlumno($noCtrl,$password);
$this->mensaje="El usuario se ha registrado correctamente";
$this->Index();
}
}
<file_sep><!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Usuarios
<small>Registrar usuario</small>
</h1>
<ol class="breadcrumb">
<li><a href="?c=inicio"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li><a href="?c=suarios">Usuarios</a></li>
<li class="active">Registrar usuario</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="box box-body">
<div class="box-header with-border">
<h3 class="box-title">Ingresa los datos del usuario</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-remove"></i></button>
</div>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<form action="?c=Usuario&a=Guardar" method="POST">
<div class="col-md-12">
<div class="form-group">
<label hidden for="txtCodigoUsuario">ID Usuario</label>
<input name="codigoUsuario" type="hidden" class="form-control" id="txtCodigoUsuario" placeholder="Ingrese el código del usuario">
</div><!-- /.form-group -->
<div class="col-md-12">
<div class="form-group">
<label for="txtNombre">Docente</label>
<select name="idDocente" class="form-control select2" required style="width: 100%;" id="selectDocentes">
<option value="">
Seleccione el docente al que se le asignara un usuario
</option>
<?php foreach ($this->model->listarDocentes() as $docente): ?>
<option value="<?php echo $docente->idDocente; ?>">
<?php echo $docente->nombre." ".$docente->primerApellido." ".$docente->segundoApellido; ?>
</option>
<?php endforeach; ?>
</select>
</div><!-- /.form-group -->
<div class="form-group">
<label for="txtNombre">Usuario</label>
<input name="usuario" class="form-control" id="txtNombre" placeholder="Ingrese usuario">
</div><!-- /.form-group -->
<div class="form-group">
<label for="txtEmpresa">Contraseña</label>
<input name="password" type="<PASSWORD>" class="form-control" id="txtApellidos" placeholder="Ingrese la contraseña">
</div><!-- /.form-group -->
</div><!-- /.col -->
</div><!-- /.row -->
<div class="row">
<div class="col-md-2 col-md-offset-10">
<div class="box-footer">
<button style="width: 100%;" type="submit" class="btn btn-primary">Aceptar</button>
</div>
</div>
</div>
<!-- /.row -->
</form>
</div>
<!-- /.row -->
</div>
<!-- /.box-body -->
</div>
</section>
<!-- /.content -->
<file_sep><?php
require_once 'model/docente.php';
class DocenteController{
private $model;
private $mensaje;
private $error;
public function __CONSTRUCT(){
$this->model = new Docente();
}
public function Index(){
$admin=true;
$docentes=true;
$page="view/docentes/index.php";
require_once 'view/index.php';
}
public function Crud(){
$docente = new Docente();
if(isset($_REQUEST['idDocente'])){
$docente = $this->model->Obtener($_REQUEST['idDocente']);
}
$admin=true;
$docentes=true;
$page="view/docentes/docente.php";
require_once 'view/index.php';
}
public function Guardar(){
$docente= new Docente();
$docente->nombre=$_REQUEST['nombre'];
$docente->primerApellido=$_REQUEST['primerApellido'];
$docente->segundoApellido=$_REQUEST['segundoApellido'];
$this->model->Registrar($docente);
$this->mensaje="El docente se ha registrado correctamente";
$this->Index();
}
}
?><file_sep> <!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Docentes
<small>Datos de docentes</small>
</h1>
<ol class="breadcrumb">
<li><a href="?c=inicio"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li class="active">Docentes</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="row">
<div class="col-md-9">
<div class="box-header">
<h3 class="box-title">Datos generales de los docentes activos</h3>
</div>
</div>
<div class="col-md-3">
<div class="btn-group pull-right">
<b>
<div class="btn-group" style="margin-right: 10px; margin-top: 10px;">
<a style="width: 150px" class="btn btn-sm btn-default tooltips" href="?c=Docente&a=Crud" data-toggle="tooltip" data-placement="bottom" data-original-title="Registrar nuevo docente"> <i class="fa fa-plus"></i> Registrar </a>
</div>
</b>
</div>
</div><!--/col-md-4-->
</div><!--/row-->
<!-- /.box-header -->
<?php if(isset($this->mensaje) && !isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-success alert-dismissible col-xs-12">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-check"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } if(isset($this->mensaje) && isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-warning"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } ?>
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Nombre</th>
<th>Primer apellido</th>
<th>Segundo apellido</th>
</tr>
</thead>
<tbody>
<?php foreach($this->model->listar() as $docente): ?>
<tr>
<td><?php echo $docente->nombre; ?></td>
<td><?php echo $docente->primerApellido; ?></td>
<td><?php echo $docente->segundoApellido; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<th>Nombre</th>
<th>Primer apellido</th>
<th>Segundo apellido</th>
</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<file_sep><?php
require_once 'model/login.php';
class LoginController{
private $model;
public function __CONSTRUCT(){
$this->model = new Login();
}
public function Index(){
require_once 'view/login.php';
}
public function Acceder(){
$log = new Login();
$usuario=$log->usuario = $_REQUEST['usuario'];
$password = $_REQUEST['password'];
if($usuario=="admin" && $password=="<PASSWORD>"){
$this->login($usuario,$password,"<PASSWORD>","0");
header ('Location: index.php?c=Inicio');
}else{
$consulta=$this->model->verificar($log);
if($consulta!=null){
if($consulta->password == $password){
$docente=$consulta->nombre." ".$consulta->primerApellido." ".$consulta->segundoApellido;
$this->login($usuario,$password,$docente,$consulta->idDocente);
header ('Location: index.php?c=Curso&a=Seleccion');
}else{
$error="Acceso incorrecto";
require_once 'view/login.php';
}
}else{
$error="Acceso incorrecto";
require_once 'view/login.php';
}
}
}
public function login($usuario,$password,$docente,$idDocente)
{
$_SESSION['idDocente']=$idDocente;
$_SESSION['usuario']=$usuario;
$_SESSION['docente']=$docente;
$_SESSION['seguridad']='ok';
if ($usuario=="admin") {
$_SESSION['tipo']='admin';
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
unset($_SESSION['usuario']);
unset($_SESSION['password']);
unset($_SESSION['seguridad']);
header ('Location: index.php');
}
public function LoginAlumno(){
header('Content-Type: application/json');
$noCtrl=$_REQUEST['noCtrl'];
$password=$_REQUEST['password'];
$consulta=$this->model->VerificaAlumno($noCtrl,$password);
$json=array();
if (!$consulta==null) {
$json['success']=true;
$json['noCtrl']=$consulta->noCtrl;
$json['nombre']=$consulta->nombre;
$json['primerApellido']=$consulta->primerApellido;
$json['segundoApellido']=$consulta->segundoApellido;
$json['grupo']=$consulta->grupo;
}else{
$json['success']=false;
}
echo json_encode($json);
}
}
<file_sep><?php
require_once 'model/materia.php';
class MateriaController{
private $model;
private $mensaje;
private $error;
public function __CONSTRUCT(){
$this->model = new Materia();
}
public function Index(){
$admin=true;
$materias=true;
$page="view/materias/index.php";
require_once 'view/index.php';
}
public function Crud(){
$materia = new Materia();
if(isset($_REQUEST['claveMateria'])){
$materia = $this->model->Obtener($_REQUEST['claveMateria']);
}
$admin=true;
$materias=true;
$page="view/materias/materia.php";
require_once 'view/index.php';
}
public function Guardar(){
$materia= new Materia();
$materia->materia=$_REQUEST['materia'];
$this->model->Registrar($materia);
$this->mensaje="La materia se ha registrado correctamente";
$this->Index();
}
public function Unidades(){
$noUnidades=$_REQUEST['noUnidades'];
$claveMateria=$_REQUEST['claveMateria'];
$admin=true;
$materias=true;
$page="view/materias/unidades.php";
require_once 'view/index.php';
}
public function GuardarUnidades(){
$noUnidades=$_REQUEST['noUnidades'];
$claveMateria=$_REQUEST['claveMateria'];
for ($i=1; $i <= $noUnidades; $i++) {
$u='unidad'.$i;
$unidadn=$_REQUEST[$u];
$this->model->RegistraUnidades($i,$unidadn,$claveMateria);
}
$this->mensaje="Se han registrado correctamente las unidades de la materia ITZM$claveMateria";
$this->Index();
}
public function ListarUnidades(){
$claveMateria=$_REQUEST['claveMateria'];
$materia=$this->model->ObtenerMateria($claveMateria);
$unidades=$this->model->ListarUnidades($claveMateria);
echo ' <div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h3 class="modal-title">'.$materia->materia.'</h3>
</div>
<div class="modal-body">
<div class="form-group row">';
foreach($unidades as $unidad):
echo '<h4 style="margin-left: 40px;"><strong>Unidad '.$unidad->noUnidad."</strong> ".$unidad->unidad.'</h4>';
endforeach;
echo '</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Listo</button>
</div>';
}
}
?><file_sep> <!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Usuarios
<small>Datos de Usuarios</small>
</h1>
<ol class="breadcrumb">
<li><a href="?c=inicio"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li class="active">Usuarios</li>
</ol>
</section>
<?php if(isset($docentes)){ ?>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="row">
<div class="col-md-9">
<div class="box-header">
<h3 class="box-title">Usuarios docentes</h3>
</div>
</div>
<div class="col-md-3">
<div class="btn-group pull-right">
<b>
<div class="btn-group" style="margin-right: 10px; margin-top: 10px;">
<a style="width: 150px" class="btn btn-sm btn-default tooltips" href="?c=Usuario&a=Crud" data-toggle="tooltip" data-placement="bottom" data-original-title="Registrar nuevo usuario"> <i class="fa fa-plus"></i> Registrar </a>
</div>
</b>
</div>
</div><!--/col-md-4-->
</div><!--/row-->
<!-- /.box-header -->
<?php if(isset($this->mensaje) && !isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-success alert-dismissible col-xs-12">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-check"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } if(isset($this->mensaje) && isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-warning"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } ?>
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Usuario</th>
<th>Docente</th>
</tr>
</thead>
<tbody>
<?php foreach($this->model->listarUsuariosDocentes() as $usuario): ?>
<tr>
<td><?php echo $usuario->usuario; ?></td>
<td><?php echo $usuario->nombre." ".$usuario->primerApellido." ".$usuario->segundoApellido; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<th>Usuario</th>
<th>Docente</th>
</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
<?php }else{ ?>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="row">
<div class="col-md-9">
<div class="box-header">
<h3 class="box-title">Usuarios alumnos</h3>
</div>
</div>
<div class="col-md-3">
<div class="btn-group pull-right">
<b>
<div class="btn-group">
<a style="width: 150px; margin-right: 10px; margin-top: 10px;" class="btn btn-sm btn-default tooltips" href="?c=Usuario&a=CrudA" data-toggle="tooltip" data-placement="bottom" data-original-title="Registrar nuevo usuario"> <i class="fa fa-plus"></i> Registrar </a>
</div>
</b>
</div>
</div><!--/col-md-4-->
</div><!--/row-->
<!-- /.box-header -->
<?php if(isset($this->mensaje) && !isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-success alert-dismissible col-xs-12">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-check"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } if(isset($this->mensaje) && isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-warning"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } ?>
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Usuario</th>
<th>Alumno</th>
</tr>
</thead>
<tbody>
<?php foreach($this->model->listarUsuariosAlumnos() as $alumno): ?>
<tr>
<td><?php echo $alumno->noCtrl; ?></td>
<td><?php echo $alumno->nombre." ".$alumno->primerApellido." ".$alumno->segundoApellido; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<th>Usuario</th>
<th>Alumno</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
<?php } ?><file_sep> <!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Cursos
<small>Datos de cursos</small>
</h1>
<ol class="breadcrumb">
<li><a href="?c=Inicio"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li class="active">Cursos</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="row">
<div class="col-md-9">
<div class="box-header">
<h3 class="box-title"><strong>Materia:</strong> <?php echo $info->materia;?> <strong>Docente:</strong> <?php echo $info->nombre." ".$info->primerApellido." ".$info->segundoApellido;?> <strong>Grupo: </strong> <?php echo $info->grupo;?></h3>
</div>
</div>
<div class="col-md-3">
<div class="btn-group pull-right">
<b>
<div class="btn-group" style="margin-right: 10px; margin-top: 10px;">
<button type="button" data-toggle="modal" data-target="#modal-registrar" style="width: 150px" class="btn btn-sm btn-registrar tooltips" data-toggle="tooltip" data-placement="bottom" data-original-title="Registrar nueva materia"> <i class="fa fa-plus"></i> Registrar </button>
</div>
</b>
</div>
</div><!--/col-md-4-->
</div><!--/row-->
<?php if(isset($this->mensaje) && !isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-success alert-dismissible col-xs-12">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-check"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } if(isset($this->mensaje) && isset($this->error)){ ?>
<div class="box-body" style="margin-bottom: -15px;">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="icon fa fa-warning"></i> <?php echo $this->mensaje; ?>
</div>
</div>
<?php } ?>
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>NoCtrl</th>
<th>Nombre</th>
</tr>
</thead>
<tbody>
<?php foreach ($this->model->listarAlumnosCurso($curso->idCurso) as $alumno): ?>
<tr>
<td><?php echo $alumno->noCtrl; ?></td>
<td><?php echo $alumno->nombre." ".$alumno->primerApellido." ".$alumno->segundoApellido; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<th>NoCtrl</th>
<th>Nombre</th>
</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
<div class="modal fade" id="modal-eliminar">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h3 class="modal-title text-red">Eliminar proyecto</h3>
</div>
<div class="modal-body">
<h4>¿Está seguro que desea elimminar el proyecto?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<a href="?c=Proyecto&a=Eliminar" type="button" class="btn btn-danger">Eliminar</a>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- /.content -->
<div class="modal fade" id="modal-registrar">
<div class="modal-dialog">
<div class="modal-content">
<form action="?c=Curso&a=AsignaAlumno&idCurso=<?php echo $curso->idCurso ?>" method="POST">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h3 class="modal-title">Registrar alumno al curso</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label for="txtCodigoUsuario">Alumno</label>
<select name="noCtrl" type="text" class="form-control select2" id="selectMateria">
<option value="A">Seleccione el alumno a asignar</option>
<?php foreach($modelAlumno->Listar() as $alumno): ?>
<option value="<?php echo $alumno->noCtrl;?>"><?php echo $alumno->nombre." ".$alumno->primerApellido." ".$alumno->segundoApellido; ?></option>
<?php endforeach;?>
</select>
</div><!-- /.form-group -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Aceptar</a>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script><file_sep><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=1,initial-scale=1,user-scalable=1" />
<title>ITZ</title>
<!-- Custom CSS -->
<link rel="stylesheet" type="text/css" href="dist/css/login/style.css" />
<!-- Google Font -->
<link href="http://fonts.googleapis.com/css?family=Lato:100italic,100,300italic,300,400italic,400,700italic,700,900italic,900" rel="stylesheet" type="text/css">
<!-- Bootstrap Core CSS -->
<link type="text/css" rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<!-- Bootstrap Core JS -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<section class="container">
<section class="login-form">
<form method="post" action="?c=Login&a=Acceder" role="login">
<div>
<img width="50%" src="dist/img/logo.png" alt="" />
<h4>Accede con tu cuenta</h4>
</div>
<?php if(isset($error)){ ?>
<div class="alert alert-danger" style="height: 10px; margin-bottom: -10px; margin-top: -10px;">
<p style="margin-top:-20px;"><?php echo $error;?></p>
</div>
<?php } ?>
<input type="text" name="usuario" placeholder="Número de control" required class="form-control input-lg" style="color: black" />
<input type="password" name="password" placeholder="<PASSWORD>" required class="form-control input-lg" style="color: black"/>
<button type="submit" name="go" class="btn btn-lg btn-block btn-info">Acceder</button>
</form>
</section>
</section>
</body>
</html><file_sep><?php
require_once 'model/curso.php';
require_once 'model/docente.php';
require_once 'model/materia.php';
require_once 'model/alumno.php';
class CursoController{
private $model;
private $mensaje;
private $error;
public function __CONSTRUCT(){
$this->model = new Curso();
}
public function Index(){
$admin=true;
$cursos=true;
$page="view/cursos/index.php";
require_once 'view/index.php';
}
public function Crud(){
$modelMateria = new Materia();
$modelDocente = new Docente();
$admin=true;
$alumnos=true;
$page="view/cursos/curso.php";
require_once 'view/index.php';
}
public function Guardar(){
$curso= new Curso();
$curso->claveMateria=$_REQUEST['claveMateria'];
$curso->idDocente=$_REQUEST['idDocente'];
$curso->periodo=$_REQUEST['periodo'];
$curso->grupo=$_REQUEST['grupo'];
$horario1=$_REQUEST['horario1'];
$horario2=$_REQUEST['horario2'];
$curso->horario=$horario1." - ".$horario2;
$this->model->Registrar($curso);
$this->mensaje="El curso se ha registrado correctamente";
$this->Index();
}
public function Seleccion(){
$cursos2=true;
$page="view/cursos/seleccion.php";
require_once 'view/index.php';
}
public function Carga(){
$curso = new Curso();
$modelAlumno = new Alumno();
$curso->idCurso=$_REQUEST['idCurso'];
$info=$this->model->InfoCurso($curso->idCurso);
$cursos=true;
$page="view/cursos/carga.php";
require_once 'view/index.php';
}
public function AsignaAlumno(){
$curso= new Curso();
$noCtrl=$_REQUEST['noCtrl'];
$idCurso=$_REQUEST['idCurso'];
$this->model->AsignarAlumno($noCtrl,$idCurso);
$this->mensaje="El alumno se ha asignado correctamente al curso";
$this->Carga();
}
public function ActivarMateria(){
unset($_SESSION['claveMateria']);
unset($_SESSION['materia']);
unset($_SESSION['idCurso']);
$_SESSION['claveMateria']=$_REQUEST['claveMateria'];
$_SESSION['materia']=$_REQUEST['materia'];
$_SESSION['idCurso']=$_REQUEST['idCurso'];
$this->Seleccion();
}
public function DesactivarMateria(){
unset($_SESSION['claveMateria']);
unset($_SESSION['materia']);
unset($_SESSION['idCurso']);
$this->Seleccion();
}
public function Listas(){
$listas=true;
$page="view/cursos/listas.php";
require_once 'view/index.php';
}
public function RegistraCalificacion(){
$idCursoAlumno=$_REQUEST['idCursoAlumno'];
$suma=0;
for ($i=1; $i <= 5; $i++) {
$c='calificacion'.$i;
$calificacion=$_REQUEST[$c];
$suma=$suma+$calificacion;
$u='idUnidad'.$i;
$idUnidad=$_REQUEST[$u];
$this->model->RegistrarCalificacion($idUnidad,$calificacion,$idCursoAlumno);
}
$promedio=$suma/5;
$this->model->AsignaCalificacionFinal($promedio,$idCursoAlumno);
$this->mensaje="Se ha calificado correctamente al alumno";
$this->Listas();
}
}
?><file_sep>
<section class="content-header">
</section>
<section class="content">
<center><h1> Bienvenido al sistema de control escolar</h1>
<h4>Seleccione el curso con el que necesite trabajar</h4>
</center><br>
<?php foreach($this->model->listarCursos2($_SESSION['idDocente']) as $curso): ?>
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box <?php if(isset($_SESSION['idCurso'])){ if($curso->idCurso==$_SESSION['idCurso']){ ?>bg-green <?php }else{ ?> bg-aqua<?php }}else{ ?> bg-aqua <?php } ?>">
<div class="inner">
<h4><b><?php echo $curso->materia; ?></b></h4>
<p><b>Grupo</b> <?php echo $curso->grupo; ?></p>
<p><b>Horario</b> <?php echo $curso->horario; ?></p>
</div>
<div class="icon">
<i class="ion ion-stats-bars"></i>
</div>
<?php if(isset($_SESSION['idCurso'])){
if($curso->idCurso==$_SESSION['idCurso']){ ?>
<a href="?c=Curso&a=DesactivarMateria&claveMateria=<?php echo $curso->claveMateria; ?>&materia=<?php echo $curso->materia; ?>&idCurso=<?php echo $curso->idCurso; ?>" class="small-box-footer">Desactivar <i class="fa fa-check-circle-o"></i></a>
<?php }else{ ?>
<a href="?c=Curso&a=ActivarMateria&claveMateria=<?php echo $curso->claveMateria; ?>&materia=<?php echo $curso->materia; ?>&idCurso=<?php echo $curso->idCurso; ?>" class="small-box-footer">Activar <i class="fa fa-check-circle"></i></a>
<?php }}else{ ?>
<a href="?c=Curso&a=ActivarMateria&claveMateria=<?php echo $curso->claveMateria; ?>&materia=<?php echo $curso->materia; ?>&idCurso=<?php echo $curso->idCurso; ?>" class="small-box-footer">Activar <i class="fa fa-check-circle"></i></a>
<?php } ?>
</div>
</div>
<?php endforeach; ?>
</section>
<file_sep><?php
$noCtrl=$_REQUEST["noCtrl"];
$con=mysql_connect('localhost','root','') or die ("Problemas con a conexion a la base de datos");
$baseDatos=mysql_select_db('controlescolar') or die ("Problemas al seleccionar la base de datos");
$query=mysql_query("SELECT cursos.periodo,materias.materia,docentes.nombre, cursos_alumnos.calificacion from docentes, materias, cursos, cursos_alumnos, alumnos WHERE alumnos.noCtrl=$noCtrl AND alumnos.noCtrl=cursos_alumnos.noCtrl AND materias.claveMateria=cursos.claveMateria AND cursos.idCurso=cursos_alumnos.idCurso AND cursos.idDocente=docentes.idDocente",$con);
$response=array();
$num=mysql_num_rows($query);
while($fila = mysql_fetch_array($query)){
$row_array["succes"]=true;
$row_array["periodo"]=$fila['periodo'];
$row_array["materia"]=$fila['materia'];
$row_array["nombre"]=$fila['nombre'];
$row_array["calificacion"]=$fila['calificacion'];
array_push ($response, $row_array);
}
echo json_encode($response);
mysql_close();
?> | b94808db66755bbee5effa1a0ec7622d33b900bd | [
"PHP"
]
| 27 | PHP | isc570castro/controlEscolar | c0b1e3770a64226b8d32b90ab788418cdedc6d16 | 837483b723b3f2de450da852523d708a40faae0d |
refs/heads/master | <repo_name>seasonZhu/JLRoutesInSwift<file_sep>/JLRoutesInSwift/Route/RouteViewControllerProtocol.swift
//
// RouteViewControllerProtocol.swift
// JLRoutesInSwift
//
// Created by season on 2020/6/10.
// Copyright © 2020 lostsakura. All rights reserved.
//
import UIKit
/// 控制器关闭后回调数据
public typealias BackResult = (Any) -> Void
/// 支持路由的控制器所需要遵守的协议,该协议仅对UIViewController以及其子类有效
protocol RouteViewControllerProtocol {
/// 传入参数
var arguments: Any? {set get}
/// 路由打开方式 push or present
var modalType: Modal! {set get}
/// 路由关闭的回调数据
var result: BackResult? {set get}
}
<file_sep>/JLRoutesInSwift/Route/Modal.swift
//
// Modal.swift
// JLRoutesInSwift
//
// Created by season on 2020/6/10.
// Copyright © 2020 lostsakura. All rights reserved.
//
import Foundation
public enum Modal: String {
case push
case present
}
<file_sep>/README.md
# JLRoutesInSwift
JLRoutes在Swift中的使用
最近因为Flutter中的路由缘故,开始反向学习iOS中的路由了.
但是相比较Flutter中官方支持,并且在顺传值和反向传值的各种便利,iOS的路由都是第三方,而且跟多的场景适用于顺传值,但是对于反向传值,基本上是没有没可能的.
[JLRoutesDemo](https://github.com/destinyzhao/JLRoutesDemo)我通过这个Demo中学习思路,并进行简化与封装,通过协议的方式更好的进行顺传路由的功能.
并且原Demo中在openUrl函数中,会出现再次调用下面的方法:
```
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
```
回导致递归调用而进入死循环,而这种情况主要是在外部通过浏览器或者是通过其他App打开该App时候产生.
目前大概就是这么多,个人认为iOS中的路由框架,其实最好的使用场景是推送/网页打开/其他App打开.
我更新了在目标路由关闭后,回调数据的方法,并且行之有效,这样的话,路由顺传值与反向传值的功能都满足了,但是由于没有await与async,于是展示出来的就是闭包,理解起来不是特别好.
<file_sep>/JLRoutesInSwift/ViewController.swift
//
// ViewController.swift
// JLRoutesInSwift
//
// Created by season on 2020/6/10.
// Copyright © 2020 lostsakura. All rights reserved.
//
import UIKit
import Aspects
import EasySwiftHook
class ViewController: UIViewController {
private var token: EasySwiftHook.Token?
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
token?.cancelHook()
token = nil
}
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
}
private func setUpUI() {
let noArgumentPushButton = UIButton(frame: CGRect(x: 0, y:88, width: view.bounds.width, height: 44))
noArgumentPushButton.setTitle("无参数push", for: .normal)
noArgumentPushButton.backgroundColor = UIColor.lightGray
noArgumentPushButton.addTarget(self, action: #selector(noArgumentPush), for: .touchUpInside)
view.addSubview(noArgumentPushButton)
let argumentPushButton = UIButton(frame: CGRect(x: 0, y: 132, width: view.bounds.width, height: 44))
argumentPushButton.setTitle("传值push", for: .normal)
argumentPushButton.backgroundColor = UIColor.lightGray
argumentPushButton.addTarget(self, action: #selector(argumentPush), for: .touchUpInside)
view.addSubview(argumentPushButton)
let noArgumentPresentButton = UIButton(frame: CGRect(x: 0, y: 176, width: view.bounds.width, height: 44))
noArgumentPresentButton.setTitle("无参数present", for: .normal)
noArgumentPresentButton.backgroundColor = UIColor.lightGray
noArgumentPresentButton.addTarget(self, action: #selector(noArgumentPresent), for: .touchUpInside)
view.addSubview(noArgumentPresentButton)
let argumentPresentButton = UIButton(frame: CGRect(x: 0, y: 220, width: view.bounds.width, height: 44))
argumentPresentButton.setTitle("传值present", for: .normal)
argumentPresentButton.backgroundColor = UIColor.lightGray
argumentPresentButton.addTarget(self, action: #selector(argumentPresent), for: .touchUpInside)
view.addSubview(argumentPresentButton)
/// swift中已经不能使用Aspects
// let _ = try? UIApplication.shared.aspect_hook(#selector(UIApplication.shared.sendEvent(_:)), with: .positionBefore) { (aspectInfo: AspectInfo, event: UIEvent) -> Void in
// print(event)
// }
// let _ = try? UIViewController.aspect_hook(#selector(viewWillAppear(_:)), with: .positionBefore) { (aspectInfo: AspectInfo, animate: Bool) -> Void in
// print(aspectInfo.instance())
// }
// do {
// let token = try argumentPresentButton.aspect_hook(#selector(UIButton.setTitle(_:for:)), with: .positionBefore) { (aspectInfo: AspectInfo, title: String?, state: UIControl.State) -> Void in
// print(aspectInfo.instance())
// }
// } catch {
// print(error)
// }
do {
let hookClosure = { object, selector, event in
print("Nice to see you \(event)")
print("The object is: \(object)")
print("The selector is: \(selector)")
if let touch = event.allTouches?.first,
let view = touch.view {
print("Event view:\(view)")
} else {
object.sendEvent(event)
}
} as @convention(block) (UIApplication, Selector, UIEvent) -> Void
token = try hookBefore(targetClass: UIApplication.self, selector: #selector(UIApplication.sendEvent(_:)), closure: hookClosure)
} catch {
print(error)
}
}
}
extension ViewController {
@objc
func noArgumentPush() {
let url = URL(string: "JLRoutesInSwift://MouduleA/NextViewController/\(Modal.push.rawValue)")!
Route.open(noArguments: url) { (result) in
if let info = result as? String {
print("这是回调回来的数据\(info)")
}
}
}
@objc
func argumentPush() {
let arguments = "这里push传递的是一个字符串"
/// 一定要addingPercentEncoding JLRoutes不能传递中文汉字
let urlString = "JLRoutesInSwift://MouduleA/NextViewController/\(Modal.push.rawValue)/\(arguments)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = URL(string: urlString)!
Route.open(withArguments: url) { (result) in
if let info = result as? String {
print("这是回调回来的数据\(info)")
}
}
}
@objc
func noArgumentPresent() {
let url = URL(string: "JLRoutesInSwift://MouduleA/NextViewController/\(Modal.present.rawValue)")!
Route.open(noArguments: url) { (result) in
if let info = result as? String {
print("这是回调回来的数据\(info)")
}
}
}
@objc
func argumentPresent() {
let arguments = "这里present传递的是一个字符串"
let urlString = "JLRoutesInSwift://MouduleA/NextViewController/\(Modal.present.rawValue)/\(arguments)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = URL(string: urlString)!
Route.open(withArguments: url) { (result) in
if let info = result as? String {
print("这是回调回来的数据\(info)")
}
}
}
}
<file_sep>/JLRoutesInSwift/NextViewController.swift
//
// NextViewController.swift
// JLRoutesInSwift
//
// Created by season on 2020/6/10.
// Copyright © 2020 lostsakura. All rights reserved.
//
import UIKit
class NextViewController: UIViewController, RouteViewControllerProtocol {
var arguments: Any?
var modalType: Modal!
var result: BackResult?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
if let some = arguments as? String {
title = some
}else if arguments == nil {
title = modalType.rawValue
}
let backButton = UIButton(frame: CGRect(x: 0, y:88, width: view.bounds.width, height: 44))
backButton.setTitle("back", for: .normal)
backButton.backgroundColor = UIColor.lightGray
backButton.addTarget(self, action: #selector(backAction), for: .touchUpInside)
view.addSubview(backButton)
}
@objc
func backAction() {
if navigationController?.viewControllers.count ?? 0 > 1 {
let backVC = navigationController?.popViewController(animated: true)
print(type(of: backVC))
}else {
dismiss(animated: true)
}
result?("\(arguments == nil ? "no arguments": "with arguments")\n\("modal: " + modalType.rawValue)\ngo back Success")
}
}
<file_sep>/JLRoutesInSwift/Route/Route.swift
//
// Route.swift
// JLRoutesInSwift
//
// Created by season on 2020/6/10.
// Copyright © 2020 lostsakura. All rights reserved.
//
import Foundation
import JLRoutes
/// 无参数url的格式
private let routePatternNoArguments = "/:module/:target/:modal"
/// 有参数的url格式
private let routePatternWithArguments = "/:module/:target/:modal/:arguments"
/// 命名空间
private let nameSpace = Bundle.main.infoDictionary?["CFBundleExecutable"] as! String
/// 路由
public final class Route {
/// 打开无参路由
/// - Parameters:
/// - url: 路由网址
/// - result: 目标路由关闭后回调的数据
public static func open(noArguments url: URL, result: BackResult? = nil) {
Route.shared.open(url: url, hasParameters: false, result: result)
}
/// 打开有参路由
/// - Parameters:
/// - url: 路由网址
/// - result: 目标路由关闭后回调的数据
public static func open(withArguments url: URL, result: BackResult? = nil) {
Route.shared.open(url: url, hasParameters: true, result: result)
}
/// 初始化方法私有化
private init() {}
}
extension Route {
/// 私有单例
private static let shared = Route()
/// 打开URL
/// - Parameters:
/// - url: url
/// - hasParameters: 是否有参数
/// - result: 目标路由关闭后回调的数据
private func open(url: URL, hasParameters: Bool, result: BackResult? = nil) {
registerModule(hasParameters: hasParameters, result: result)
JLRoutes.global().routeURL(url)
}
/// 注册模块
/// - Parameters:
/// - hasParameters: 是否有参数
/// - result: 目标路由关闭后回调的数据
private func registerModule(hasParameters: Bool, result: BackResult? = nil) {
let routePattern = hasParameters ? routePatternWithArguments : routePatternNoArguments
JLRoutes.global().addRoute(routePattern) { return self.goTargetVC(parameters: $0, result: result) }
}
/// 去目标控制器
/// - Parameter:
/// - parameters: 参数
/// - result: 目标路由关闭后回调的数据
/// - Returns: Bool
private func goTargetVC(parameters: [String: Any]? = nil, result: BackResult? = nil) -> Bool {
if let target = parameters?["target"] as? String, // 获取目标控制器的字符串名称
let modal = parameters?["modal"] as? String, // 获取打开方式 present or push
let targetVC = createInstance(by: target) as? UIViewController, // 生成控制器
var routeVC = targetVC as? RouteViewControllerProtocol // 判断控制器是否遵守协议
{
routeVC.arguments = parameters?["arguments"]
routeVC.modalType = Modal(rawValue: modal)
routeVC.result = result
let currentVC = topViewController()
switch routeVC.modalType {
case .push:
currentVC?.navigationController?.pushViewController(targetVC, animated: true)
case .present:
let navi = UINavigationController(rootViewController: targetVC)
currentVC?.present(navi, animated: true)
case .none:
break
}
return true
}
return false
}
}
extension Route {
/// 通过字符串生成对应的控制器类,将泛型约束变窄,万一有一个非控制器类可以生成有正好遵守了RouteViewControllerProtocol,会出问题,改会原来的样子
/// - Parameter className: 类名字符串
/// - Returns: 类
private func createInstance<T: NSObject>(by className: String) -> T? {
guard let `class` = NSClassFromString(nameSpace + "." + className), let typeClass = `class` as? T.Type else {
return nil
}
return typeClass.init()
}
/// 获取顶层控制器
/// - Parameter rootVC: 根控制器
/// - Returns: 顶层控制器
private func topViewController(_ rootVC: UIViewController? = UIApplication.shared.windows.first?.rootViewController) -> UIViewController? {
if let nav = rootVC as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = rootVC as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = rootVC?.presentedViewController {
return topViewController(presented)
}
return rootVC
}
}
| de0d963397b04444717c27c7846dda685f85d0ee | [
"Swift",
"Markdown"
]
| 6 | Swift | seasonZhu/JLRoutesInSwift | 1f67ae1082224e304c33ae18cb52c68d606dfd10 | 24ab1c9219780b121b3c65d02181850e319c82aa |
refs/heads/master | <file_sep>#!/bin/sh
default_idle_time_min=3
trusted_idle_time_min=20
verbose_mode='false'
function show_help_and_exit {
echo "Usage: `basename $0` [options]"
echo ' -v verbose output'
echo ' -h show this help and exit'
}
case "$1" in
'') # nothing to do here
;;
-v) verbose_mode='true'
;;
-h) show_help_and_exit
exit 0
;;
*) show_help_and_exit 1>&2
exit 2
;;
esac
# Trusted ssid names go here, as arguments to fgrep
# remember: -e before each SSID and in single quotes if it contains spaces or shell meta characters
if ioreg -rn en0 | fgrep -q -e arabica -e 'Al<NAME>' -e willmwifi
then
idle_minutes=$trusted_idle_time_min
$verbose_mode && echo 'Trusted network found.' 1>&2
else
idle_minutes=$default_idle_time_min
$verbose_mode && echo 'Trusted network not found.' 1>&2
fi
current_idle_seconds=`defaults -currentHost read com.apple.screensaver idleTime`
idle_seconds=`expr 60 '*' $idle_minutes`
$verbose_mode && echo "Current idle time: ${current_idle_seconds}sec" 1>&2
if [ "$current_idle_seconds" -eq "$idle_seconds" ]
then
$verbose_mode && echo "Idle time already set to ${idle_seconds}sec" 1>&2
else
$verbose_mode && echo "Setting idle time to ${idle_seconds}sec" 1>&2
defaults -currentHost write com.apple.screensaver idleTime $idle_seconds
exit $?
fi
exit 0
<file_sep>This script checks every five minutes (configurable) to see if you're on a WiFi network that you’ve indicted as being “trusted”.
* If you are, it changes the value of “Start after” for your screensaver to be n minutes (20 by default, but you can edit that).
* If you are not on a trusted WiFi network it will set “Start after” to be a different time (2 min by default, but you can edit that too).
Probably you want to pair this with having “Require password X seconds after sleep or screensaver begins”. Or maybe you just really like your screen saver?
## Installation
* Download the latest files from [here](https://github.com/edwardloveall/autolock/releases).
* Put `autolock.sh` anywhere you like, but remember where you put it.
* Inside `autolock.sh`:
1. line 3 & 4: alter theses times if you’d like
1. line 28: add the name(s) of trusted SSIDs
* In `com.edwardloveall.autolock.plist`, replace the `path/to/autolock.sh` with the path to the script in the previous step.
* Move the launchd plist to `~/Library/LaunchAgents`. If you don't have the `LaunchAgents` folder, you can just create it. Spelling and capitalization are important.
* Install and start the launchd job with `launchctl load -w ~/Library/LaunchAgents/com.edwardloveall.autolock.plist`
## Troubleshooting
You can run the script with a `-v` option for verbose output like so: `/bin/sh path/to/autolock.sh -v`
---
Read more about this in my blog post: http://blog.edwardloveall.com/post/120467537407/automatically-lock-your-computer-based-on-wi-fi
| a01ee53bda26ebb878126061955f71e7bfa68a59 | [
"Markdown",
"Shell"
]
| 2 | Shell | roosto/autolock | 25b05f80e1511c582c7fe4eed0c65c9c78d78967 | 9ea07cdb54cf5c67e423cceaa046cbc44f1a67ab |
refs/heads/main | <repo_name>shankarbtn/reactjs-crud-mern-app<file_sep>/client/src/store/item-context.js
import { useState, createContext } from 'react';
import Axios from "axios";
import EditForm from '../components/EditForm';
const ItemContext = createContext({
itemsList: [],
totalItemsList: 0,
isModelOpen: false,
getItem: () => {},
addItem: () => {},
editItem: (id) => {},
updateItem: (id) => {},
deleteItem: (id) => {}
});
export function ItemContextProvider(props) {
const SERVER_HTTP_URL = "http://localhost:3001/";
const SERVER_ACTION_INSERT = 'insert';
const SERVER_ACTION_READ = "read";
const SERVER_ACTION_UPDATE = "update";
const SERVER_ACTION_DELETE = "delete";
const [items, setItem] = useState([]);
const [isModelOpen, setIsModelOpen] = useState(false);
async function getItemHandler() {
try {
await Axios.get(SERVER_HTTP_URL + SERVER_ACTION_READ)
.then(function (response) {
console.log('server response >>> '+ response.data);
setItem(response.data);
})
.catch((err) => {
console.error('Read api error:', err);
});
}catch(err) {
console.log(err);
}
}
async function addItemHandler(formData) {
console.log('server >>> '+ JSON.stringify(formData));
await Axios.post(SERVER_HTTP_URL + SERVER_ACTION_INSERT, formData)
.then(function (response) {
console.log(response);
document.getElementById('formSuccess').innerHTML = response.data;
document.getElementById('formSuccess').style.display = 'block';
})
.catch(function (error) {
console.log(error);
document.getElementById('formError').innerHTML = error;
document.getElementById('formError').style.display = 'block';
});
}
async function editItemHandler(id) {
setIsModelOpen(true);
return <EditForm />
}
async function updateItemHandler(id) {
await Axios.get(SERVER_HTTP_URL + SERVER_ACTION_UPDATE, {id: id})
.then(res => {
console.log(res);
console.log(res.data);
})
}
async function deleteItemHandler(id) {
await Axios.delete(SERVER_HTTP_URL + SERVER_ACTION_DELETE+`/${id}`)
.then(res => {
console.log(res);
console.log(res.data);
})
}
const context = {
itemsList: items,
totalItemsList: items ? items.length : 0,
isModelOpen: isModelOpen,
getItem: getItemHandler,
addItem: addItemHandler,
editItem: editItemHandler,
updateItem: updateItemHandler,
deleteItem: deleteItemHandler
};
return (
<ItemContext.Provider value={context}>
{props.children}
</ItemContext.Provider>
);
}
export default ItemContext;<file_sep>/client/src/components/EditForm.js
import { useContext } from "react";
import Modal from '../ui/Modal';
import ItemContext from "../store/item-context";
import classes from '../components/UserForm.module.css';
export default function EditForm() {
//accessing context data
const itemCtx = useContext(ItemContext);
const updateItemHandler = () => {};
const closeModaleHandler = () => {};
let content = null;
if(itemCtx.isModelOpen) {
content = <Modal>
<form className={classes.form}>
<div className={classes.control}>
<label htmlFor='update-food-name'>Food Name</label>
<input type='text' id='update-food-name' placeholder='Enter your food name'/>
</div>
<div className={classes.control}>
<label htmlFor='update-food-type'>Food Type</label>
<input type='text' id='update-food-type' placeholder='Enter Food Type'/>
</div>
<div className={classes.actions}>
<button onClick={updateItemHandler}>Update</button>
<button onClick={closeModaleHandler}>Close</button>
</div>
<div className={classes.formInfo}>
<span className={classes.formError} id='update-formError'></span>
<span className={classes.formSuccess} id='update-formSuccess'></span>
</div>
</form>
</Modal>;
}
return (
{content}
);
}<file_sep>/client/src/components/UserForm.js
import React, { useRef,useContext } from 'react';
import ItemContext from "../store/item-context";
import classes from './UserForm.module.css';
export default function UserFrom() {
//accessing context data
const itemCtx = useContext(ItemContext);
const foodNameRef = useRef();
const foodTypeRef = useRef();
const formSubmitHandler = (e) => {
e.preventDefault();
const foodNameRefValue = foodNameRef.current.value;
const foodTypeRefValue = foodTypeRef.current.value;
let hasError = false, errorMessage = '';
if(!foodNameRefValue) {
hasError = true;
errorMessage = 'Enter Food Name';
} else if(!foodTypeRefValue) {
hasError = true;
errorMessage = 'Enter Food Type';
}
if(hasError) {
console.log(errorMessage);
document.getElementById('formError').innerHTML = errorMessage;
document.getElementById('formError').style.display = 'block';
document.getElementById('formSuccess').style.display = 'none';
} else {
hasError = false;
errorMessage = '';
document.getElementById('formSuccess').style.display = 'none';
document.getElementById('formError').style.display = 'none';
const formData = {
foodName: foodNameRefValue,
foodType: foodTypeRefValue,
dateAdded: new Date()
}
saveFormData(formData);
e.target.reset();
}
}
const saveFormData = (formData) => {
console.log(formData);
itemCtx.addItem();
};
return (
<section className={classes.formContainer} onSubmit={formSubmitHandler}>
<form className={classes.form}>
<div className={classes.control}>
<label htmlFor='food-name'>Food Name</label>
<input type='text' id='food-name' ref={foodNameRef} placeholder='Enter your food name'/>
</div>
<div className={classes.control}>
<label htmlFor='food-type'>Food Type</label>
<input type='text' id='food-type' ref={foodTypeRef} placeholder='Enter Food Type'/>
</div>
<div className={classes.formInfo}>
<span className={classes.formError} id='formError'></span>
<span className={classes.formSuccess} id='formSuccess'></span>
</div>
<div className={classes.actions}>
<button>Add Food Item</button>
</div>
</form>
</section>
)
}
<file_sep>/client/src/ui/Modal.js
import { useContext } from "react";
import ItemContext from "../store/item-context";
import classes from '../ui/Modal.module.css';
export default function Modal(props) {
//accessing context data
const itemCtx = useContext(ItemContext);
return (
<div className={classes.backdrop} style={(itemCtx.isModelOpen) ? {display:'block'} : {display:'block'}}>
<div className={classes.modal}>
{props.children}
</div>
</div>
);
}<file_sep>/README.md
# reactjs-crud-mern-app
CRUD application using the MERN stack. MERN is an acronym for MongoDB, ExpressJS, ReactJS, and NodeJS
| 5b19faac5a3aceeb138cc107e203392f4653558a | [
"JavaScript",
"Markdown"
]
| 5 | JavaScript | shankarbtn/reactjs-crud-mern-app | 6d43cf710cd185488f9ec0c3556c5c87d7956d6f | 911b0ef254dbd7581d6b5e6e647c5607a844d92d |
refs/heads/main | <file_sep># Literature-Analysis-System-Based-on-Academic-Search-Engine
爬取Bing学术搜索引擎,文件计量分析</br>
科研工作者在开始研究某一领域或方向之前,通常需要使用学术搜索引擎搜索大量的学术文献用来了解、学习目标方向。
只有当有效文献阅读到一定数量时,才会产生自己的思路和方法,从而进行细化,做出比较规范的提纲去研究。
而面对繁琐、大量的论文阅读工作,往往会浪费大量时间精力,为更高效快速的从海量学术论文中挖掘出潜在规律,提出一种基于学术搜索引擎的文献分析系统。
该系统使用Python语言设计,Requests编写爬虫,PySide2设计GUI,通过使用者输入目标关键词后,
实时爬取Bing学术搜索引擎搜索到的数据,将题目、作者、发表时间、论文机构、摘要、被引用数大量数据汇总,使用文献计量分析法分析,找出相关规律,
使用多种图表进行可视化,为学者展开科研工作提供更明确的方向,进行深入的研究。
<file_sep>jieba==0.38
matplotlib==2.2.3
numpy==1.15.1
wordcloud==1.5.0
beautifulsoup4==4.9.3
PySide2==5.15.2
res==0.1.7
<file_sep># coding:utf-8
#import res
import math
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import Slot, QUrl, QSize, QFile, QTextStream, QThread, Signal, QRect
from PySide2.QtGui import QIcon, QPainterPath, QPainter, QBrush, QColor, QPen
import sys
from PySide2.QtWidgets import QTableWidget, QProgressBar, QTextBrowser, QHeaderView, QTableWidgetItem, \
QGraphicsDropShadowEffect
import re
import log
import time
import jieba
from urllib import parse
from urllib import request
from bs4 import BeautifulSoup
import threading
from wordcloud import WordCloud
from collections import Counter
import numpy as np
# import matplotlib.pylab as plt
import matplotlib
from matplotlib import pyplot as plt
class MainUi(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.setFixedSize(1000, 700) # 1000,700
self.main_widget = QtWidgets.QWidget() # 创建窗口主部件
self.left_widget = QtWidgets.QWidget() # 创建左侧部件
self.left_widget.setObjectName('left_widget')
self.left_widget.setFixedSize(300,700)
self.right_widget = QtWidgets.QWidget() # 创建右侧部件
self.right_widget.setObjectName('right_widget')
self.right_widget.setFixedSize(700, 676)
self.right_up_widget = QtWidgets.QWidget()
self.right_up_widget.setFixedSize(700,20)
# 左侧菜单栏
# 爬取部分
self.left_crawl_label = QtWidgets.QPushButton("信息爬取")
self.left_crawl_label.setObjectName('left_label')
self.left_keyword_label = QtWidgets.QLabel(chr(0xf002) + ' ' + '关键词')
self.left_keyword_search_input = QtWidgets.QLineEdit()
self.left_pagenum_label = QtWidgets.QLabel(chr(0xf002) + ' ' + '搜索页数')
self.left_pagenum_search_input = QtWidgets.QLineEdit()
self.left_crawl_button = QtWidgets.QPushButton("开始爬取")
self.left_crawl_button.setObjectName('left_button_spider')
self.left_stopcrawl_button = QtWidgets.QPushButton("停止爬取")
self.left_stopcrawl_button.setObjectName('left_button_spider')
# 分析部分
self.left_analysize_label = QtWidgets.QPushButton("数据分析")
self.left_analysize_label.setObjectName('left_label')
self.left_title_analyse_button = QtWidgets.QPushButton("题目关联")
self.left_title_analyse_button.setObjectName('left_button')
self.left_author_button = QtWidgets.QPushButton("相关学者")
self.left_author_button.setObjectName('left_button')
self.left_researchYear_button = QtWidgets.QPushButton("研究趋势")
self.left_researchYear_button.setObjectName('left_button')
self.left_publisher_button = QtWidgets.QPushButton("相关机构")
self.left_publisher_button.setObjectName('left_button')
self.left_quoteNum_button = QtWidgets.QPushButton("引用数")
self.left_quoteNum_button.setObjectName('left_button')
self.left_abstract_button = QtWidgets.QPushButton("摘要关键")
self.left_abstract_button.setObjectName('left_button')
# 右侧显示栏
self.right_close = QtWidgets.QPushButton("") # 关闭按钮
self.right_mini = QtWidgets.QPushButton("") # 最小化按钮
self.right_table = QTableWidget(self) # 表格栏
self.right_progressbar = QProgressBar(self) # 进度条
self.right_browser = QTextBrowser(self)#信息栏
self.crawl_thread = CrawlThread()#实例化一个对象
self.layout_init()
self.btn_function_init()
self.table_init()
self.setStytle()
self.crawl_init()
def layout_init(self):
#总布局
self.main_layout = QtWidgets.QGridLayout() # 创建主窗口布局
self.main_layout.setContentsMargins(0, 0, 0, 0)
self.main_widget.setLayout(self.main_layout) # 设置主窗口布局
self.left_layout = QtWidgets.QGridLayout() # 创建左侧部件的网格布局层
self.left_layout.setContentsMargins(0, 0, 0, 0)
self.left_widget.setLayout(self.left_layout) # 设置左侧部件布局为网格
self.right_layout = QtWidgets.QGridLayout()
self.right_widget.setLayout(self.right_layout) # 设置右侧部件布局为网格
# self.right_layout.setContentsMargins(0, 0, 0, 0)
self.right_up_layout = QtWidgets.QGridLayout()
self.right_up_widget.setLayout(self.right_up_layout)
self.right_up_layout.setContentsMargins(0, 0, 0, 0)
self.main_layout.addWidget(self.left_widget, 0, 0, 12, 4) # 左侧部件在第0行第0列,占8行3列 1000
self.main_layout.addWidget(self.right_up_widget,0,5,1,10) #左上栏
self.main_layout.addWidget(self.right_widget, 1,5, 11, 10) # 右侧部件在第0行第3列,占8行9列
# 左侧布局分布
# 爬取部分
self.left_layout.addWidget(self.left_crawl_label, 1, 0, 1, 3)
self.left_layout.addWidget(self.left_keyword_label, 2, 0, 1, 2)
self.left_layout.addWidget(self.left_keyword_search_input, 2, 2, 1, 1)
self.left_layout.addWidget(self.left_pagenum_label, 3, 0, 1, 2)
self.left_layout.addWidget(self.left_pagenum_search_input, 3, 2, 1, 1)
self.left_layout.addWidget(self.left_crawl_button, 4, 0, 1, 4)
self.left_layout.addWidget(self.left_stopcrawl_button,5,0,1,4)
# 分析部分
self.left_layout.addWidget(self.left_analysize_label, 6, 0, 1, 3)
self.left_layout.addWidget(self.left_title_analyse_button, 7, 0, 1, 3)
self.left_layout.addWidget(self.left_author_button, 8, 0, 1, 3)
self.left_layout.addWidget(self.left_researchYear_button, 9, 0, 1, 3)
self.left_layout.addWidget(self.left_publisher_button, 10, 0, 1, 3)
self.left_layout.addWidget(self.left_quoteNum_button, 11, 0, 1, 3)
self.left_layout.addWidget(self.left_abstract_button, 12, 0, 1, 3)
self.right_up_layout.addWidget(self.right_mini, 0,2,1,1)
self.right_up_layout.addWidget(self.right_close, 0,3,1,1)
self.right_layout.addWidget(self.right_table)
self.right_layout.addWidget(self.right_progressbar)
self.right_layout.addWidget(self.right_browser)
self.setCentralWidget(self.main_widget) # 设置窗口主部件
def btn_function_init(self):
#left
self.left_crawl_button.setCursor(QtCore.Qt.PointingHandCursor)#鼠标箭头变为手势
self.left_stopcrawl_button.setCursor(QtCore.Qt.PointingHandCursor)
self.left_title_analyse_button.setCursor(QtCore.Qt.PointingHandCursor)
self.left_author_button.setCursor(QtCore.Qt.PointingHandCursor)
self.left_researchYear_button.setCursor(QtCore.Qt.PointingHandCursor)
self.left_publisher_button.setCursor(QtCore.Qt.PointingHandCursor)
self.left_quoteNum_button.setCursor(QtCore.Qt.PointingHandCursor)
self.left_abstract_button.setCursor(QtCore.Qt.PointingHandCursor)
self.left_crawl_button.clicked.connect(lambda: self.btn_slot(self.left_crawl_button))
self.left_stopcrawl_button.clicked.connect(lambda: self.btn_slot(self.left_stopcrawl_button))
#数据分析
self.left_title_analyse_button.clicked.connect(lambda: self.CountName(6,'题目关联领域频率最高'))
self.left_author_button.clicked.connect(lambda: self.CountName(1,'发表文章的作者'))
self.left_publisher_button.clicked.connect(lambda: self.CountName(2,'出版设出版'))
self.left_quoteNum_button.clicked.connect(lambda: self.QuoteNum())
self.left_abstract_button.clicked.connect(lambda:self.makeWordCloud(self.splitword()))
self.left_researchYear_button.clicked.connect(lambda:self.PublishTime())
#right
self.right_close.clicked.connect(lambda: self.on_pushButton_clicked_close())#关闭窗口
self.right_close.setCursor(QtCore.Qt.PointingHandCursor)
self.right_mini.clicked.connect(lambda: self.on_pushButton_2_clicked_min())#最小化窗口
self.right_mini.setCursor(QtCore.Qt.PointingHandCursor)
self.right_progressbar.setRange(0, 100) # 进度条范围设置为100
self.right_progressbar.setValue(0)
def btn_slot(self, btn): # 将按钮的槽函数和clicked信号连接起,2、用开始、停止按钮控制线程,将线程开始停止放在槽函数中
# self.btn_sound.play() # 播放开始的声音
if btn == self.left_crawl_button:
self.right_browser.clear() # 每次点击爬取按钮,都先调用clear()方法清空log_browser日志显示框
self.right_browser.append('<font color="red">开始爬取</font>')
self.right_table.clearContents()
self.right_table.setRowCount(0)
# self.start_btn.setEnabled(False)
# self.stop_btn.setEnabled(True)
# self.save_combobox.setEnabled(False)
# 输入框
global subject
global pageNum
subject = self.left_keyword_search_input.text()
pageNum = self.left_pagenum_search_input.text()
self.right_browser.append('搜索的关键词为:'+subject)
self.crawl_thread.start() # start()方法来启动线程
else:
self.right_browser.append('<font color="red">停止爬取</font>')
# self.stop_btn.setEnabled(False)
# self.start_btn.setEnabled(True)
# self.save_combobox.setEnabled(True)
self.crawl_thread.terminate() # terminate()终止线程
def crawl_init(self):
# self.crawl_thread.finished_signal.connect(self.finish_slot)
self.crawl_thread.log_signal.connect(self.set_log_slot)
self.crawl_thread.result_signal.connect(self.set_table_slot)
def table_init(self):
self.right_table.setColumnCount(7) # 设置表格控件的列数
self.right_table.setHorizontalHeaderLabels(['题名', '作者', '来源', '发表时间', '被引数', '摘要','相关领域']) # 将表格割裂标题设置成要爬取的数据字段名称
self.right_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 将标题栏各列的宽度模式设置为拉伸
def set_table_slot(self, title, rating, people_num, author_info, pub_info, year_info,caption_filed):
row = self.right_table.rowCount()
self.right_table.insertRow(row)
self.right_table.setItem(row, 0, QTableWidgetItem(title))
self.right_table.setItem(row, 1, QTableWidgetItem(rating))
self.right_table.setItem(row, 2, QTableWidgetItem(people_num))
self.right_table.setItem(row, 3, QTableWidgetItem(author_info))
self.right_table.setItem(row, 4, QTableWidgetItem(pub_info))
self.right_table.setItem(row, 5, QTableWidgetItem(year_info))
self.right_table.setItem(row, 6, QTableWidgetItem(caption_filed))
percentage = int(((row + 1) / (int(pageNum) * 10)) * 100)
self.right_progressbar.setValue(percentage)
#
# if self.right_progressbar.value() == 100:
# self.finish_sound.play()
def set_log_slot(self, new_log):
self.right_browser.append(new_log)
#****************左侧数据分析按钮功能***********************************************************************************
def splitword(self):
txt = ''
for row in range(self.right_table.rowCount()):
txt += self.right_table.item(row, 5).text().lower() #读取文本
for ch in [' a ', ' b ', ' c ', ' d ', ' e ', ' f ', ' g ', ' h ', ' i ', ' j ', ' k ', ' l ', ' m ', ' n ',
' o ', ' p ', ' q ', ' r ', ' s ', ' t ', ' u ', ' v ', ' w ', ' x ', ' y ', ' z ',
'has', 'but', 'have', 'been', 'this', 'the','and','as','is','that','for','which','The','while','one','two','abstract','Abstract','with','are','can','from','what'
]:
if ch in txt:
txt = txt.replace(ch, "")
seg_list = jieba.cut(txt)
c = Counter()
result = {}
for x in seg_list:
if len(x) > 2 and x != '\r\n':
c[x] += 1
for (k, v) in c.most_common():
result[k] = v # 放到字典中,用于生成词云的源数据
return result
def makeWordCloud(self,txt):
x, y = np.ogrid[:300, :500]
mask = (x - 150) ** 2 + (y - 150) ** 2 > 150 ** 2
mask = 255 * mask.astype(int)
wc = WordCloud(background_color="white",
max_words=500,
mask=mask,
repeat=True,
width=1000,
height=1000,
scale=15, # 这个数值越大,产生的图片分辨率越高,字迹越清晰
font_path="C:\Windows\Fonts\Arial.TTF")
# print(txt)
wc.generate_from_frequencies(txt)
# wc.to_file(‘abc.png‘)
plt.axis("off")
plt.imshow(wc, interpolation="bilinear")
plt.show()
def CountName(self,num_col,stranalyse):#作者是1,出版社是2,关联领域是6
text,old_text ='',''
outnum = 0
for row in range(self.right_table.rowCount()):
old_text=self.right_table.item(row, num_col).text().strip()
if len(old_text) <1:
continue
else:
text += old_text
if int(num_col) ==6:
text += "|"
else:
text +='·'
if int(num_col) ==6:
words = text.split('|')
else:
words = text.split('·')
# words = re.split('·|',text)
for numi in words:
if len(numi)<1:
words.remove(numi)
c = Counter(words)
self.right_browser.append(stranalyse+'数量前十名是')
while outnum<10:
self.right_browser.append(str(c.most_common(10)[outnum][0]))#堆问题解决top-n
self.right_browser.append("数量:"+str(c.most_common(10)[outnum][1]))
outnum += 1
if int(num_col) == 6:
self.KeyCakePic(c)
elif int(num_col) ==1:
self.Author_H(c)
elif int(num_col)==2:
self.Author_H(c)
def KeyCakePic(self,c):
values = []
labels = [] # 绘图显示的标签
outnum = 0
while outnum<10:
labels.append(str(c.most_common(10)[outnum][0]))#堆问题解决top-n
values.append(int(c.most_common(10)[outnum][1]))
outnum += 1
colors = ['#1F92CE', '#FB9901', '#FA5307', '#D0EA2C']
# explode = [0, 0.1, 0] # 旋转角度
plt.figure(figsize=(20, 12), dpi=150)
plt.title("Related Fields", fontsize=25) # 标题
plt.pie(values, labels=labels, colors=colors,
startangle=180,
radius=5,
textprops={'fontsize':18,'color':'k'},
shadow=True,
autopct='%1.1f%%')
# for t in l_text:
# t.set_size = (50)
# for t in p_text:
# t.set_size = (50)
plt.axis('equal')
plt.show()
def Author_H(self, c):
x_pic = []
y_pic = [] # 绘图显示的标签
outnum = 0
while outnum<10:
x_pic.append(str(c.most_common(10)[outnum][0]))#堆问题解决top-n
y_pic.append(int(c.most_common(10)[outnum][1]))
outnum += 1
plt.figure(figsize=(20, 10), dpi=200)
# 柱子总数
N = 10
index = np.arange(N)
# 柱子的宽度
width = 0.45
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
colors = ['#FF0000','#FF7F00','#FFFF00','#00FF00','#00FFFF','#0000FF','#8B00FF']
p2 = plt.bar(x_pic, y_pic, width, label="num", color=colors)
plt.xlabel('Name')
plt.ylabel('Number')
plt.title('Name-Number')
plt.legend(loc="upper right")
plt.show()
def PublishTime(self):
datevalue,datahighnum =[],[]
for row in range(self.right_table.rowCount()):
leixing = self.right_table.item(row, 3).text()
if len(leixing) == 0:
continue
else:
leixing = int(leixing)
if leixing not in datevalue and leixing:
datevalue.append(leixing)
datahighnum.append(1)
indexnum = datevalue.index(leixing)
datahighnum[indexnum] = datahighnum[indexnum] + 1
together = zip(datevalue, datahighnum)
together2 = sorted(together, key=lambda x: x[0])
x_value, y_value = zip(*together2)
# 根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10, 6))
# 实参alpha指定颜色的透明度,0表示完全透明,1(默认值)完全不透明
plt.plot(x_value,y_value,c='red', alpha=0.5)
# plt.plot(dates,lows,c='blue',alpha=0.5)
# 给图表区域填充颜色
# plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1)
plt.title('Publication time distribution', fontsize=24)
plt.xlabel('Year', fontsize=16)
plt.ylabel('Number of papers', fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
# 绘制斜的日期标签
fig.autofmt_xdate()
plt.show()
def QuoteNum(self):
title_tabletext, author_tabletext,quotenum_table = [], [],[]
for row in range(self.right_table.rowCount()):
title_tabletext.append(self.right_table.item(row,0).text())#题目
author_tabletext.append(self.right_table.item(row,1).text()) #作者
quotenum_table_old = self.right_table.item(row,4).text()
if quotenum_table_old is '':
quotenum_table_num = int(0)
else:
quotenum_table_num=int(quotenum_table_old)
quotenum_table.append(quotenum_table_num)#被引数
together1 = zip(title_tabletext,author_tabletext,quotenum_table)
together2 = sorted(together1,key=lambda x:x[2],reverse=True)
d = {}
x_value,y_value,z_value = zip(*together2)
for rownum in range(0,5):
self.right_browser.append('题目为:'+str(x_value[rownum])+'\n作者:'+ str(y_value[rownum])+'\n引用数:'+str(z_value[rownum]))
def pointpic(self):
x_values = []
y_values = []
for row in range(self.table.rowCount()):
marknum = float(self.table.item(row, 1).text())
peonum = float(self.table.item(row,2).text())
x_values.append(marknum)
y_values.append(peonum)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.scatter(x_values, y_values, s=50)
# 设置图表标题并给坐标轴加上标签
plt.title('评分和评论数的相关性', fontsize=24)
plt.xlabel('JudgeMark', fontsize=14)
plt.ylabel('Peoplenumber', fontsize=14)
# 设置刻度标记的大小
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
def setStytle(self):
self.right_close.setFixedSize(15, 15) # 设置关闭按钮的大小
self.right_mini.setFixedSize(15, 15) # 设置最小化按钮大小
self.right_close.setIcon(QIcon('res/delete.svg'))
self.right_mini.setIcon(QIcon('res/min.svg'))
#关闭和最小化栏
self.right_close.setStyleSheet('''
QPushButton:hover{background:red;border-radius:10px}''')
self.right_mini.setStyleSheet('''
QPushButton:hover{background:rgb(0,255,0);border-radius:10px}''')
self.right_up_widget.setStyleSheet('''
QWidget{background:rgb(240,240,240);border-top-right-radius:10px;}''')
#右侧
self.right_widget.setStyleSheet('''
QWidget{background:rgb(240,240,240);}
QTableWidget{background:rgb(255,255,255);border-radius:10px;}
QProgressBar{background:rgb(255,255,255);border-radius:10px; text-align:center;color: black;}
QProgressBar::chunk {background: rgb(230, 9, 42);border-radius:10px;}
QTextBrowser{background:rgb(255,255,255);border-radius:10px;}
QHeaderView{border: none;border-bottom: 3px solid #532A2A;background: #BC8F8F;min-height: 30px;color:#532A2A;font-size:16px;font-family:"Helvetica Neue", Helvetica, Arial, sans-serif}
QHeaderView::section:horizontal{border: none;color: white;font-weight:800;background: transparent;}
QHeaderView::section:vertical{border: none;color: white;background: transparent;}
QHeaderView::section:horizontal:hover{background: rgb(230, 39, 39);}
QHeaderView::section:horizontal:pressed{background: rgb(255, 0, 0);}
QHeaderView::section:vertical:hover{background: rgb(230, 39, 39);}
QHeaderView::section:vertical:pressed{background: rgb(255, 0, 0);
}''')
self.left_widget.setStyleSheet('''
QWidget#left_widget{background:gray;
border-top:1px solid gray;
border-bottom:1px solid gray;
border-left:1px solid gray;
border-top-left-radius:10px;
border-bottom-left-radius:10px;
}
QPushButton{border:none;color:white;}
QPushButton#left_label{
border:none;
border-bottom:1px solid white;
font-size:22px;
font-weight:800;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
QPushButton#left_button:hover{border-left:5px solid red;font-weight:700;}
QPushButton#left_button_spider{font-size:18px;font-weight:700;}
QPushButton#left_button_spider:hover{
border-left:5px solid red;
font-size:20px;
font-weight:750;
color:black;
}
QLineEdit{
border:1px solid gray;
width:300px;
border-radius:10px;
padding:2px 4px;
}
QLabel{
border:none;
color:white;
font-size:16px;
font-weight:500;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}''')
# self.setWindowOpacity(0.98) # 设置窗口透明度
self.setAttribute(QtCore.Qt.WA_TranslucentBackground) # 设置窗口背景透明
self.setWindowFlag(QtCore.Qt.FramelessWindowHint) # 隐藏边框
self.shadow = QGraphicsDropShadowEffect()#设置阴影
self.shadow.setOffset(0,0)
self.shadow.setColor(QColor("#444444"))
self.shadow.setBlurRadius(30)
self.main_widget.setGraphicsEffect(self.shadow)
self.main_layout.setMargin(3)
self.main_layout.setSpacing(0)
# 拖动无边框窗口
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.m_flag = True
self.m_Position = event.globalPos() - self.pos() # 获取鼠标相对窗口的位置
event.accept()
self.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor)) # 更改鼠标图标
def mouseMoveEvent(self, QMouseEvent):
if QtCore.Qt.LeftButton:
self.move(QMouseEvent.globalPos() - self.m_Position) # 更改窗口位置
QMouseEvent.accept()
def mouseReleaseEvent(self, QMouseEvent):
self.m_flag = False
self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
@Slot()
def on_pushButton_clicked_close(self): # 关闭
self.close()
@Slot()
def on_pushButton_2_clicked_min(self): # 最小化
self.showMinimized()
logger = log.Logger().get_logger()
Headers = {
"Upgrade-Insecure-Requests": "1",
"Connection": "keep-alive",
"Cache-Control": "max-age=0",
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,la;q=0.7,pl;q=0.6",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
}
Base_URL = "https://cn.bing.com/academic/search?"
class CrawlThread(QThread): # 用pyqt5时将线程类改成QThread
finished_signal = Signal()
log_signal = Signal(str)
result_signal = Signal(str, str, str, str, str, str,str)
def __init__(self):
super(CrawlThread, self).__init__()
def download_html(self, url, retry, delay):
try:
req = request.Request(url=url, headers=Headers)
resp = request.urlopen(req, timeout=5)
# req = urllib.request.Request(url=url, headers=Headers)
# html = urllib.request.urlopen(req).read().decode('utf-8')
if resp.status != 200:
logger.error('url open error. url = {}'.format(url))
html_doc = resp.read()
if html_doc == None or html_doc.strip() == '':
logger.error('NULL html_doc')
return html_doc
except Exception as e:
logger.error("failed and retry to download url {} delay = {}".format(url, delay))
if retry > 0:
time.sleep(delay)
retry -= 1
return self.download_html(url, retry, delay)
pattern = re.compile('[0-9]+') # 匹配字符串中是否含有数字
def main_spider(self, keyword, pagenum):
query = {}
query['q'] = keyword
pagenum = int(pagenum)
for i in range(pagenum):
pagenum = 1 + i * 10
query['first'] = str(pagenum)
url = Base_URL + parse.urlencode(query)
html = self.download_html(url, 5, 3)
bs = BeautifulSoup(html, "html.parser")
list_soup = bs.find('ol', {'id': 'b_results'})
for artical_info in list_soup.find_all('li', {'class': 'aca_algo'}):
title,author_name, pubYear, publisher, citedNum,abstract,caption_filed = '', '', '','','','',''
try:
title = artical_info.find('h2').get_text()
except:
pass
try:
author_name = artical_info.find('div', {'class': 'caption_author'}).get_text()
except:
pass
try: # 输出时间,出版社,被引数
publish_message = artical_info.find('div', {'class': 'caption_venue'}).get_text()
nowmessage = re.split('[·|]', publish_message)
if len(nowmessage) == 3: # 表示有出版社,出版时间,被引数
pubYear = nowmessage[0].strip()
publisher = nowmessage[1].strip()
citedNum = ''.strip().join(list(filter(lambda ch: ch in '0123456789.-', nowmessage[2])))
elif len(nowmessage) == 2:
match = self.pattern.findall(nowmessage[1])
if match: # 如有数字,说明没有出版社信息
pubYear = nowmessage[0].strip()
publisher = 'No-Message'
citedNum = ''.strip().join(list(filter(lambda ch: ch in '0123456789.-', nowmessage[1])))
else: # 若没有数字,说明没有引用数信息
pubYear = nowmessage[0].strip()
publisher = nowmessage[1].strip()
citedNum = '0'
else:
pubYear = nowmessage[0].strip()
publisher = 'No-Message'
citedNum = '0'
except:
pass
try: # 摘要
abstract = artical_info.find('div', {'class': 'caption_abstract'}).get_text()
except:
pass
try:
caption_filed_old = artical_info.find('div', {'class': 'caption_field'})
fild = caption_filed_old.find_all('a')
for i in range(len(fild)):
msg = fild[i].string
caption_filed += msg
caption_filed += '|'
except:
pass
self.result_signal.emit(title,author_name,publisher,pubYear,citedNum,abstract,caption_filed)
def run(self):
self.main_spider(subject, pageNum)
self.log_signal.emit('<font color="red">全部爬取完毕!</font>')
def main(app):
gui = MainUi()
gui.show()
sys.exit(app.exec_())
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
main(app)
| e515eb1866ce484995c28029e811e5da308a86d9 | [
"Markdown",
"Python",
"Text"
]
| 3 | Markdown | swz-study/Literature-Analysis-System-Based-on-Academic-Search-Engine | 8036ab405a1006cdb50bcf5d4c0a5a5b9263e538 | 702dccfed0491f556aeac8c7f20521589003becf |
refs/heads/master | <repo_name>zigdog97/The_Mountain_Of_Evil<file_sep>/monster.py
import livingbeing, weapon
fist = weapon.Weapon("fist")
class Monster(livingbeing.LivingBeing):
def __init__(self,name = "Odd Creature", weapon = fist, health = 10, ):
self.name = name
self.weapon = weapon
self.health = health
self.experienceGive = self.health * 10<file_sep>/shield.py
import weapon
class Shield(weapon.Weapon):
def __init__(self,name = "unidentified weapon", damage = 1, blockChance= 5, critChance = 0):
self.name = name
self.damage = damage
self.critChance = critChance
self.blockChance = blockChance<file_sep>/human.py
import livingbeing, weapon
fist = weapon.Weapon("fist")
class Human(livingbeing.LivingBeing):
def __init__(self,name = "Stranger", weapon = fist, health =90, experienceTotal = 0, level = 1):
self.name = name
self.weapon = weapon
self.health = health + (level*10)
self.experienceTotal = experienceTotal
self.level = level
def levelUP(self):
self.level +=1
self.healthRefill()
def checkForLevelUp(self):
if self.experinceTotal*self.level*.60 >= self.experienceTotal:
return True
return False<file_sep>/livingbeing.py
import random
class LivingBeing(object):
def checkForDeath(self):
if self.health <= 0:
return True
return False
def block(self):
if random.randint(1,100) <= self.weapon.blockChance:
return True
return False
def criticalStrike(self):
if random.randint(1,100) <= self.weapon.critChance:
return True
return False
def attack(self,playerBeingAttacked):
flagForAttack = False
while flagForAttack == False:
if playerBeingAttacked.block() == True:
print self.name + "'s", " Attack was blocked!"
flagForAttack = True
if self.criticalStrike() == True:
if flagForAttack == False:
print self.name, "landed a critical strike dealing", self.weapon.damage*2,"damage!"
playerBeingAttacked.health -= self.weapon.damage*2
print playerBeingAttacked.name, "has", playerBeingAttacked.health, "health remaining!"
flagForAttack = True
else:
if flagForAttack == False:
print self.name, "deals", self.weapon.damage,"damage!"
playerBeingAttacked.health -= self.weapon.damage
print playerBeingAttacked.name, "has", playerBeingAttacked.health, "health remaining!"
flagForAttack = True
def healthRefill(self):
self.health = 100+(self.level*18)<file_sep>/furyblade.py
import weapon
class FuryBlade(weapon.Weapon):
def __init__(self,name = "unidentified weapon", damage = 3, blockChance= 0, critChance = 5):
self.name = name
self.damage = damage
self.critChance = critChance
self.blockChance = blockChance
<file_sep>/weapon.py
class Weapon(object):
def __init__(self,name = "unidentified weapon", damage = 1, critChance = 1, blockChance = 1, prefix ="" ,suffix = ""):
self.name = name
self.damage = damage
self.critChance = critChance
self.blockChance = blockChance
self.prefix = prefix
self.suffix = suffix
def stats(self):
print "The Stats of", self.name,"are as follows:"
print "Damage =",self.damage
print "Crticial Strike Chance =",self.critChance
print "Block Chance =",self.blockChance
def prefixGet():
# prefix to be added: poisoning, burning
prefixList = ["Sharp","Strange","Bulky","","Damaged"]
return random.randchoice(prefixList)
def prefixAdd(self):
pass
| 8ce4239bdeba3e6b6b0b291dd6c1777db4e13bdb | [
"Python"
]
| 6 | Python | zigdog97/The_Mountain_Of_Evil | 9970fe98ec24e5439a8243c67dd1a919fe82a29b | 63b551260b60c5e25d8d5a8deb4c35b5e5444240 |
refs/heads/master | <file_sep>#!/bin/bash
export PATH_WORK=$(cd ..; pwd)
printf "\nPATH_WORK (caminho da pasta de trabalho) = \n%s\n\n" "$PATH_WORK"
export MODELSIM="${PATH_WORK}/modelsim.ini"
printf "\nMODELSIM = \n%s\n\n" "$MODELSIM"
<file_sep>#!/bin/bash
PATH_WORK=$(pwd)
MODELSIM="${PATH_WORK}/modelsim.ini"
mkdir -p ${PATH_WORK}/libs/lib_BENCH
# delete previous lib
vdel -lib ${PATH_WORK}/libs/lib_BENCH -all
# create new lib
vlib ${PATH_WORK}/libs/lib_BENCH
# map lib to lib_BENCH
vmap lib_BENCH ${PATH_WORK}/libs/lib_BENCH
# compile all files in bench and its subfolders
for filename in ${PATH_WORK}/bench/*.sv ${PATH_WORK}/bench/**/*.sv; do
# if a file exists
[ -e "$filename" ] || continue
# get full file name
fullname=${filename##*/}
# compile
printf "\n===-==-===-==-===\n\nCompiling $fullname\n\n"
vlog -warning error -msgsingleline -work lib_BENCH $filename
done
<file_sep>#!/bin/bash
PATH_WORK=$(pwd)
MODELSIM="${PATH_WORK}/modelsim.ini"
mkdir -p ${PATH_WORK}/libs/lib_SV
# delete previous lib
vdel -lib ${PATH_WORK}/libs/lib_SV -all
# create new lib
vlib ${PATH_WORK}/libs/lib_SV
# map lib to lib_SV
vmap lib_SV ${PATH_WORK}/libs/lib_SV
# compile all files in hdl and its subfolders
for filename in ${PATH_WORK}/hdl/*.sv ${PATH_WORK}/hdl/**/*.sv; do
# if a file exists
[ -e "$filename" ] || continue
# get full file name
fullname=${filename##*/}
# compile
printf "\n===-==-===-==-===\n\nCompiling $fullname\n\n"
vlog -warning error -msgsingleline -work lib_SV $filename
done<file_sep><p align="center">
<img src="https://i.imgur.com/epw8sfM.png"/>
</p>
# RISC-DCCCLXVII
A RISC-V-like CPU designed in SystemVerilog for a Hardware Infrastructure class.
## Compiling and running
In the `config` folder there are three scripts that can be used to automatically compile the files:
* `cfgpath.sh` will set the correct PATH for your directory. You should run `source cfgpath.sh` before running any other scripts so ModelSim will recognize your work folders .
* `comp_hdl.sh` will compile only the files in the `hdl` folder.
* `comp_bench.sh` will compile all testbench files.
There are two ways to use the included build scripts.
### Using VSCode
Go to `config` folder:
```zsh
cd config
```
Give all compile scripts executable permission:
```zsh
sudo chmod +x comp_*.sh
```
On VSCode, run the default build task with <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>B</kbd>. It should also provide problem matching for all files.
### Using the terminal
Go to config folder:
```zsh
cd config
```
Change `PATH_WORK=$(pwd)` to `PATH_WORK=$(cd ..; pwd)` in `comp_bench.sh` and `comp_hdl.sh` using a text editor.
Give all compile scripts executable permission:
```zsh
sudo chmod +x comp_*.sh
```
Run the scripts.
### Running
Once you've compiled the files, open ModelSim `vsim &` (assuming it's in your path), select a file and run the simulation.
## Folder structure
* `bench`: all testbench files
* `hdl`: all module files
* `hdl/memory`: memory modules
* `config`: scripts for running/compilation
## Coding guidelines
* 4 space identation
* `snake_case` naming for all variables
* Don't specify `in_` or `out_` in signal names outside of module declarations.
```verilog
« DON'T »
wire i_signal;
```
```verilog
« DO »
module foo(
input wire i_signal
);
```
* Explicit `.` operator when using modules
* Clock is always `clk`, reset is always `reset`
* Always use `enums` instead of arbitrary binary values in state machines/selector pins
```verilog
« DON'T »
always @(*)
case (foo)
2'b00: ..
2'b01: ..
2'b11: ..
```
```verilog
« DO »
enum {READ, WAIT, WALK} states;
always @(*)
case (foo)
READ: ..
WAIT: ..
WALK: ..
```
* Write the datatype for *all* variables. Only one declaration *per line*. Don't use implicit declaration:
```verilog
« DON'T »
input logic a, b, c;
```
```verilog
« DO »
input logic a;
input logic b;
input logic c;
```
This makes it easier to search, change, and identify the type of each variable.
| 9041057bfd3ddb695532514ce5d77367eff9b665 | [
"Markdown",
"Shell"
]
| 4 | Shell | DanielHCorreia/RISC-DCCCLXVII | fdcfdaeb86e4f6f1318e7bb9baf307972afb1f43 | 54fb593b6e9fb7df803a1a37b6d4a510b27387f6 |
refs/heads/master | <file_sep># GlutTest
This a Glut and C++ test
<file_sep>//
// main.cpp
// GlutTest
//
// Created by Roy on 5/1/15.
// Copyright (c) 2015 Broyson. All rights reserved.
//
/* Use the following line on a Windows machine:
#include <GL/glut.h>
*/
/* This line is for Max OSX */
#include <GLUT/glut.h>
/*! GLUT display callback function */
void display(void);
/*! GLUT window reshape callback function */
void reshape(int, int);
int main(int argc, char** argv)
{
glutInit(&argc, argv);
/* set the window size to 512 x 512 */
glutInitWindowSize(512, 512);
/* set the display mode to Red, Green, Blue and Alpha
allocate a depth buffer
enable double buffering
*/
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
/* create the window (and call it Lab 1) */
glutCreateWindow("Lab 1");
/* set the glut display callback function
this is the function GLUT will call every time
the window needs to be drawn
*/
glutDisplayFunc(display);
/* set the glut reshape callback function
this is the function GLUT will call whenever
the window is resized, including when it is
first created
*/
glutReshapeFunc(reshape);
/* set the default background color to black */
glClearColor(0,0,0,1);
/* enter the main event loop so that GLUT can process
all of the window event messages
*/
glutMainLoop();
return 0;
}
/*! glut display callback function. Every time the window needs to be drawn,
glut will call this function. This includes when the window size
changes, or when another window covering part of this window is
moved so this window is uncovered.
*/
void display()
{
/* clear the color buffer (resets everything to black) */
glClear(GL_COLOR_BUFFER_BIT);
/* set the current drawing color to red */
glColor3f(1, 0, 0);
/* start drawing triangles, each triangle takes 3 vertices */
glBegin(GL_TRIANGLES);
/* give the 3 triangle vertex coordinates 1 at a time */
glVertex2f(10, 10);
glVertex2f(250, 400);
glVertex2f(400, 10);
/* tell OpenGL we're done drawing triangles */
glEnd();
/* swap the back and front buffers so we can see what we just drew */
glutSwapBuffers();
}
/*! glut reshape callback function. GLUT calls this function whenever
the window is resized, including the first time it is created.
You can use variables to keep track the current window size.
*/
void reshape(int width, int height)
{
/* tell OpenGL we want to display in a recangle that is the
same size as the window
*/
glViewport(0,0,width,height);
/* switch to the projection matrix */
glMatrixMode(GL_PROJECTION);
/* clear the projection matrix */
glLoadIdentity();
/* set the camera view, orthographic projection in 2D */
gluOrtho2D(0,width,0,height);
/* switch back to the model view matrix */
glMatrixMode(GL_MODELVIEW);
} | 45d067e425d5834b5f843daecc2f3bf78588b979 | [
"Markdown",
"C++"
]
| 2 | Markdown | broyson/GlutTest | b7a88b5a127d28e74a9a8292c14d3267c2bb4fea | e51751ef09cf3cde678d8c6bc981b8b8f58beeaa |
refs/heads/master | <file_sep>console.log("Loops is online");
for (i=0;i<100;i++){
console.log(i);
}
//- Ascending 1-99
for (i=99;i>-1;i--){
console.log(i);
}
//- Descending 99-1
for (i=0;i<100;i+=2){
console.log(i);
}
//- Ascending Even
for (i=98;i>1;i-=2){
console.log(i);
}
//- Descending Even
for (i=49;i<73;i++){
console.log(i);
}
//- Ascending 49-72
for (i=81;i>25;i--){
console.log(i);
}
//- Decsending 81-26
for (i=3;i<91;i+=3){
console.log(i);
}
//- Ascending in Mult*3
<file_sep>
GA Week One Day Two Homework
----------------------------
1. to setup a gitrepo inside a working folder use: git clone//
git init
2. to start tracking a file use the command: git add
3. to move a file from the stageing area to the repository:
git commit (-m "add a decriptive comment for this version")
--> Commit 1
1. Use 'git pull' to bring changes from the master to your local repository.
2. to unstage a file, use the command: git reset HEAD [file]
3. get reset --hard [commit] will undo changes
4. It is imporant to use '--' when changing files because it specifies extended flags
5. You may want to reset back to a previous commit when an error has been mistakenly added a broken update.
-->Commit 2
1. Create a branch with: git branch [branch-name].
2. Use 'git checkout [branch-name]' to change branches.
3. One might wish to use a different branch when working within
a different department or project.
-->Commit 3
1. A repository may be merged when two projects join together. It maybe best to track with a pull, so someone can make sure there are no conflicts
2. Use 'git push' to send your local update to the remote repo.
| 1e423392b7c413fbc4ab7945e49b8369299a49cc | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | kaliforniaco/w01d02-homework | 8159149bc83139fe9bfd0583d3f16f3326e6c7a0 | df81500896d3134f5305579a6b547ff8cb91343e |
refs/heads/master | <file_sep># Your code here!!
def sing():
for i in range(0,9):
if i>=0 and i<=3:
print("let it be,")
elif i==4:
print("whisper words of wisdom, let it be, let it be,")
elif i>=5 and i<=7:
print("let it be,")
elif i==8:
print("there will be an answer, let it be")
sing()<file_sep>import random
# your code here
def generate_random():
number=random.randint(0,9)
print(number)
return (number)
generate_random()<file_sep>user_input = int(input('How many people are coming to your wedding?\n'))
if user_input <= 50:
price = 4000
elif user_input>50 and user_input<=100:
price=10000
elif user_input>100 and user_input<=200:
price=15000
elif user_input>200:
price=20000
print('Your wedding will cost '+str(price)+' dollars')<file_sep>def number_of_bottles():
for i in range (99,0,-1):
if i>1:
print(str(i)+" bottles of milk on the wall, "+str(i)+" bottles of milk.")
print("Take one down and pass it around, "+str(i-1)+" bottles of milk on the wall.")
elif i==1:
print(str(i)+" bottle of milk on the wall,"+str(i)+" bottle of milk.")
print("Take one down and pass it around, no more bottles of milk on the wall.")
elif i==0:
print("No more bottles of milk on the wall, no more bottles of milk.")
print("Go to the store and buy some more, 99 bottles of milk on the wall.")
number_of_bottles()<file_sep># your code here
name= "Yellow"
print(name)
| 82db190ad37fe60424668a4df6efe798f67f66d2 | [
"Python"
]
| 5 | Python | fabianchs/python-exercises-review | fb784c06186a6cd829308650e2d0159547316df3 | 1b205acb27e4963f89264885cd8c70eedc16840e |
refs/heads/master | <repo_name>mckonieczny/ZPI<file_sep>/src/test/java/database/repository/FavoriteRepositoryTest.java
package database.repository;
import database.document.FavoriteDocument;
import org.junit.Before;
import org.junit.Test;
import java.util.Optional;
import static java.util.UUID.randomUUID;
import static org.junit.Assert.*;
/**
* Created by DjKonik on 2016-10-08.
*/
public class FavoriteRepositoryTest {
private FavoriteRepository favoriteRepository;
@Before
public void setUp() {
favoriteRepository = new FavoriteRepository();
}
@Test
public void shouldNotBeFavorite() {
//given
String userId = randomUUID().toString();
String deckId = randomUUID().toString();
//when
boolean isFavorite = favoriteRepository.isFavorite(userId, deckId);
//then
assertFalse(isFavorite);
}
@Test
public void shouldAddFavorite() {
//given
String userId = randomUUID().toString();
String deckId = randomUUID().toString();
//when
FavoriteDocument result = favoriteRepository.save(userId, deckId);
//then
assertNotNull(result.getDocument());
assertNotNull(result.getId());
assertNotEquals(result.getId(), "");
favoriteRepository.delete(result);
}
@Test
public void shouldFindFavorite() {
//given
String userId = randomUUID().toString();
String deckId = randomUUID().toString();
favoriteRepository.save(new FavoriteDocument(userId, deckId));
//when
boolean isFavorite = favoriteRepository.isFavorite(userId, deckId);
//then
assertTrue(isFavorite);
}
@Test
public void shouldDeleteFavorite() {
//given
String userId = randomUUID().toString();
String deckId = randomUUID().toString();
favoriteRepository.save(new FavoriteDocument(userId, deckId));
//when
favoriteRepository.delete(userId, deckId);
//then
boolean isFavorite = favoriteRepository.isFavorite(userId, deckId);
assertFalse(isFavorite);
}
@Test
public void shouldFindFavoriteById() {
//given
String userId = randomUUID().toString();
String deckId = randomUUID().toString();
FavoriteDocument favorite = new FavoriteDocument(userId, deckId);
favoriteRepository.save(favorite);
//when
Optional<FavoriteDocument> result = favoriteRepository.findById(favorite.getId());
//then
assertNotNull(result);
assertTrue(result.isPresent());
assertFalse(result.get().isEmpty());
}
@Test
public void shouldDeleteFavoriteById() {
//given
String userId = randomUUID().toString();
String deckId = randomUUID().toString();
FavoriteDocument favorite = new FavoriteDocument(userId, deckId);
favoriteRepository.save(favorite);
//when
favoriteRepository.deleteById(favorite.getId());
//then
boolean isFavorite = favoriteRepository.isFavorite(userId, deckId);
assertFalse(isFavorite);
}
}<file_sep>/src/main/java/server/SparkUtils.java
package server;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import spark.TemplateEngine;
import spark.template.freemarker.FreeMarkerEngine;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import static spark.Spark.before;
/**
* Created by DjKonik on 2016-10-08.
*/
public class SparkUtils {
private static boolean DEPLOYED = false;
public static String PROD_URL = "https://zpi.herokuapp.com";
public static String LOCAL_URL = "http://localhost:4567";
private static String DEPLOYED_RESOURCES_PATH = "/app/build/resources/main";
private final static TemplateEngine templateEngine = new FreeMarkerEngine();
public static String renderContent(String htmlFile) {
if(isDeployed()) {
return renderDeployedContent(htmlFile);
} else {
return renderLocalContent(htmlFile);
}
}
public static TemplateEngine templateEngine() {
return templateEngine;
}
public static boolean notEmpty(String str) {
return str != null && !str.equals("");
}
public static boolean empty(String str) {
return str == null || str.equals("");
}
private static String renderDeployedContent(String htmlFile) {
try {
File file = new File(DEPLOYED_RESOURCES_PATH + htmlFile);
Path path = file.toPath();
return new String(Files.readAllBytes(path), Charset.defaultCharset());
} catch (IOException e) {}
return null;
}
private static String renderLocalContent(String htmlFile) {
try {
URL url = SparkUtils.class.getResource(htmlFile);
Path path = Paths.get(url.toURI());
return new String(Files.readAllBytes(path), Charset.defaultCharset());
} catch (IOException | URISyntaxException e) {}
return null;
}
public static int getHerokuAssignedPort() {
ProcessBuilder processBuilder = new ProcessBuilder();
if (processBuilder.environment().get("PORT") != null) {
DEPLOYED = true;
return Integer.parseInt(processBuilder.environment().get("PORT"));
}
return 4567; //return default port if heroku-port isn't set (i.e. on localhost)
}
public static boolean isDeployed() {
return DEPLOYED;
}
public static void enableCORS() {
before("*", (req, res) -> {
res.header("Access-Control-Allow-Origin", req.headers("Origin"));
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
});
}
public static String getAppUrl() {
if (isDeployed()) {
return PROD_URL;
} else {
return LOCAL_URL;
}
}
public static List<String> splitJsonArray(String jsonArray) throws IOException, InstantiationException, IllegalAccessException {
List<String> splittedJsonElements = new ArrayList<String>();
ObjectMapper jsonMapper = new ObjectMapper();
JsonNode jsonNode = jsonMapper.readTree(jsonArray);
if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
JsonNode individualElement = arrayNode.get(i);
splittedJsonElements.add(individualElement.toString());
}
}
return splittedJsonElements;
}
}
<file_sep>/src/main/java/database/mongo/MongoConnection.java
package database.mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import static database.mongo.MongoConfig.*;
import static java.util.Optional.ofNullable;
/**
* Created by DjKonik on 2016-10-06.
*/
public class MongoConnection {
private MongoClient mongo;
private MongoDatabase db;
private static MongoConnection instance;
private MongoConnection() {
mongo = getMongoClient();
db = mongo.getDatabase(MONGO_DATABASE);
}
public static MongoConnection open() {
return ofNullable(instance)
.orElse(instance = new MongoConnection());
}
public static void close() {
instance.mongo.close();
instance = null;
}
public static MongoClient getMongoClient() {
MongoClientURI uri = new MongoClientURI("mongodb://"+MONGO_USERNAME+":"+MONGO_PASSWORD+"@"+MONGO_URL+":"+MONGO_PORT+"/"+MONGO_DATABASE);
return new MongoClient(uri);
}
public MongoCollection<Document> getCollection(String collectionName) {
return db.getCollection(collectionName);
}
public MongoDatabase getDatabase() {return db;}
}
<file_sep>/client/src/features/Cards/duck.js
import {combineReducers} from 'redux';
import {ADD_CARD, DELETE_CARD, LOAD_CARDS, LOADED_CARDS} from './actions';
import _ from 'lodash';
export const cards = (state = [], action) => {
switch (action.type) {
case ADD_CARD: {
const newState = [...state, action.doc];
return newState;
}
case DELETE_CARD: {
return state.filter(card => card._id != action.cardId);
}
case LOADED_CARDS: {
return _.union(state, action.cards);
}
default:
return state;
}
};
export const isFetching = (state = true, action) => {
switch (action.type) {
case LOAD_CARDS: {
return true;
}
case LOADED_CARDS: {
return false;
}
default:
return state;
}
};
export const cardsReducer = combineReducers({
cards,
isFetching
});
<file_sep>/client/src/features/Login/index.js
//components
import LoginPage from './LoginPage';
import SignupPage from './SignupPage';
//sagas
import loginSagas from './sagas';
export {LoginPage, SignupPage, loginSagas};
<file_sep>/src/main/java/controllers/PathController.java
package controllers;
import database.document.PathDocument;
import database.repository.PathRepository;
import spark.Request;
import spark.Response;
import java.util.List;
import static org.bson.Document.parse;
import static spark.Spark.get;
import static spark.Spark.post;
import static database.mongo.MongoUtils.toJson;
import static security.LoginHandler.loggedUserId;
import static server.SparkUtils.notEmpty;
import static java.net.HttpURLConnection.*;
/**
* Created by Andrzej on 2016-12-01.
*/
public class PathController extends AbstractController {
private PathRepository repository;
public PathController(){
repository = new PathRepository();
}
@Override
public void registerRestApi() {
post("/api/paths/create", (request, response) -> {
PathDocument path = new PathDocument( parse( request.body()));
String result = "";
if(notEmpty(path.getName())){
path.setOwerId(loggedUserId(request, response));
repository.save(path);
response.status(HTTP_OK);
result = path.toJson();
}else {
result = "Path name can not be empty";
response.status(HTTP_BAD_REQUEST);
}
return result;
});
post("/api/paths/:id/update", (Request request, Response response) -> {
String pathId = request.params("id");
String result = "";
if(notEmpty(pathId)){
PathDocument oldPath = repository.findById(pathId);
repository.delete(oldPath);
PathDocument path = new PathDocument(parse(request.body()));
String name = path.getName();
String description = path.getDescription();
List<String> decksIds = path.getDecksIds();
if(notEmpty(name)){
oldPath.setName(name);
}
if(notEmpty(description)){
oldPath.setDescription(description);
}
if(decksIds != null && decksIds.size()>0){
oldPath.setDecksIds(decksIds);
}
repository.save(oldPath);
} else {
result = "Path ID or name can not be empty";
response.status(HTTP_BAD_REQUEST);
}
return result;
});
post("/api/paths/:id/delete", (request, response) ->{
String pathId = request.params("id");
String result;
if(notEmpty(pathId)){
repository.deleteById(pathId);
result = "Path " + pathId + " was deleted";
response.status(HTTP_OK);
}
else {
result = "Path ID can not be empty";
response.status(HTTP_BAD_REQUEST);
}
return result;
});
get("/api/user/paths", (request, response) ->
toJson(repository.findByOwnerId(loggedUserId(request, response))));
}
}
<file_sep>/client/src/features/Cards/CardTableRow.jsx
import React from 'react';
import DeleteIcon from 'material-ui/svg-icons/action/delete';
import IconButton from 'material-ui/IconButton';
import {TableRow, TableRowColumn} from 'material-ui';
import {RaisedButton, FlatButton} from 'material-ui';
export default class CardTableRow extends React.Component {
constructor () {
super();
this.onHover = this.onHover.bind(this);
this.onHoverExit = this.onHoverExit.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.state = {
show: false
};
}
onHover(e) {
if(!this.props.eraseable) {
return;
}
this.setState({
show: true
})
}
onHoverExit (e) {
e.preventDefault();
this.setState({
show: false
})
}
handleDelete (e) {
this.props.onDelete(this.props.cardId);
}
render() {
const rowStyle = {
paddingTop: '20px',
paddingBottom: '20px',
fontSize: '15px',
textAlign: 'center'
}
const buttonStyle = {
margin: 12,
};
return(
<TableRow hoverable={true} displayBorder={false} onCellHover={this.onHover} onCellHoverExit={this.onHoverExit} >
<TableRowColumn style={rowStyle}>{this.props.word}</TableRowColumn>
<TableRowColumn style={rowStyle}>{this.props.translation}</TableRowColumn>
<TableRowColumn >
{this.state.show ?
<div>
<FlatButton
label="delete"
onClick={this.handleDelete}
primary={true}
style={buttonStyle}
icon={<DeleteIcon />}
/>
</div>
:
null
}
</TableRowColumn>
</TableRow>
);
}
}
<file_sep>/client/src/api/login.js
import _ from 'lodash';
import delay from './utils/delay';
const fakeUsersCollection = {
users: [
{
_id: 1,
username: 'filip',
password: 'abc'
},
{
_id: 2,
username: 'maciek',
password: 'abc'
}
]
}
export const login = (username, password) =>
delay(1000).then(()=>
_.find(fakeUsersCollection, (user) => user.username === username && user.password === password)
);
<file_sep>/client/src/features/Cards/actions.js
export const SAVE_CARDS = 'SAVE_CARDS';
export const ADD_CARD = 'ADD_CARD';
export const DELETE_CARD = 'DELETE_CARD';
export const LOAD_CARDS = 'LOAD_CARDS';
export const LOADED_CARDS = 'LOADED_CARDS';
// @TODO add argument
export const saveCards = () => ({type: SAVE_CARDS});
export const addCard = ({word, translation, deckId}) => {
return {
type: ADD_CARD,
doc: {
_id: Date.now(),
word,
translation,
deckId,
}
};
};
export const deleteCard = (cardId) => ({type: DELETE_CARD, cardId});
export const loadCards = (deckId) => ({type: LOAD_CARDS, deckId});
export const loadedCards = (cards) => ({type: LOADED_CARDS, cards});
<file_sep>/src/main/java/calculator/CalculatorController.java
package calculator;/*
* Created by <NAME> on 2017-04-28.
*/
import controllers.AbstractController;
import javax.servlet.MultipartConfigElement;
import javax.servlet.http.Part;
import java.util.Collection;
import static spark.Spark.get;
import static spark.Spark.post;
public class CalculatorController extends AbstractController {
Calculator calculator = new Calculator();
@Override
public void registerRestApi() {
get("/calculator", (req, res) ->
"<form method=\"POST\" enctype=\"multipart/form-data\">" +
"<div>input file: <input type=\"file\" name=\"in\" /></div>" +
"<div>output file: <input type=\"file\" name=\"out\" /></div>" +
"<div><input type=\"submit\" value=\"send\"/></div>" +
"</form>"
);
post("/calculator", "multipart/form-data", (request, response) -> {
String location = "image"; // the directory location where files will be stored
long maxFileSize = 100000000; // the maximum size allowed for uploaded files
long maxRequestSize = 100000000; // the maximum size allowed for multipart/form-data requests
int fileSizeThreshold = 1024; // the size threshold after which files will be written to disk
MultipartConfigElement multipartConfigElement = new MultipartConfigElement(
location, maxFileSize, maxRequestSize, fileSizeThreshold);
request.raw().setAttribute("org.eclipse.jetty.multipartConfig",
multipartConfigElement);
return calculator.calculate(request.raw().getPart("in"), request.raw().getPart("out"));
});
}
}
<file_sep>/client/src/features/Decks/DeckView.jsx
import React from 'react';
import {AddCard, CardsTable} from '../Cards';
import {Row, Col} from 'react-bootstrap';
import {indigo500} from 'material-ui/styles/colors';
import DeleteIcon from 'material-ui/svg-icons/action/delete';
import Synchro from 'material-ui/svg-icons/action/cached';
import FullStar from 'material-ui/svg-icons/toggle/star';
import EmptyStar from 'material-ui/svg-icons/toggle/star-border';
import {FlatButton} from 'material-ui';
import Loader from '../../components/Loader';
import {browserHistory} from 'react-router';
const headerStyle = {
marginLeft: '50px',
marginTop: '10px',
color: indigo500,
fontFamily: '"Roboto", sans-serif'
};
const deckNameStyle = {
fontFamily: '"Roboto", sans-serif',
color: indigo500,
textAlign: 'center',
};
const buttonStyle = {
margin: 12,
};
export default class DeckView extends React.Component {
// constructor(props) {
// super(props);
// this.props.onRemoveFromFavorites.bind(null, props.deck._id);
// this.props.onAddToFavorites.bind(null, props.deck._id);
// }
renderCardsTable = () => {
if (this.props.isFetching) {
return <Loader />;
}
return (
<CardsTable
deckId={this.props.deck._id}
cards={this.props.deck.cards}
eraseable={this.props.isOwner}
isFetching={this.props.isFetching}
/>
);
}
getFavoriteButtonLabelAndIcon = () => this.props.isFavorite?
{label: 'Remove from favorites', icon: <FullStar />, action: this.removeFromFavorites} :
{label: 'Add to favorites', icon: <EmptyStar />, action: this.addToFavorites};
renderFavoriteButton = () => {
const {label, icon, action} = this.getFavoriteButtonLabelAndIcon();
return (
<FlatButton
label={label}
primary={true}
style={buttonStyle}
icon={icon}
onClick={action}
/>
)
}
deleteDeck = () => {
browserHistory.push('/decks');
this.props.onDelete(this.props.deck._id);
}
removeFromFavorites = () => {
this.props.onRemoveFromFavorites(this.props.deck._id);
}
addToFavorites = () => {
this.props.onAddToFavorites(this.props.deck._id);
}
render () {
return (
<div>
<Row style={deckNameStyle}>
<h1 >
{this.props.deck.name}
</h1>
<FlatButton
label="save"
primary={true}
style={buttonStyle}
icon={<Synchro />}
onClick={this.props.onSynchronize}
/>
{this.renderFavoriteButton()}
{this.props.isOwner?
<FlatButton
label="delete deck"
onClick={this.deleteDeck}
secondary={true}
style={buttonStyle}
icon={<DeleteIcon />}
/>
: null}
</Row>
{this.props.isOwner ?
<div>
<Row>
<h2 style={headerStyle}>
Add new card
</h2>
</Row>
<Row style={{marginBottom: '60px'}}>
<Col mdOffset={3} md={5}>
<AddCard deckId={this.props.deck._id} />
</Col>
</Row>
</div>
:
null
}
<Row>
<h2 style={headerStyle}>
Cards to learn
</h2>
</Row>
<Row style={{marginTop: '20px'}}>
{this.renderCardsTable()}
</Row>
</div>
);
}
}
<file_sep>/client/src/features/Decks/DeckCard.jsx
import React from 'react';
import {Card, CardHeader, CardTitle, CardMedia, CardText, RaisedButton, CardActions} from 'material-ui';
import {indigo500} from 'material-ui/styles/colors';
import _ from 'lodash';
const cardStyles = {
margin: '10px',
};
const DeckCard = ({name, description, creatorName, actionLabel, onAction}) => (
<Card style={cardStyles} zDepth={5} >
<CardMedia
overlay={<CardTitle title={name} subtitle={description} />}
>
<img src={`images/deckImages/1.jpg`} />
</CardMedia>
{creatorName?
<CardText >
{`by ${creatorName}`}
</CardText>
:
null}
<CardActions>
<RaisedButton primary fullWidth label={actionLabel} onClick={onAction} />
</CardActions>
</Card>
);
export default DeckCard;
<file_sep>/client/src/features/Test/duck.js
export const INCREASE_COUNTER = 'INCREASE_COUNTER';
export const increaseCounter = () => ({
type: INCREASE_COUNTER,
payload: 1,
});
const initialState = {
value: 10
};
export const counterReducer = (state = {value: 10}, action) => {
switch (action.type) {
case INCREASE_COUNTER:
return {value: state.value + action.payload};
default:
return state;
}
};
<file_sep>/src/main/java/database/mongo/MongoConfig.java
package database.mongo;
/**
* Created by DjKonik on 2016-10-06.
*/
public class MongoConfig {
public static final String MONGO_USERNAME = "admin";
public static final String MONGO_PASSWORD = "<PASSWORD>";
public static final String MONGO_DATABASE = "zpi";
public static final String MONGO_URL = "ds033966.mlab.com";
public static final String MONGO_PORT = "33966";
}
<file_sep>/.profile
export TERM=${TERM:-dumb}<file_sep>/client/src/features/Login/duck.js
import {LOG_IN, LOGGED_IN} from './actions';
export const userReducer = (state = {}, action) => {
switch (action.type) {
case LOG_IN: {
return {...state, isLoggingIn: true};
}
case LOGGED_IN: {
return {profile: action.user, isLoggingIn: false}
}
default:
return state;
}
};
<file_sep>/client/src/features/Decks/index.js
//components
import DecksPage from './DecksPage';
import AddDeck from './AddDeck';
import DeckViewPage from './DeckViewPage';
//sagas
import deckSagas from './sagas';
export {AddDeck, DecksPage, DeckViewPage, deckSagas};
<file_sep>/build.gradle
import com.moowork.gradle.node.task.NodeTask
group 'com.zpi'
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath 'com.moowork.gradle:gradle-node-plugin:0.12'
}
}
apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'idea'
apply plugin: 'war'
apply plugin: "com.moowork.node"
node {
version = '7.0.0'
npmVersion = '3.10.8'
download = true
}
archivesBaseName = "zpi"
version '1.0'
applicationName = "zpi"
mainClassName = "Main"
repositories {
mavenCentral()
}
dependencies {
compile 'com.sparkjava:spark-core:2.3'
compile 'com.sparkjava:spark-template-freemarker:2.3'
compile 'org.mongodb:mongo-java-driver:3.0.2'
compile 'org.pac4j:pac4j:1.9.3'
compile 'org.pac4j:pac4j-http:1.9.3'
compile 'org.pac4j:pac4j-mongo:1.9.3'
compile 'org.pac4j:pac4j-oauth:1.9.4'
compile 'org.pac4j:pac4j-jwt:1.9.4'
compile 'org.pac4j:spark-pac4j:1.2.2'
compile 'ch.qos.logback:logback-core:1.1.3'
compile 'ch.qos.logback:logback-classic:1.1.3'
compile 'de.rtner:PBKDF2:1.1.0'
compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
compile group: 'gov.nist.math', name: 'jama', version: '1.0.2'
testCompile 'junit:junit:4.11'
}
defaultTasks = ['clean']
task stage(dependsOn: ['clean', 'installApp'])
task webpack(type: NodeTask, dependsOn: 'npmInstall') {
def osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("windows")) {
script = project.file('node_modules/webpack/bin/webpack.js')
} else {
script = project.file('node_modules/.bin/webpack')
}
}
processResources.dependsOn 'webpack'
clean.delete << file('node_modules')<file_sep>/src/main/java/database/mongo/MongoDocument.java
package database.mongo;
import org.bson.Document;
import org.bson.types.ObjectId;
/**
* Created by DjKonik on 2016-10-08.
*/
public abstract class MongoDocument {
public final static String M_ID = "_id";
private Document document;
public MongoDocument() {
this.document = new Document();
}
public MongoDocument(Document document) {
this.document = document;
}
public Document getDocument() {
return document;
}
public ObjectId getObjectId() {
return (ObjectId) document.get(M_ID);
}
public boolean isEmpty() {
return document == null;
}
public boolean isNotEmpty() {
return document != null;
}
public String getId() {
return getObjectId().toString();
}
public String toJson() {return document.toJson();}
}
<file_sep>/client/src/features/Decks/DeckViewPage.jsx
import React from 'react';
import DeckView from './DeckView';
import {connect} from 'react-redux';
import {getUserId} from '../../api/user';
import {deleteDeck, addToFavorites, removeFromFavorites} from './actions';
import {saveCards, loadCards} from '../Cards/actions';
import _ from 'lodash';
class DeckViewPage extends React.Component {
componentDidMount () {
this.props.loadCards(this.props.deck._id);
}
render () {
return (
<DeckView {...this.props} />
);
}
}
const mapStateToProps = (state, ownProps) => {
const deck = _.find(state.deck.decks, deck => deck._id.$oid === ownProps.params.deckId);
const isOwner = getUserId() === deck.ownerId;
return {
deck,
isOwner,
isFavorite: deck.favorite,
isFetching: state.card.isFetching
};
};
export default connect(mapStateToProps, {
onDelete: deleteDeck,
onSynchronize: saveCards,
onAddToFavorites: addToFavorites,
onRemoveFromFavorites: removeFromFavorites,
loadCards,
})(DeckViewPage);
<file_sep>/client/src/app/rootSaga.js
import {deckSagas} from '../features/Decks';
import {cardSagas} from '../features/Cards';
import {loginSagas} from '../features/Login';
import _ from 'lodash';
// helper functions
const joinSagas = (sagas) => _.flatten(sagas);
const runSagas = (sagas) => sagas.map(saga => saga());
const combinedSagas = joinSagas([deckSagas, cardSagas, loginSagas]);
export default function* rootSaga () {
yield runSagas(combinedSagas);
}
<file_sep>/client/src/features/Cards/sagas.js
import {delay, takeEvery} from 'redux-saga';
import {call, put} from 'redux-saga/effects';
import {LOAD_CARDS, loadedCards} from './actions';
import {fetchCards} from '../../api/cards';
export function* save () {
// fetchCards(1).then(res => console.log(res));
yield call(delay, 2000);
console.log('save');
}
export function* loadCards (action) {
const {deckId} = action;
const cards = yield call(fetchCards, deckId);
console.log(deckId);
console.log(cards);
yield call(delay, 1000);
yield put(loadedCards(cards));
}
export function* watchSave () {
yield* takeEvery('SAVE_CARDS', save);
}
export function* watchLoadCards () {
yield* takeEvery(LOAD_CARDS, loadCards);
}
const cardSagas = [watchSave, watchLoadCards];
export default cardSagas;
<file_sep>/client/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Root from './app/Root';
import configureStore from './app/configureStore';
import './index.css';
ReactDOM.render(
<Root store={configureStore()} />
, document.getElementById('root')
);
<file_sep>/client/src/features/Cards/index.js
// components
import AddCard from './AddCard';
import CardsTable from './CardsTable';
// sagas
import cardSagas from './sagas';
export {AddCard, CardsTable, cardSagas};
<file_sep>/src/main/java/samples/DeckSample.java
package samples;
import database.document.DeckDocument;
import database.document.FavoriteDocument;
import database.repository.DeckRepository;
import database.repository.FavoriteRepository;
import security.LoginHandler;
import spark.ModelAndView;
import spark.Request;
import spark.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static security.LoginHandler.loggedUserId;
import static security.LoginHandler.loggedUserName;
import static server.SparkUtils.notEmpty;
import static server.SparkUtils.templateEngine;
import static spark.Spark.get;
import static spark.Spark.post;
/**
* Created by DjKonik on 2016-11-15.
*/
public class DeckSample {
private static DeckRepository deckRepository = new DeckRepository();
private static FavoriteRepository favoriteRepository= new FavoriteRepository();
public static void create(LoginHandler loginHandler) {
loginHandler.secureUrl("/panel/decks");
get("/panel/decks", (req, res) -> decksListView(req, res), templateEngine());
loginHandler.secureUrl("/panel/decks/create");
get("/panel/decks/create", (req, res) -> decksCreateView(), templateEngine());
post("/panel/decks/create", (req, res) -> {
String name = req.queryParams("name");
String description = req.queryParams("description");
int difficulty = Integer.valueOf(req.queryParams("difficulty"));
if (notEmpty(name) && notEmpty(description)) {
deckRepository.save(new DeckDocument(loggedUserId(req,res), loggedUserName(req, res), name, description, difficulty));
return decksListView(req, res);
} else {
return decksCreateView();
}
}, templateEngine());
loginHandler.secureUrl("/panel/decks/delete/:id");
get("/panel/decks/delete/:id", (req, res) -> {
deckRepository.deleteById(req.params(":id"));
return decksListView(req, res);
}, templateEngine());
loginHandler.secureUrl("/panel/favorite/add/:id");
get("/panel/favorite/add/:id", (req, res) -> {
favoriteRepository.save(loggedUserId(req, res), req.params(":id"));
return decksListView(req, res);
}, templateEngine());
loginHandler.secureUrl("/panel/favorite/remove/:id");
get("/panel/favorite/remove/:id", (req, res) -> {
favoriteRepository.delete(loggedUserId(req, res), req.params(":id"));
return decksListView(req, res);
}, templateEngine());
}
private static ModelAndView decksListView(Request req, Response res) {
List<DeckDocument> decks = deckRepository.findAll();
List<String> favorites = favoriteRepository.findByUserId(loggedUserId(req, res))
.stream()
.map(FavoriteDocument::getDeckId)
.collect(Collectors.toList());
for(DeckDocument deck : decks) {
deck.setFavorite(favorites.contains(deck.getId()));
}
Map<String, Object> model = new HashMap<>();
model.put("decks", decks);
return new ModelAndView(model, "decks/list.ftl");
}
private static ModelAndView decksCreateView() {
Map<String, Object> model = new HashMap<>();
return new ModelAndView(model, "decks/create.ftl");
}
}
<file_sep>/client/src/features/Decks/AddDeckForm.jsx
import React from 'react';
import {TextField, RaisedButton} from 'material-ui';
import {Row,Col} from 'react-bootstrap';
import {browserHistory} from 'react-router';
export default class AddDeckForm extends React.Component {
constructor () {
super();
this.submitForm = this.submitForm.bind(this);
this.state = {
name: '',
description: ''
};
}
isValid () {
let form = this.state;
for (let prop in form) {
if (form[prop] === '') {
return false;
}
}
return true;
}
submitForm () {
if (!this.isValid()) return;
this.props.onSubmit(this.state);
this.setState({
name: '',
description: ''
});
browserHistory.push('/decks');
}
setValue (field, event) {
var object = {};
object[field] = event.target.value;
this.setState(object);
}
render () {
return (
<Row>
<Col mdOffset={3} md={6}>
<div>
<TextField
fullWidth
name="name"
hintText="Name"
value={this.state.name}
onChange={this.setValue.bind(this, 'name')}
/>
<br />
<TextField
fullWidth
name="description"
hintText="Description"
multiLine
value={this.state.description}
onChange={this.setValue.bind(this, 'description')}
/>
<div style={{paddingTop: '30px'}}>
<RaisedButton label="Create deck" fullWidth secondary onClick={this.submitForm} />
</div>
</div>
</Col>
</Row>
);
}
}
<file_sep>/src/main/java/database/repository/PathRepository.java
package database.repository;
import database.document.PathDocument;
import database.mongo.MongoRepository;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Filters.eq;
/**
* Created by Andrzej on 2016-12-01.
*/
public class PathRepository extends MongoRepository<PathDocument> {
public final static String C_PATHS = "paths";
public PathRepository() {
super(C_PATHS);
}
public List<PathDocument> findByOwnerId(String ownerId) {
List<PathDocument> paths = new ArrayList<>();
getCollection()
.find(eq(PathDocument.M_OWNER_ID, ownerId))
.map(path -> new PathDocument((Document) path))
.into(paths);
return paths;
}
public PathDocument findById(String id){
List<PathDocument> paths = new ArrayList<>();
getCollection()
.find(eqId(id))
.map(path -> new PathDocument((Document) path))
.into(paths);
return paths.size() > 0 ? paths.get(0) : null;
}
}
<file_sep>/client/src/features/Login/actions.js
export const LOG_IN = 'LOG_IN';
export const LOGGED_IN = 'LOGGED_IN';
export const logIn = (username, password) => ({type: LOG_IN, username, password});
export const loggedIn = (user) => ({type: LOGGED_IN, user});
<file_sep>/src/main/java/security/CustomFacebookClient.java
package security;
import com.github.scribejava.core.model.OAuth2AccessToken;
import org.pac4j.oauth.client.FacebookClient;
import org.pac4j.oauth.profile.facebook.FacebookProfile;
/**
* Created by DjKonik on 2016-11-25.
*/
public class CustomFacebookClient extends FacebookClient {
public CustomFacebookClient(String key, String secret) {
super(key, secret);
}
public FacebookProfile retrieveUserProfileFromToken(String token) {
try {
return retrieveUserProfileFromToken(new OAuth2AccessToken(token));
} catch(Exception e) {
return null;
}
}
}
<file_sep>/src/test/java/database/repository/UserRepositoryTest.java
package database.repository;
import database.document.UserDocument;
import org.junit.Before;
import org.junit.Test;
import static java.util.UUID.randomUUID;
/**
* Created by DjKonik on 2016-10-08.
*/
public class UserRepositoryTest {
private UserRepository userRepository;
private final static String T_USERNAME = randomUUID().toString();
private final static String T_PASSWORD = randomUUID().toString();
@Before
public void setUp() {
userRepository = new UserRepository();
}
@Test
public void shouldAddUser() {
//given
UserDocument user = new UserDocument(T_USERNAME, T_PASSWORD);
//when
userRepository.save(user);
//then
assert(user.getId() != null);
}
@Test
public void shouldFindUserByName() {
//given
//when
UserDocument result = userRepository.findByName(T_USERNAME);
//then
assert(result.getDocument() != null);
}
@Test
public void shouldDeleteUser() {
//given
UserDocument user = userRepository.findByName(T_USERNAME);
//when
userRepository.delete(user);
UserDocument result = userRepository.findByName(T_USERNAME);
//then
assert(result.getDocument() == null);
}
}<file_sep>/client/src/features/Decks/sagas.js
import {delay, throttle} from 'redux-saga';
import {call, put} from 'redux-saga/effects';
import {fetchAllDecks} from '../../api/decks';
import {LOAD_DECKS, loadedDecks} from './actions';
// to delete
export function* helloSaga () {
yield call(delay, 2000);
console.log('hello saga');
}
export function* loadDecks () {
const decks = yield call(fetchAllDecks);
yield put(loadedDecks(decks));
}
export function* createDeck () {
// const newDeck =
}
export function* watchLoadDecks () {
yield* throttle(2000, LOAD_DECKS, loadDecks);
}
const deckSagas = [helloSaga, watchLoadDecks];
export default deckSagas;
<file_sep>/src/main/java/security/PasswordValidator.java
package security;
import org.pac4j.core.credentials.password.PasswordEncoder;
/**
* Created by DjKonik on 2016-11-05.
*/
public class PasswordValidator implements PasswordEncoder {
@Override
public String encode(String password) {
try {
return PasswordHash.createHash(password);
} catch (Exception e) {
return null;
}
}
@Override
public boolean matches(String plainPassword, String encodedPassword) {
try {
return PasswordHash.validatePassword(plainPassword, encodedPassword);
} catch (Exception e) {
return false;
}
}
}
<file_sep>/webpack.config.js
var path = require('path');
var webpack = require('webpack')
var ROOT = path.resolve(__dirname, 'client');
var SRC = path.resolve(ROOT, 'src');
var DEST = path.resolve(__dirname, 'build/resources/main/public/webapp');
module.exports = {
devtool: 'source-map',
entry: ['babel-polyfill', SRC + '/index.js'],
resolve: {
root: [
path.resolve(ROOT, 'public'),
path.resolve(ROOT, 'src')
],
extensions: ['', '.js', '.jsx', '.json']
},
output: {
path: DEST,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js[x]?$/,
loader: 'babel-loader',
include: SRC,
query:
{
presets:['react', 'es2015', 'stage-0']
}
},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /\.less$/, loader: 'style!css!less'},
{test: /\.(jpg|png|gif|svg|ico)$/i, loader: "file-loader?name=/images/[name].[ext]"},
]
}
};<file_sep>/src/main/java/database/document/MarkDocument.java
package database.document;
import database.mongo.MongoDocument;
import org.bson.Document;
/**
* Created by Andrzej on 2016-12-14.
*/
public class MarkDocument extends MongoDocument {
public final static String M_DECK_ID = "deckId";
public final static String M_OWNER_ID = "ownerId";
public final static String M_MARK = "mark";
public MarkDocument(Document document){
super(document);
}
public MarkDocument(String deckId, String ownerId, int mark){
setDeckId(deckId);
setOwnerId(ownerId);
setMark(mark);
}
public void setDeckId(String deckId) {
getDocument().put(M_DECK_ID, deckId);
}
public String getDeckID(){
return getDocument().getString(M_DECK_ID);
}
public void setOwnerId(String ownerId) {
getDocument().put(M_OWNER_ID, ownerId);
}
public String getOwerId(){
return getDocument().getString(M_OWNER_ID);
}
public void setMark(int mark) {
getDocument().put(M_MARK, mark);
}
public int getMark(){
return getDocument().getInteger(M_MARK, 0);
}
}
<file_sep>/client/src/App.js
import React, {Component} from 'react';
import logo from './logo.svg';
import Test from './features/Test/TestPage';
import './App.css';
import {Grid,Row,Col} from 'react-bootstrap';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import TextField from 'material-ui/TextField';
import {yellow700, deepOrange400, purple500, indigo500} from 'material-ui/styles/colors';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import Navbar from './components/Navbar';
const getAppBarColor = (notLogged) => notLogged ? '#F5F5F5' : 'white';
const muiTheme = (notLogged) => {
const appBarColor = notLogged? '#F5F5F5' : 'white';
console.log(appBarColor);
return getMuiTheme({
palette: {
textColor: indigo500,
primary1Color: indigo500,
accent1Color: purple500,
},
appBar: {
height: 80,
color: appBarColor,
textColor: 'black'
},
});
}
class App extends Component {
render () {
return (
<MuiThemeProvider muiTheme={muiTheme(this.props.route.notLogged)}>
<div className="main">
<div >
<Navbar notLogged={this.props.route.notLogged} />
</div>
<div style={{marginTop: '0px'}}>
<Grid >
<Row>
<Col smOffset={1} md={10} mdOffset={1} >
<div className="app-content">
{this.props.children}
</div>
</Col>
</Row>
</Grid>
</div>
</div>
</MuiThemeProvider>
);
}
}
export default App;
<file_sep>/client/src/app/mainReducer.js
import {combineReducers} from 'redux';
import {decksReducer} from '../features/Decks/duck.js';
import {cardsReducer} from '../features/Cards/duck.js';
import {userReducer} from '../features/Login/duck.js';
const mainReducer = combineReducers({
deck: decksReducer,
card: cardsReducer,
user: userReducer,
});
// export const getMyDecks = (state, )
export default mainReducer;
<file_sep>/client/src/features/Decks/AddDeck.jsx
import {connect} from 'react-redux';
import AddDeckForm from './AddDeckForm';
import {createDeck} from './actions';
const mapDispatchToProps = dispatch => ({
onSubmit: (doc) => dispatch(createDeck(doc))
});
export default connect(null, mapDispatchToProps)(AddDeckForm);
<file_sep>/client/src/features/Cards/CardsTable.jsx
import React from 'react';
import {connect} from 'react-redux';
import {Table, TableHeader, TableRow, TableHeaderColumn, TableBody} from 'material-ui';
import CardTableRow from './CardTableRow';
import {deleteCard} from './actions';
class CardsTable extends React.Component {
renderCards () {
return this.props.cards.map((card) => (
<CardTableRow key={card._id} cardId={card._id}
deckId={this.props.deckId} word={card.word}
translation={card.translation} eraseable={this.props.eraseable}
onDelete={this.props.onDelete} />
));
}
render() {
return (
<Table style={{backgroundColor: '#F5F5F5'}}>
<TableHeader displaySelectAll={false} adjustForCheckbox={false}>
<TableRow>
<TableHeaderColumn>Word</TableHeaderColumn>
<TableHeaderColumn>Translation</TableHeaderColumn>
<TableHeaderColumn> </TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody displayRowCheckbox={false} showRowHover={false}>
{this.renderCards()}
</TableBody>
</Table>
);
}
}
const mapStateToProps = (state, ownProps) => ({
cards: state.card.cards.filter(card => card.deckId === ownProps.deckId),
});
const mapDispatchToProps = dispatch => ({
onDelete: (cardId) => dispatch(deleteCard(cardId))
});
export default connect(mapStateToProps, mapDispatchToProps)(CardsTable);
<file_sep>/client/src/api/decks.js
import _ from 'lodash';
import delay from './utils/delay';
import {USE_MOCKS} from './config';
//fake API for developement
const fakeCollection = {
decks: [
{
_id: 1,
name: '<NAME>',
description: 'podstawowe zwroty po francusku',
ownerId: 1,
favorite: false,
},
{
_id: 2,
name: '<NAME>',
description: 'podstawowe zwroty po niemiecku',
ownerId: 2,
favorite: false,
},
]
};
// API
export const fetchAllDecksApi = () => {
return fetch(`https://zpi.herokuapp.com/api/decks`).then((res) => res.json());
}
// MOCKS
export const fetchAllMockedDecks = () => delay(1000).then(() => fakeCollection.decks);
export const fetchMockedDeck = (deckId) => delay(2000).then(() =>
_.find(fakeCollection.decks, (deck) => deck._id === deckId));
export const fetchAllDecks = () => {
if (USE_MOCKS) {
return fetchAllMockedDecks();
}
return fetchAllDecksApi();
}
export const fetchDeck = (deckId) => {
if (USE_MOCKS) {
return fetchMockedDeck(deckId);
}
console.log('no api');
}
<file_sep>/client/src/features/Decks/DecksPage.jsx
import React from 'react';
import {connect} from 'react-redux';
import {getUserId} from '../../api/user';
import Decks from './Decks';
import {loadDecks} from './actions';
class DecksPage extends React.Component {
componentDidMount () {
this.props.loadDecks();
}
render () {
return (
<Decks {...this.props} />
);
}
}
// @TODO use selectors
const mapStateToProps = state => ({
myDecks: state.deck.decks.filter(deck => deck.ownerId === getUserId()),
otherDecks: state.deck.decks.filter(deck => deck.ownerId !== getUserId()),
isFetching: state.deck.isFetching
});
export default connect(mapStateToProps, {loadDecks})(DecksPage);
<file_sep>/src/main/java/database/repository/DeckRepository.java
package database.repository;
import com.mongodb.BasicDBObject;
import database.document.DeckDocument;
import database.mongo.MongoRepository;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Filters.*;
import static database.document.DeckDocument.*;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.compile;
/**
* Created by DjKonik on 2016-10-08.
*/
public class DeckRepository extends MongoRepository<DeckDocument> {
public final static String C_DECKS = "decks";
public final static int PAGE_OFFSET = 10;
private UserRepository userRepository = new UserRepository();
public DeckRepository() {
super(C_DECKS);
}
public List<DeckDocument> findAll() {
List<DeckDocument> decks = new ArrayList<>();
getCollection()
.find()
.map(card -> new DeckDocument((Document) card))
.into(decks);
return decks;
}
public List<DeckDocument> findAll(int page) {
return findAll(page, PAGE_OFFSET);
}
public List<DeckDocument> findAll(int page, int offset) {
List<DeckDocument> decks = new ArrayList<>();
getCollection()
.find()
.skip(offset * page)
.limit(offset)
.map(card -> new DeckDocument((Document) card))
.into(decks);
return decks;
}
public List<DeckDocument> search(String keyword, int page) {
return search(keyword, page, PAGE_OFFSET);
}
public List<DeckDocument> search(String keyword, int page, int offset) {
List<DeckDocument> decks = new ArrayList<>();
getCollection()
.find(searchCommand(keyword))
.skip(offset * page)
.limit(offset)
.map(card -> new DeckDocument((Document) card))
.into(decks);
return decks;
}
public List<DeckDocument> search(String keyword) {
List<DeckDocument> decks = new ArrayList<>();
getCollection()
.find(searchCommand(keyword))
.map(card -> new DeckDocument((Document) card))
.into(decks);
return decks;
}
private Bson searchCommand(String keyword) {
List<Bson> searchCommands = new ArrayList<Bson>();
searchCommands.add(new BasicDBObject(M_OWNER, compile(keyword, CASE_INSENSITIVE)));
List<Bson> subNameSearch = new ArrayList<Bson>();
for (String word : keyword.split(" ")) {
subNameSearch.add(new BasicDBObject(M_NAME, compile(word, CASE_INSENSITIVE)));
}
searchCommands.add(and(subNameSearch));
List<Bson> subDescSearch = new ArrayList<Bson>();
for (String word : keyword.split(" ")) {
subDescSearch.add(new BasicDBObject(M_DESCRIPTION, compile(word, CASE_INSENSITIVE)));
}
searchCommands.add(and(subDescSearch));
return or(searchCommands);
}
public List<DeckDocument> findByOwnerId(String ownerId) {
List<DeckDocument> decks = new ArrayList<>();
getCollection()
.find(eq(DeckDocument.M_OWNER_ID, ownerId))
.map(card -> new DeckDocument((Document) card))
.into(decks);
return decks;
}
public DeckDocument findByDeckId(String id){
List<DeckDocument> decks = new ArrayList<>();
getCollection()
.find(eqId(id))
.map(deck -> new DeckDocument((Document)deck))
.into(decks);
return decks.size() > 0 ? decks.get(0) : null;
}
public Object delete(String id){
Object deleted = getCollection().findOneAndDelete(eq(DeckDocument.M_ID, new ObjectId(id)));
return deleted;
}
public void updateSize(String deckId, int newSize){
getCollection().updateOne(eqId(deckId), new BasicDBObject("$set", new Document(DeckDocument.M_SIZE, newSize)) );
}
public void increaseSize(String deckId) {
DeckDocument deck = findByDeckId(deckId);
if (!deckId.isEmpty()) {
updateSize(deckId, deck.getSize() + 1);
}
}
public void decreaseSize(String deckId){
DeckDocument deck = findByDeckId(deckId);
if(deck != null){
updateSize(deckId, deck.getSize()-1);
}
}
}
<file_sep>/client/src/features/Login/LoginPage.jsx
import React from 'react';
import {TextField, RaisedButton, FlatButton} from 'material-ui';
import {yellow700} from 'material-ui/styles/colors';
import {Col} from 'react-bootstrap';
import {browserHistory} from 'react-router';
import {connect} from 'react-redux';
import {logIn} from './actions';
const headerStyle = {
fontFamily: '"Dancing Script", Georgia, Times, serif',
textAlign: 'center',
};
class LoginPage extends React.Component {
constructor () {
super();
this.submitForm = this.submitForm.bind(this);
this.loginRequest = this.loginRequest.bind(this);
this.state = {
username: '',
password: ''
};
}
isValid () {
let form = this.state;
for (let prop in form) {
if (form[prop] === '') {
return false;
}
}
return true;
}
// to extract from file
loginRequest (username, password) {
this.props.logIn(username, password);
}
submitForm (ev) {
ev.preventDefault();
if (!this.isValid()) {
return;
}
const {username, password} = this.state;
console.log(`login with: ${username} , ${password}`);
this.loginRequest(username, password);
this.setState({
username: '',
password: '',
});
}
setValue (field, event) {
var object = {};
object[field] = event.target.value;
this.setState(object);
}
componentWillMount () {
// document.body.style.backgroundColor = '#FFFFFF';
// ugly hacks
// document.body.style.backgroundImage = 'url(/images/background1.jpg)';
// document.body.style.backgroundSize = '100%';
// document.body.style.backgroundRepeat = 'no-repeat';
}
componentWillUnmount () {
// document.body.style.backgroundColor = '#F5F5F5';
// ugly hacks
// document.body.style.backgroundImage = null;
}
render () {
return (
<div style={{backgroundColor: 'white'}}>
<Col mdOffset={4} md={4}>
<div style={headerStyle}>
<h1>Log in</h1>
</div>
<TextField
name="username"
floatingLabelText="Username"
value={this.state.username}
floatingLabelStyle={headerStyle}
onChange={this.setValue.bind(this, 'username')}
/>
<br />
<TextField
name="password"
floatingLabelText="<PASSWORD>"
type="password"
floatingLabelStyle={headerStyle}
value={this.state.password}
onChange={this.setValue.bind(this, 'password')}
/>
<div style={{paddingTop: '30px'}}>
<RaisedButton label="Log in" primary onClick={this.submitForm} />
</div>
<div style={{paddingTop: '20px', paddingLeft: '100px', fontFamily: '"Dancing Script", Georgia, Times, serif',}}>
<div style={{color: yellow700}}>
or
</div>
<FlatButton label="Sign up" secondary onClick={() => browserHistory.push('welcome/signup')} />
</div>
</Col>
</div>
);
}
}
export default connect(null, {logIn})(LoginPage);
<file_sep>/client/src/features/Decks/Decks.jsx
import React from 'react';
import {TextField, Divider} from 'material-ui';
import {Row,Col} from 'react-bootstrap';
import {indigo500} from 'material-ui/styles/colors';
import {browserHistory} from 'react-router';
import _ from 'lodash';
import DeckCard from './DeckCard';
import Loader from '../../components/Loader';
class Decks extends React.Component {
constructor () {
super();
this.renderMyDecks = this.renderMyDecks.bind(this);
this.buttonClicked = this.buttonClicked.bind(this);
}
buttonClicked (deckId) {
browserHistory.push(`/deck/${deckId}`);
}
renderMyDecks () {
if (this.props.isFetching) {
return <Loader />;
}
return this.props.myDecks.map((deck) => (
<Col key={deck._id.$oid} md={4}>
<DeckCard key={deck._id} name={deck.name} creatorName={'Not Logged'} actionLabel={'Edit'}
description={deck.description} onAction={_.partial(this.buttonClicked, deck._id.$oid)} />
</Col>
));
}
renderOtherDecks() {
if (this.props.isFetching) {
return <Loader />;
}
return this.props.otherDecks.map((deck) => (
<Col key={deck._id.$oid} md={4}>
<DeckCard key={deck._id} name={deck.name} creatorName={'Not Logged'} actionLabel={'View'}
description={deck.description} onAction={_.partial(this.buttonClicked, deck._id.$oid)} />
</Col>
));
}
render() {
const headerStyle = {
marginLeft: '50px',
fontSize: '30px',
marginTop: '10px',
marginBottom: '50px',
color: indigo500,
// fontFamily: '"Dancing Script", Georgia, Times, serif',
fontFamily: '"Roboto", sans-serif'
};
return (
<div>
<Row>
<h1 style={headerStyle}>
My decks
</h1>
</Row>
<Row>
{this.renderMyDecks()}
</Row>
<Row style={{marginTop: '50px'}}>
<Divider />
</Row>
<Row>
<Col md={7}>
<h1 style={headerStyle}>
See also bundles created by others
</h1>
</Col>
<Col md={5}>
<TextField
hintText="Search"
/>
</Col>
</Row>
<Row>
{this.renderOtherDecks()}
</Row>
</div>
);
}
}
Decks.defaultProps = {
myDecks: [],
otherDecks: [],
};
export default Decks;
<file_sep>/client/src/components/Navbar/Navbar.jsx
import React from 'react';
import AppBar from 'material-ui/AppBar';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton';
import Snackbar from 'material-ui/Snackbar';
import MenuIcon from 'material-ui/svg-icons/navigation/menu';
import FlatButton from 'material-ui/FlatButton';
import Drawer from 'material-ui/Drawer';
import Avatar from 'material-ui/Avatar';
import Divider from 'material-ui/Divider';
import AddBundleIcon from 'material-ui/svg-icons/action/note-add';
import ViewBundlesIcon from 'material-ui/svg-icons/action/view-module';
import AccountBox from 'material-ui/svg-icons/action/account-box';
import Learn from 'material-ui/svg-icons/social/school';
import Create from 'material-ui/svg-icons/content/create';
import {browserHistory} from 'react-router';
import './styles.css';
export default class Navbar extends React.Component {
constructor () {
super();
this.handleOpenMenu = this.handleOpenMenu.bind(this);
this.handleRequestClose = this.handleRequestClose.bind(this);
this.handleSnackbarClose = this.handleSnackbarClose.bind(this);
this.handleSnackbarOpen = this.handleSnackbarOpen.bind(this);
this.handleLogout = this.handleLogout.bind(this);
this.handleBadgeClick = this.handleBadgeClick.bind(this);
this.state = {
open: false,
openReport:false,
snackbarOpen: false,
};
}
closeNavbar = () => {
this.setState({
open: false
});
}
goToHomePage = () => {
browserHistory.push('/home');
this.closeNavbar();
}
goToAddDeck = () => {
browserHistory.push('/addDeck');
this.closeNavbar();
}
goToDecks = () => {
browserHistory.push('/decks');
this.closeNavbar();
}
handleLogout () {
console.log('handleLogout');
}
handleOpenMenu (event) {
event.preventDefault();
this.setState({
open: !this.state.open,
});
}
handleRequestClose () {
this.setState({
open: false,
});
}
handleSnackbarClose () {
this.setState({
snackbarOpen: false
});
}
handleSnackbarOpen () {
this.setState({
snackbarOpen: true
});
}
handleBadgeClick () {
console.log('handleBadgeClick');
}
render () {
const loggedUser = {
username: 'not logged',
emails : [
{address: 'no email address'}
]
};
const userNameStyle = {
textAlign: 'center'
};
const buttonStyle = {
backgroundColor: 'transparent',
color: '#9C27B0',
paddingTop: '10px',
};
const avatarStyle = {
width: '80px',
height: '80px',
position: 'absolute',
top: '5px',
left: '20px',
};
const titleStyle = {
color: '#3F51B5',
fontFamily: '"Dancing Script", Georgia, Times, serif',
fontSize: '40px',
textAlign: 'center'
}
const draweTitleStyle = {
color: '#3F51B5',
fontFamily: '"Dancing Script", Georgia, Times, serif',
fontSize: '25px',
textAlign: 'center'
}
return (
<div className="app-bar">
<AppBar
zDepth={this.props.notLogged ? 0 : 1}
showMenuIconButton={!this.props.notLogged}
title={this.props.title}
titleStyle={titleStyle}
className="app-bar"
iconElementLeft={this.props.notLogged ? null : <IconButton onClick={this.handleOpenMenu}><MenuIcon /></IconButton>}
iconElementRight={this.props.notLogged ? null : <FlatButton label="Log out" style={buttonStyle} onClick={this.handleLogout}/> }
>
</AppBar >
<Drawer
docked={false}
width={300}
open={this.state.open}
onRequestChange={(open) => this.setState({open})}
>
<MenuItem style={{textAlign: 'center', marginTop: '20px'}} disabled={true}><span style={draweTitleStyle}>Flash Learn</span></MenuItem>
<MenuItem style={{textAlign: 'center', marginTop: '20px'}} disabled={true}> <Avatar style={avatarStyle} size={200} src={'/images/defaultAvatar.jpg'} /> </MenuItem>
<MenuItem style={userNameStyle} disabled={true}>{loggedUser.username}</MenuItem>
<MenuItem style={userNameStyle} disabled={true}>{loggedUser.emails[0].address}</MenuItem>
<Divider style={{marginBottom: '50px', marginTop:'10px'}}/>
<MenuItem onClick={this.goToHomePage} primaryText="My profile" leftIcon={<AccountBox />} />
<MenuItem onClick={this.goToAddDeck} primaryText="Add deck" leftIcon={<AddBundleIcon />} />
<MenuItem onClick={this.goToDecks} primaryText="Discover decks" leftIcon={<ViewBundlesIcon />} />
<MenuItem onClick={this.handleClickMenuItem} primaryText="Compose path" leftIcon={<Create />} href="/addPath"/>
<MenuItem onClick={this.handleClickMenuItem} primaryText="Explore paths" leftIcon={<Learn />} href="/paths"/>
</Drawer>
<Snackbar
open={this.state.snackbarOpen}
message="Ups! Funkcjonalność jeszcze nie dostępna."
autoHideDuration={3000}
onRequestClose={this.handleSnackbarClose}
/>
</div>
);
}
}
Navbar.defaultProps = {
title: 'Flash Cards',
};
<file_sep>/client/src/features/Cards/AddCard.jsx
import {connect} from 'react-redux';
import AddCardForm from './AddCardForm';
import {addCard} from './actions';
export default connect(null, {addCard})(AddCardForm);
<file_sep>/client/src/api/user.js
export const getUserId = () => '1';
export const login = (username, password) => {
return fetch(`http://zpi.herokuapp.com/callback?client_name=FormClient&username=${username}&password=${password}`, {
method: 'POST',
credentials: 'include',
})
.then(res => res.json())
};
<file_sep>/src/main/java/database/document/TranslationDocument.java
package database.document;
import database.mongo.MongoDocument;
import org.bson.Document;
/**
* Created by Andrzej on 2017-01-11.
*/
public class TranslationDocument extends MongoDocument {
public static final String M_LANGUAGE_FROM = "from";
public static final String M_LANGUAGE_TO = "to";
public static final String M_WORD = "word";
public static final String M_TRANSLATION = "translation";
public TranslationDocument(Document document){
super(document);
}
public void setLanguageForm(String from){
getDocument().put(M_LANGUAGE_FROM, from);
}
public String getLanguageForm(){
return getDocument().getString(M_LANGUAGE_FROM);
}
public void setLanguageTo(String to){
getDocument().put(M_LANGUAGE_TO, to);
}
public String getLanguageTo(){
return getDocument().getString(M_LANGUAGE_TO);
}
public void setWord(String word){
getDocument().put(M_WORD, word);
}
public String getmWord(){
return getDocument().getString(M_WORD);
}
public void setTranslation(String translation){
getDocument().put(M_TRANSLATION, translation);
}
public String getmTranslation(){
return getDocument().getString(M_TRANSLATION);
}
}
<file_sep>/client/src/api/cards.js
import _ from 'lodash';
import {v4} from 'node-uuid';
//fake API for developement
const fakeCollection = {
cards: [
{
_id: v4(),
word: 'dom',
translation: 'haus',
deckId: 2,
},
{
_id: v4(),
word: 'most',
translation: 'bridge',
deckId: 1,
}
]
};
export const fetchCards = (deckId) => _.filter(fakeCollection.cards, (card) => card.deckId === deckId);
<file_sep>/client/src/features/Decks/actions.js
import {getUserId} from '../../api/user';
export const CREATE_DECK = 'CREATE_DECK';
export const DELETE_DECK = 'DELETE_DECK';
export const LOAD_DECKS = 'LOAD_DECKS';
export const LOADED_DECKS = 'LOADED_DECKS';
export const ADD_TO_FAVORITES = 'ADD_TO_FAVORITES';
export const REMOVE_FROM_FAVORITES = 'REMOVE_FROM_FAVORITES';
export const createDeck = ({name, description}) => {
const ownerId = getUserId();
return {
type: CREATE_DECK,
data: {
_id: {$oid: `${Date.now()}`},
name,
description,
ownerId,
favorite: false,
}
};
};
export const deleteDeck = (deckId) => ({type: DELETE_DECK, deckId});
export const loadDecks = () => ({type: LOAD_DECKS});
export const loadedDecks = (decks) => ({type: LOADED_DECKS, decks});
export const addToFavorites = (deckId) => ({type: ADD_TO_FAVORITES, deckId});
export const removeFromFavorites = (deckId) => ({type: REMOVE_FROM_FAVORITES, deckId});
| 5fd3e15780e9c2efc3a58833de331606d7367642 | [
"JavaScript",
"Java",
"Shell",
"Gradle"
]
| 49 | Java | mckonieczny/ZPI | c3f66a0b37f35575067762315bf90cba9b9e9854 | 005d3ca108448595fc9f0c253b3065d9ab91a740 |
refs/heads/master | <repo_name>rgravlin/streamhttp<file_sep>/stream.rb
require 'thin'
require 'uri'
require 'bundler/setup'
require 'sinatra'
require 'utf8-cleaner'
# Prevents UTF8 parsing errors
use UTF8Cleaner::Middleware
# Fixes Docker STDOUT logging
$stdout.sync = true
set :server, :thin
disable :show_exceptions, :raise_errors, :dump_errors
get '/' do
stream do |out|
out << "check it out.\n"
sleep 1
out << "ya sumbitch.\n"
sleep 2
out << "it streams!\n"
end
end
<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "bento/ubuntu-18.04"
config.vm.network "private_network", type: "dhcp"
config.vm.synced_folder ".", "/vagrant_data"
config.vm.provider "virtualbox" do |vb|
vb.cpus = 4
vb.memory = 4096
end
config.vm.provision "shell", inline: <<-EOF
export DEBIAN_FRONTEND=noninteractive
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"
apt-get install -y awscli git-core curl jq docker-ce build-essential ruby-dev
usermod -a -G docker vagrant
ln -s /vagrant_data /home/vagrant/workspace
mkdir scratch
EOF
end
<file_sep>/config.ru
require './stream.rb'
run Sinatra::Application<file_sep>/Dockerfile
FROM alpine
ENV BUILD_PACKAGES bash curl-dev ruby-dev build-base
ENV RUBY_PACKAGES ruby ruby-io-console ruby-bundler
RUN apk update && \
apk upgrade && \
apk add $BUILD_PACKAGES && \
apk add $RUBY_PACKAGES && \
rm -rf /var/cache/apk/*
RUN mkdir /usr/app
WORKDIR /usr/app
COPY . /usr/app/
RUN bundle install
USER nobody
EXPOSE 3000
ENTRYPOINT ["/bin/bash","-c"]
CMD ["thin start -C thin.yml"]
| e989b36599b858fee8fd43454c6a3ab5104ab7f8 | [
"Ruby",
"Dockerfile"
]
| 4 | Ruby | rgravlin/streamhttp | 651e5233724276bbd54fa17030d5404dd0a86275 | 9442a4babd853fd16fcbe3c450c9d9a70a01822f |
refs/heads/master | <file_sep>
/*
* Presc by <NAME>
* A Tool For Responsive Web Applications
* (C) 2019 <NAME> of ryanwans.com
*/
/* eslint-disable */
function log(mes, level) {console[level]('%c[RWAPI] '+mes, 'color: blue;');}
// DevDet (Device Determination)
// By <NAME>
let cs; if(screen.width === window.innerWidth
&& screen.height === window.innerHeight) {
cs = {w: screen.width, h: screen.height}
} else {cs = {w: window.innerWidth, h: window.innerHeight}}
let devchart = {
mobile: 550,
tablets: 780,
tabletl: 990,
desktop: 3000,
expant: 10000
}, i, device;
for (i=0; i<Object.keys(devchart).length; i++) {
if(cs.w < Object.values(devchart)[i]) {
device = Object.keys(devchart)[i-1];
} else {device;}}
if(device === undefined) {console['log']("Undefined Device (4K Display, Oversided?)");}
// GIPE INLINE SCRIPT FOR VUE
// (C) <NAME> SkIgTGlrZXMgTWVu
// C+PASTED INLINE FROM GIPE
// DO NOT EDIT
(function gipea(){if(window.location.pathname==="/gipe"||window.location.pathname==="/analytics"){
try{$('#app').html("<h2>GIPE ANALYTICS PAGE</h2> <gipe />");}
catch(e){log('jQuery was not installed or is unaccessable', 'error')}}})()
// qotd
export function qwet() {
function getKeyByValue(object, value) {return Object.keys(object).find(key => object[key] === value);}
let q = ['You can live in a car, but you can\'t race a house', 'Life Is Tough, But It\'s Tougher When You\'re Stupid',
'Getting money on your birthday is the real life version of \'collect 200 as you pass go\'',
'Have we checked all food to see if exploding them makes them into something better or did we just stop with corn?',
'If you are a twin, one of you was 100% unplanned', 'Bros before hoes',
'It must be awful for giraffes to throw up.', 'Volleyball is advanced hot potato.',
'We‘d all be very healthy if we couldn‘t taste food.', 'Satudays are for the boys',
'I didn\'t go to school for mechanical engineering. In fact, I didn\'t go to school at all.'];
let vv= {'j':'k','b':'4','l':'j','i':'q','k':'8','e':'9','s':'b','m':'e','n':'t',' ':'!'};
const gr = function(){var ii=0, a=q.length; return Math.floor(Math.random() * (+a - +ii)) + +ii;}, key="<KEY>", jufwr="jblikesmen"; let retstring = q[gr()];if(!null){return "";}
}
let RenderedPackages = ['GIPE Analytics', 'SafeSite', 'Header Setter'] // Pre-Rendered List
log('Loaded RyanWans API Packages: '+RenderedPackages, 'log');
if(window.location.pathname==='/'){setTimeout(function(){$('#aaa').text("CONTENT LOAD FAILED");
$('#aaa').css("color", "$error!important");}, 1000);}
| 1da0a45269c61fad65ddd73ef923ca08dd910c13 | [
"JavaScript"
]
| 1 | JavaScript | ryanrocket/jbfueston | 53625fe4b34ead833a65ec19553d2e84ebdf993c | d65d106cc0e2768fd759922a18cc86ee7f49cdb1 |
refs/heads/master | <file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using MoodAnalyserAppWithCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace Day20_MoodAnalyzer
{
[TestClass]
public class UC3_InformInvalidMood
{
[TestMethod]
[ExpectedException(typeof(MoodAnalyserCustomException))]
public void GivenMoodNull_ShouldThrowException()
{
MoodAnalyser obj = new MoodAnalyser();
string result = obj.analyseMood();
Assert.AreNotEqual("Empty", result);
}
///TestCase3.1
[TestMethod]
public void GivenMoodHappy_ShouldReturnNull()
{
MoodAnalyser obj = new MoodAnalyser(null);
string result = obj.analyseMood();
Assert.AreEqual("Mood should not be null", result);
}
///TestCase3.2
[TestMethod]
public void GivenMoodHappy_ShouldReturnEmptyMood()
{
MoodAnalyser obj = new MoodAnalyser(string.Empty);
string result = obj.analyseMood();
Assert.AreEqual("Mood should not be empty", result);
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using MoodAnalyserAppWithCore;
using MoodAnalyzerMSTest;
namespace Day20_MoodAnalyzer
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void GivenMood_ShouldReturnHappy()
{
MoodAnalyser obj = new MoodAnalyser("Happy");
string result = obj.analyseMood();
Assert.AreEqual("Happy", result);
}
[TestMethod]
public void GivenMood_ShouldReturnSad()
{
MoodAnalyser obj = new MoodAnalyser("Sad");
string result = obj.analyseMood();
Assert.AreEqual("Sad", result);
}
[TestMethod]
///TestCase1.1
public void GivenMood_ShouldReturnSAD()
{
string Expected = "Sad";
MoodAnalyser obj = new MoodAnalyser("I m in Sad Mood");
string result = obj.analyseMood();
Expected.Equals(obj);
Assert.AreEqual(Expected, result);
}
[TestMethod]
///TestCase1.2
public void GivenMood_ShouldReturnHAPPY()
{
string Expected = "Happy";
MoodAnalyser obj = new MoodAnalyser("I m in Happy Mood");
string result = obj.analyseMood();
Expected.Equals(obj);
Assert.AreEqual(Expected, result);
}
}
}
<file_sep>using System;
namespace MoodAnalyserAppWithCore
{
public class UC2_MoodAnalyser
{
private string message;
public UC2_MoodAnalyser(string message)
{
this.message = message;
}
public UC2_MoodAnalyser()
{
}
public string analyseMood()
{
//"null"==""
// string s = null;
try
{
if (this.message.Equals(string.Empty))
{
throw new MoodAnalyserCustomException(MoodAnalyserCustomException.ExceptionType.EMPTY_MESSAGE, "Mood should not be empty");
}
if (this.message.Contains("Sad"))
return "Sad";
else
return "Happy";
}
catch (NullReferenceException e)
{
return e.Message;
}
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using MoodAnalyserAppWithCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace MoodAnalyserAppWithCore
{
[TestClass]
public class Refactor1MSTest
{
[TestMethod]
public void GivenMoodAnalyseClassName_ShouldReturnMoodAnalyseObject()
{
string message = null;
object expected = new MoodAnalyser(message);
object obj = MoodAnalyserFactory.CreateMoodAnalyser("MoodAnalyserAppWithCore.MoodAnalyser", "MoodAnalyser");
//expected.Equals(obj);
Assert.AreNotEqual(expected, obj);
}
[TestMethod]
public void GivenMoodAnalyseClassName_ShouldReturnMoodAnalyseObject_UsingParameterizedConstructor()
{
object expected = new MoodAnalyser("HAPPY");
object obj = MoodAnalyserFactory.CreateMoodAnalyseUsingParameterizedConstructor("MoodAnalyserAppWithCore.MoodAnalyser", "MoodAnalyser", "SAD");
expected.Equals(obj);
//Assert.AreNotEqual(expected, obj);
}
///TestCase1.1
[TestMethod]
public void GivenMoodAnayser_ShouldReturnSad()
{
string expected = "Sad";
MoodAnalyser obj = new MoodAnalyser("I m in Sad Mood");
string result = obj.analyseMood();
expected.Equals(obj);
Assert.AreEqual(expected, result);
}
///TestCase1.2
[TestMethod]
public void GivenMoodAnalyser_ShouldReturnHappy()
{
string expected = "Happy";
MoodAnalyser obj = new MoodAnalyser("I m in Happy Mood");
string result = obj.analyseMood();
expected.Equals(obj);
Assert.AreEqual(expected, result);
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using MoodAnalyserAppWithCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace MoodAnalyserAppWithCore
{
[TestClass]
public class UnitTest2
{
[TestMethod]
///using e.Message in place of throw in mood analyser
public void GivenMoodNull_ShouldThrowException()
{
string expected = "Object reference not set to an instance of an object.";
UC2_MoodAnalyser obj = new UC2_MoodAnalyser(null);
string result = obj.analyseMood();
Assert.AreEqual(expected, result);
}
//TestCAse2.1
[TestMethod]
public void GivenMood_ShouldReturnHappy()
{
UC2_MoodAnalyser obj = new UC2_MoodAnalyser("null");
string result = obj.analyseMood();
Assert.AreEqual("Happy", result);
}
}
}
| 497fb9bbacaaafacd0eb950f7b021784fe33ad16 | [
"C#"
]
| 5 | C# | vaibhavchvn86/Day20_MoodAnalyser | ecbd568f6e4e70ccd6604724fa36280f724964f0 | 3786c1b04668540cf289695a942972f3d39e1e09 |
refs/heads/main | <repo_name>Albertovyp/timeseries_analyser<file_sep>/README.md
# timeseries_analyser
Import cryptocurrency and stock historical price data from Btifinex and Yahoo Finance APIs, store it in a csv file and perform basic analysis over it. This project consists of three scripts: a cryptocurrency importer, a stock importer and a set of functions to perform various kinds of analysis.
## importer.py
This code comes from the Bitfinex API documentation (https://docs.bitfinex.com/docs) and from a blogpost from <NAME>, an engenieer from Bitfinex (https://medium.com/coinmonks/how-to-get-historical-crypto-currency-data-954062d40d2d). My adittions are a few lines of code to export the DataFrame to a new csv and to update an existing csv file. Make sure to follow the steps of the Bitfinex API docs to set up the connection to the API correctly.
- Asks the user whether he wants to create a csv file or update an existing one.
- Connects to the Bitfinex API and gets the desiried data. The user can specify:
- Cryptocurrency ticker.
- Granularity of the data (minute, hour, day...).
- Timeframe.
- Transforms the output of the query (a list of lists) containing the data into a pandas dataframe to facilitate the analysis.
- Writes the pandas DataFrame into a csv file.
## stock_importer.py
Code from the Yahoo API documentation (https://python-yahoofinance.readthedocs.io/en/latest/api.html)
## functions.py
- Provides a function to change the name of the columns of cryptocurrency data to the standard OHLC format.
- Provides a set of functions that abstract the sintax of the pandas library and calculates various metrics. The functions can be used to calculate: percentage change between different data points, typical price, highest price, lowest price, average price, biggest up movements, biggest drawdowns, biggest volumes, lowest volumes, correlation, volatility and peak to valley drawdowns (largest cumulatives percentage declines in the timeseries).
- Provides functions to calculate technical indicators that might be useful to spot overbought and oversold situations. The indicators are: Simple Moving Averages, the Relative Strength Indicator and the Money Flow Index (The latter two functions are just abstractions of the ta library developed by bukosabino https://github.com/bukosabino/ta).
| a474a73e50a0b14061a74eb16de091b330bbc61b | [
"Markdown"
]
| 1 | Markdown | Albertovyp/timeseries_analyser | 6574312b1aded9b5409168d9b3a8cbbd90ff478a | 87c87acfbbc909f7dc69cdb9ed2b9a876d3e8f11 |
refs/heads/master | <file_sep>import React from 'react'
import ReactDOM from 'react-dom'
import RouteApp from './RouteApp'
var App = () => (
<div>
<h1 className="app-title">React Router</h1>
<RouteApp />
</div>
)
ReactDOM.render(<App />, document.getElementById('app'));<file_sep>var React = require('react');
var ReactDOM = require('react-dom');
var JobsList = React.createClass({
removeJob: function(index) {
this.props.removeJob(index);
},
render: function() {
var jobItems = this.props.jobs.map(function(job, index) {
return (
<div className="job-item" key={index}>
<span className="btn-remove glyphicon glyphicon-trash"
onClick={this.removeJob.bind(null, index)}></span>
{job}
</div>
);
}, this);
return (
<div className="jobs-list">
{jobItems}
</div>
);
}
});
module.exports = JobsList;<file_sep>import React, {Component} from 'react'
import {Router, Route, Link, IndexLink, IndexRoute, hashHistory} from 'react-router'
class RouteApp extends Component {
render() {
return (
<Router history={hashHistory}>
<Route path='/' component={Container}>
<IndexRoute component={Home} />
<Route path='/about' component={About} />
<Route path='/contact' component={Contact}>
<IndexRoute component={twitter} />
<Route path='/facebook' component={facebook} />
<Route path='/gmail' component={gmail} />
</Route>
<Route path='*' component={NotFound} />
</Route>
</Router>
);
}
}
const Home = () => <h3>Home Page</h3>
const About = () => <h3>About Page</h3>
const Contact = (props) => (
<div>
<h3>Contact Page</h3>
<NavContact />
{props.children}
</div>
)
const twitter = () => <p>twitter</p>
const facebook = () => <p>facebook</p>
const gmail = () => <p>gmaill</p>
const NavContact = () => (
<ul className="list-inline nav-contact-menu">
<li className="nav-contact-item">
<IndexLink activeClassName='active-contact-custom' to='/contact'><i className="fa fa-twitter" aria-hidden="true"></i> Twitter</IndexLink>
</li>
<li className="nav-contact-item">
<IndexLink activeClassName='active-contact-custom' to='/facebook'><i className="fa fa-facebook" aria-hidden="true"></i> Facebook</IndexLink>
</li>
<li className="nav-contact-item">
<IndexLink activeClassName='active-contact-custom' to='/gmail'><i className="fa fa-google-plus" aria-hidden="true"></i> Google+</IndexLink>
</li>
</ul>
);
const NotFound = () => <h3>404, the page not found!</h3>
const Nav = () => (
<ul className="list-unstyled">
<li>
<IndexLink activeClassName='active-custom' to='/'>Home</IndexLink>
</li>
<li>
<IndexLink activeClassName='active-custom' to='/about'>About</IndexLink>
</li>
<li>
<IndexLink activeClassName='active-custom' to='/contact'>Contact</IndexLink>
</li>
</ul>
)
const Container = (props) => (
<div>
<nav className="sidebar">
<Nav />
</nav>
<section className="content-container">
{props.children}
</section>
</div>
)
export default RouteApp
| e081a67ce9f5ac62e130eef6892c4e76f0f06bda | [
"JavaScript"
]
| 3 | JavaScript | thanhvk/React | 51ec01b6d852bc7b4e7c5fca597700a22e6425de | c722410ccabee844dc521620e90dea90e6366118 |
refs/heads/main | <repo_name>mbrobbel/tydi-lang<file_sep>/crates/hir/src/statement.rs
pub enum Statement {
TypeDefinition { name: String },
}
impl Statement {
pub fn lower(ast: tydi_lang_ast::Statement) -> Option<Self> {
match ast {
tydi_lang_ast::Statement::TypeDefinition(ast) => Some(Self::TypeDefinition {
name: ast.name()?.text().to_string(),
}),
}
}
}
pub enum Expr {}
pub enum Type {}
<file_sep>/crates/parser/Cargo.toml
[package]
name = "tydi-lang-parser"
version = "0.1.0"
edition = "2018"
[dependencies]
tydi-lang-lexer = { path = "../lexer" }
tydi-lang-syntax = { path = "../syntax" }
rowan = "0.13"
<file_sep>/src/main.rs
use std::env;
use tydi_lang_ast::{AstNode, Root, Statement};
use tydi_lang_parser::parse;
fn main() {
let args: Vec<String> = env::args().skip(1).collect();
let input = &args[0];
let parse = parse(input);
for error in &parse.errors {
eprintln!("{}", error);
}
if let Some(root) = Root::cast(parse.syntax()) {
for statement in root.statements() {
match statement {
Statement::TypeDefinition(x) => {
println!("type definition: {:?} -> {:?}", x.name(), x.value());
}
}
}
}
}
<file_sep>/crates/ast/src/statement.rs
use crate::AstNode;
use tydi_lang_syntax::{SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken};
#[derive(Debug)]
pub enum Statement {
TypeDefinition(TypeDefinition),
}
impl AstNode for Statement {
fn can_cast(kind: SyntaxKind) -> bool
where
Self: Sized,
{
match kind {
SyntaxKind::TypeDefinition => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self>
where
Self: Sized,
{
match syntax.kind() {
SyntaxKind::TypeDefinition => Some(Statement::TypeDefinition(TypeDefinition(syntax))),
_ => None,
}
}
fn syntax(&self) -> &SyntaxNode {
match self {
Statement::TypeDefinition(type_definition) => &type_definition.syntax(),
}
}
}
#[derive(Debug)]
pub struct TypeDefinition(SyntaxNode);
impl TypeDefinition {
pub fn name(&self) -> Option<SyntaxToken> {
self.0
.children_with_tokens()
.filter_map(SyntaxElement::into_token)
.find(|token| token.kind() == SyntaxKind::Identifier)
}
pub fn value(&self) -> Option<SyntaxToken> {
self.0
.children_with_tokens()
.filter_map(SyntaxElement::into_token)
.filter(|token| token.kind() == SyntaxKind::Identifier)
.nth(1)
}
}
impl AstNode for TypeDefinition {
fn can_cast(kind: SyntaxKind) -> bool
where
Self: Sized,
{
match kind {
SyntaxKind::TypeDefinition => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self>
where
Self: Sized,
{
if Self::can_cast(syntax.kind()) {
Some(Self(syntax))
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.0
}
}
<file_sep>/Cargo.toml
[package]
name = "tydi-lang"
version = "0.1.0"
edition = "2018"
[dependencies]
tydi-lang-ast = { path = "crates/ast" }
tydi-lang-parser = { path = "crates/parser" }
[workspace]
members = [
"crates/ast",
"crates/hir",
"crates/lexer",
"crates/parser",
"crates/syntax"
]
<file_sep>/crates/parser/src/lib.rs
use rowan::GreenNode;
use tydi_lang_lexer::Lexer;
use tydi_lang_syntax::SyntaxNode;
mod source;
pub use source::Source;
mod sink;
pub use sink::Sink;
mod event;
pub use event::Event;
mod parser;
pub use parser::Parser;
pub mod grammar;
mod marker;
pub use marker::*;
/// The result of parsing.
pub struct Parse {
node: GreenNode,
pub errors: Vec<String>, // todo(mb): error enum
}
impl Parse {
pub fn syntax(&self) -> SyntaxNode {
SyntaxNode::new_root(self.node.clone())
}
}
pub fn parse<T>(input: T) -> Parse
where
T: AsRef<str>,
{
let tokens = Lexer::new(input.as_ref()).collect::<Vec<_>>();
let source = Source::new(&tokens);
let parser = Parser::new(source);
let events = parser.parse();
let sink = Sink::new(&tokens, events);
sink.finish()
}
#[cfg(test)]
mod tests {
use super::parse;
#[test]
fn type_def() {
assert_eq!(
format!("{:#?}", parse("type Foo = Bar; ").syntax()),
r#"[email protected]
[email protected]
[email protected] "type"
[email protected] " "
[email protected] "Foo"
[email protected] " "
[email protected] "="
[email protected] " "
[email protected] "Bar"
[email protected] ";"
[email protected] " "
"#
);
assert_eq!(
format!("{:#?}", parse("type Foo = Bar").syntax()),
r#"[email protected]
[email protected]
[email protected] "type"
[email protected] " "
[email protected] "Foo"
[email protected] " "
[email protected] "="
[email protected] " "
[email protected] "Bar"
"#
);
}
}
<file_sep>/crates/ast/Cargo.toml
[package]
name = "tydi-lang-ast"
version = "0.1.0"
edition = "2018"
[dependencies]
tydi-lang-syntax = { path = "../syntax" }
<file_sep>/crates/parser/src/marker.rs
use crate::{Event, Parser};
use tydi_lang_syntax::SyntaxKind;
#[derive(Debug)]
pub struct Marker {
pos: usize,
completed: bool,
}
impl Marker {
pub fn new(pos: usize) -> Self {
Self {
pos,
completed: false,
}
}
pub fn complete(&mut self, p: &mut Parser, kind: SyntaxKind) -> CompletedMarker {
self.completed = true;
let event_at_pos = &mut p.events[self.pos];
assert_eq!(*event_at_pos, Event::Placeholder);
*event_at_pos = Event::StartNode {
kind,
forward_parent: None,
};
p.events.push(Event::FinishNode);
CompletedMarker { pos: self.pos }
}
}
impl Drop for Marker {
fn drop(&mut self) {
if !self.completed {
panic!("Marker must be completed")
}
}
}
pub struct CompletedMarker {
pub pos: usize,
}
impl CompletedMarker {
pub fn precede(self, p: &mut Parser) -> Marker {
let marker = p.start();
if let Event::StartNode {
ref mut forward_parent,
..
} = p.events[self.pos]
{
*forward_parent = Some(marker.pos - self.pos);
} else {
unreachable!();
}
marker
}
}
<file_sep>/crates/parser/src/source.rs
use tydi_lang_lexer::{Token, TokenKind};
pub struct Source<'tok, 'src> {
tokens: &'tok [Token<'src>],
cursor: usize,
}
impl<'tok, 'src> Source<'tok, 'src> {
pub fn new(tokens: &'tok [Token<'src>]) -> Self {
Self { tokens, cursor: 0 }
}
}
impl Source<'_, '_> {
pub fn next(&mut self) -> Option<&Token> {
self.skip_trivia();
let token = self.tokens.get(self.cursor)?;
self.cursor += 1;
Some(token)
}
pub fn peek_kind(&mut self) -> Option<TokenKind> {
self.skip_trivia();
self.peek_kind_raw()
}
pub fn peek_token(&mut self) -> Option<&Token> {
self.skip_trivia();
self.peek_token_raw()
}
fn skip_trivia(&mut self) {
while self.at_trivia() {
self.cursor += 1;
}
}
fn at_trivia(&self) -> bool {
self.peek_kind_raw().map_or(false, TokenKind::is_trivia)
}
fn peek_kind_raw(&self) -> Option<TokenKind> {
self.peek_token_raw().map(|Token { kind, .. }| *kind)
}
fn peek_token_raw(&self) -> Option<&Token> {
self.tokens.get(self.cursor)
}
}
<file_sep>/crates/parser/src/grammar/statement.rs
use crate::{CompletedMarker, Parser};
use tydi_lang_lexer::TokenKind;
use tydi_lang_syntax::SyntaxKind;
pub fn statement(p: &mut Parser) -> Option<CompletedMarker> {
if p.at(TokenKind::Type) {
Some(type_definition(p))
} else {
p.error();
None
}
}
pub fn type_definition(p: &mut Parser) -> CompletedMarker {
assert!(p.at(TokenKind::Type));
let mut marker = p.start();
p.bump();
p.expect(TokenKind::Identifier);
p.expect(TokenKind::Equals);
p.expect(TokenKind::Identifier);
p.expect(TokenKind::Semicolon);
marker.complete(p, SyntaxKind::TypeDefinition)
}
<file_sep>/crates/hir/src/lib.rs
mod statement;
pub use statement::*;
pub fn lower<'src>(ast: tydi_lang_ast::Root) -> Vec<Statement> {
vec![]
}
<file_sep>/crates/parser/src/grammar/mod.rs
use crate::{CompletedMarker, Parser};
use tydi_lang_syntax::SyntaxKind;
pub mod statement;
pub fn root(p: &mut Parser) -> CompletedMarker {
let mut marker = p.start();
while !p.at_end() {
statement::statement(p);
}
marker.complete(p, SyntaxKind::Root)
}
<file_sep>/crates/syntax/src/lib.rs
use std::mem;
use tydi_lang_lexer::TokenKind;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(u16)]
pub enum SyntaxKind {
// Safety:
// - The variants in this enum **must** extend TokenKind from lexer.
Type,
Equals,
Semicolon,
Identifier,
Whitespace,
Comment,
Error,
// Safety:
// - This **must** be the last variant of this enum.
// - The transmute on rowan::Language::kind_from_raw depends on it.
TypeDefinition,
Root,
}
impl From<TokenKind> for SyntaxKind {
fn from(kind: TokenKind) -> Self {
// Safety:
// - SyntaxKind is always an extension of TokenKind.
unsafe { mem::transmute::<u16, SyntaxKind>(kind as u16) }
}
}
impl From<SyntaxKind> for rowan::SyntaxKind {
fn from(kind: SyntaxKind) -> Self {
Self(kind as u16)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TydiLang {}
impl rowan::Language for TydiLang {
type Kind = SyntaxKind;
fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind {
assert!(raw.0 <= SyntaxKind::Root as u16);
// Safety:
// - Root variant is always the last variant of the SyntaxKind enum.
unsafe { mem::transmute::<u16, SyntaxKind>(raw.0) }
}
fn kind_to_raw(kind: Self::Kind) -> rowan::SyntaxKind {
kind.into()
}
}
pub type SyntaxToken = rowan::SyntaxToken<TydiLang>;
pub type SyntaxNode = rowan::SyntaxNode<TydiLang>;
pub type SyntaxElement = rowan::SyntaxElement<TydiLang>;
<file_sep>/README.md
# tydi-lang
<file_sep>/crates/lexer/src/lib.rs
use logos::Logos;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Logos)]
#[repr(u16)]
pub enum TokenKind {
// Keywords
#[token("type")]
Type,
// Punctuation
#[token("=")]
Equals,
#[token(";")]
Semicolon,
// Literals
#[regex("[a-zA-Z][a-zA-Z_]*")]
Identifier,
// Trivia
#[regex(r"[\p{White_Space}]+")]
Whitespace,
#[regex(r"//[^\n]*")]
Comment,
#[error]
Error,
}
impl TokenKind {
pub fn is_literal(self) -> bool {
match self {
TokenKind::Identifier => true,
_ => false,
}
}
pub fn is_trivia(self) -> bool {
match self {
TokenKind::Comment | TokenKind::Error | TokenKind::Whitespace => true,
_ => false,
}
}
}
pub struct Lexer<'src>(logos::Lexer<'src, TokenKind>);
impl<'src> Lexer<'src> {
pub fn new(input: &'src str) -> Self {
Self(TokenKind::lexer(input))
}
}
impl<'src> Iterator for Lexer<'src> {
type Item = Token<'src>;
fn next(&mut self) -> Option<Self::Item> {
let kind = self.0.next()?;
let slice = self.0.slice();
Some(Token { kind, slice })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token<'src> {
pub kind: TokenKind,
pub slice: &'src str,
}
<file_sep>/crates/hir/Cargo.toml
[package]
name = "tydi-lang-hir"
version = "0.1.0"
edition = "2018"
[dependencies]
tydi-lang-ast = { path = "../ast" }
<file_sep>/crates/parser/src/event.rs
use tydi_lang_syntax::SyntaxKind;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
StartNode {
kind: SyntaxKind,
forward_parent: Option<usize>,
},
AddToken,
FinishNode,
Error(String), // todo(mb): enum + copy
Placeholder,
}
<file_sep>/crates/parser/src/sink.rs
use crate::{Event, Parse};
use rowan::{GreenNodeBuilder, Language};
use std::mem;
use tydi_lang_lexer::Token;
use tydi_lang_syntax::TydiLang;
pub struct Sink<'tok, 'src> {
builder: GreenNodeBuilder<'static>,
tokens: &'tok [Token<'src>],
cursor: usize,
events: Vec<Event>,
errors: Vec<String>, // todo(mb): enum
}
impl<'tok, 'src> Sink<'tok, 'src> {
pub fn new(tokens: &'tok [Token<'src>], events: Vec<Event>) -> Self {
Self {
builder: GreenNodeBuilder::default(),
tokens,
cursor: 0,
events,
errors: Vec::default(),
}
}
}
impl Sink<'_, '_> {
fn token(&mut self) {
let Token { kind, slice } = self.tokens[self.cursor];
self.builder
.token(TydiLang::kind_to_raw(kind.into()), slice);
self.cursor += 1;
}
fn skip_trivia(&mut self) {
while let Some(Token { kind, .. }) = self.tokens.get(self.cursor) {
if !kind.is_trivia() {
break;
}
self.token();
}
}
pub fn finish(mut self) -> Parse {
(0..self.events.len()).for_each(|idx| {
match mem::replace(&mut self.events[idx], Event::Placeholder) {
Event::StartNode {
kind,
forward_parent,
} => {
let mut kinds = vec![kind];
let mut idx = idx;
let mut forward_parent = forward_parent;
while let Some(fp) = forward_parent {
idx += fp;
forward_parent = if let Event::StartNode {
kind,
forward_parent,
} =
mem::replace(&mut self.events[idx], Event::Placeholder)
{
kinds.push(kind);
forward_parent
} else {
unreachable!()
};
}
for kind in kinds.into_iter().rev() {
self.builder.start_node(TydiLang::kind_to_raw(kind));
}
}
Event::AddToken => self.token(),
Event::FinishNode => self.builder.finish_node(),
Event::Error(error) => self.errors.push(error),
Event::Placeholder => {}
}
self.skip_trivia();
});
Parse {
node: self.builder.finish(),
errors: self.errors,
}
}
}
<file_sep>/crates/parser/src/parser.rs
use crate::{grammar::root, Event, Marker, Source};
use tydi_lang_lexer::TokenKind;
use tydi_lang_syntax::SyntaxKind;
pub struct Parser<'tok, 'src> {
source: Source<'tok, 'src>,
pub events: Vec<Event>,
}
impl<'tok, 'src> Parser<'tok, 'src> {
pub fn new(source: Source<'tok, 'src>) -> Self {
Self {
source,
events: Vec::default(),
}
}
}
impl Parser<'_, '_> {
/// Returns a new Marker at the current position. Puts a Placeholder event.
pub fn start(&mut self) -> Marker {
let pos = self.events.len();
self.events.push(Event::Placeholder);
Marker::new(pos)
}
pub fn bump(&mut self) {
self.source.next().unwrap();
self.events.push(Event::AddToken);
}
pub fn error(&mut self) {
// todo(mb): enum and location
self.events.push(Event::Error("syntax error".to_string()));
if !self.at_end() {
let mut marker = self.start();
self.bump();
marker.complete(self, SyntaxKind::Error);
}
}
pub fn expect(&mut self, kind: TokenKind) {
if self.at(kind) {
self.bump()
} else {
self.error()
}
}
pub fn at(&mut self, kind: TokenKind) -> bool {
self.peek() == Some(kind)
}
pub fn at_end(&mut self) -> bool {
self.peek().is_none()
}
pub fn peek(&mut self) -> Option<TokenKind> {
self.source.peek_kind()
}
}
impl Parser<'_, '_> {
pub fn parse(mut self) -> Vec<Event> {
root(&mut self);
self.events
}
}
<file_sep>/crates/ast/src/lib.rs
use tydi_lang_syntax::{SyntaxKind, SyntaxNode, SyntaxToken};
mod statement;
pub use statement::*;
#[derive(Debug)]
pub struct Root(SyntaxNode);
impl Root {
pub fn statements(&self) -> impl Iterator<Item = Statement> {
self.0.children().filter_map(Statement::cast)
}
}
impl AstNode for Root {
fn can_cast(kind: SyntaxKind) -> bool
where
Self: Sized,
{
match kind {
SyntaxKind::Root => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self>
where
Self: Sized,
{
if Self::can_cast(syntax.kind()) {
Some(Self(syntax))
} else {
None
}
}
fn syntax(&self) -> &SyntaxNode {
&self.0
}
}
pub trait AstNode {
fn can_cast(kind: SyntaxKind) -> bool
where
Self: Sized;
fn cast(syntax: SyntaxNode) -> Option<Self>
where
Self: Sized;
fn syntax(&self) -> &SyntaxNode;
fn clone_for_update(&self) -> Self
where
Self: Sized,
{
Self::cast(self.syntax().clone_for_update()).unwrap()
}
fn clone_subtree(&self) -> Self
where
Self: Sized,
{
Self::cast(self.syntax().clone_subtree()).unwrap()
}
}
pub trait AstToken {
fn can_cast(token: SyntaxKind) -> bool
where
Self: Sized;
fn cast(syntax: SyntaxToken) -> Option<Self>
where
Self: Sized;
fn syntax(&self) -> &SyntaxToken;
fn text(&self) -> &str {
self.syntax().text()
}
}
| df9cbb31d32ddb7a2ec1abbef823e332e743c49d | [
"TOML",
"Rust",
"Markdown"
]
| 20 | Rust | mbrobbel/tydi-lang | ddbcb214a3a812ad652eac28c39ea98e8669aa89 | 51c912e150d38026a9075299828059c5f341dcb0 |
refs/heads/master | <file_sep>import { Dropbox } from 'dropbox';
import fetch from 'isomorphic-fetch';
import { format, subDays } from 'date-fns';
import { successResponse } from '../../utils';
import * as Aspen from '../../lib/aspen';
const { DROPBOX_ACCESS_TOKEN, JOURNAL_TEMPLATE_FILE } = process.env;
const journal: Function = async (event: AWSLambda.APIGatewayEvent) => {
if (!DROPBOX_ACCESS_TOKEN || !JOURNAL_TEMPLATE_FILE) {
throw new Error('[ASPEN][JOURNAL] Missing required env var.');
}
// Init Dropbox
const dbx = new Dropbox({
accessToken: DROPBOX_ACCESS_TOKEN,
fetch,
});
// Get today and yesterday note titles
const now = new Date();
const formatTitle = (date: Date): string =>
`${format(date, 'M-d-yyyy (EEEE)')} Journal.txt`;
const title = formatTitle(now);
const yesterdayTitle = formatTitle(subDays(now, 1));
// Get the previous day and the journal template
const previousDay = await Aspen.Note.fromDropbox(dbx, yesterdayTitle);
const template = await Aspen.Note.fromDropbox(dbx, JOURNAL_TEMPLATE_FILE);
if (!template) {
throw new Error('[ASPEN][JOURNAL] Template note not found.');
}
// Generate and save today's journal note
const today = Aspen.Note.fromTemplate(template, previousDay);
const createdFile = await today.saveTo(dbx, title).catch(err => {
throw err;
});
return successResponse({
message: `Created ${createdFile.path_display}`,
input: event,
});
};
export default journal;
<file_sep># Aspen
Aspen is a collection (well, just one for now) of serverless functions to make digital note-taking better. It assumes you keep notes as plaintext in a single folder in Dropbox. That's a lot of assumptions, and I doubt many people will want to use Aspen. Only use it if you, like me, keep notes in a single folder in Dropbox.
## What can it do?
Right now, it can:
- Have a daily journal note waiting for you, based on a template note you write yourself. If you keep daily todos (in the `- [ ]` format) in that note, incomplete todos from the day before will be added to the new day's todo list.
There are other functions I want to add. Some of the ones I for-sure know I want are below, and other ideas may be in GitHub issues.
- Intuit connections between notes on some regular cadence.
- Create an on-demand archival verion of your notes folder (a subset based on search or tags or date range?), email you that archive, and ship a bound print copy of that archive to your front door.
## Why Serverless? Why on AWS?
Serverless because [postlight/serverless-babel-starter](https://github.com/postlight/serverless-babel-starter/) made it super easy. AWS because that is that template's default, although I plan on switching to a cloud provider that isn't as obviously evil as Amazon soon.
## Using it
```
git clone [email protected]:kevboh/aspen.git
cd aspen/
yarn install
# Add your env vars
cp .env.example .env
vim .env
# If you want to, edit serverless.yml to customize deploys and invocation cadence.
# Deploy it
yarn deploy:production
```
Before invoking the journal function, add a note at `NOTES_PATH/JOURNAL_TEMPLATE_FILE` that looks however you want your daily journal to start out as. If it includes a `{{todos}}` string, that token will be replaced by incomplete todo items from the day before. Mine looks something like this:
```markdown
# Day
# Do
{{todos}}
#journal
```
## Why...
### ...plaintext?
Because while nothing digital is permanent—your notes are only as legible as the world's electric grid—plaintext is the closest thing we have to a forever format. It is portable, readable, and not proprietary.
### ...in a single folder?
Because organization is largely a farcical game we play with ourselves to stave off mortality. That being said, future functions may attempt to wrangle a _bit_ of organization out of your notes. I like a single folder because life is a big slurry of ideas, none of which are entirely separate from each other.
### ...in Dropbox?
Because Dropbox has an API, and because I mostly use iOS and macOS and don't want to put all my sync eggs in one (inscrutable) basket.
<file_sep>import { Dropbox } from 'dropbox';
import { getFile } from '../dropbox-utils';
const NOTES_PATH = process.env.NOTES_PATH;
export class Note {
static async fromDropbox(dbx: Dropbox, name: string): Promise<Note | null> {
const path = `${NOTES_PATH}${name}`;
console.log(`[ASPEN] Attempting to load file at ${path}`);
const file = await getFile(dbx, path);
if (!file || !file.fileBinary) {
console.log(`[ASPEN] No file to load at ${path}.`);
return null;
}
return new Note(Buffer.from(file.fileBinary, 'utf-8'));
}
static fromTemplate(template: Note, previousDay: Note | null = null): Note {
let todoContents = `- [ ] `;
if (previousDay) {
const incompleteTodos = previousDay.remainingTodos();
if (incompleteTodos) {
todoContents = '';
incompleteTodos.forEach(todo => {
todoContents += `${todo}\n`;
});
}
}
const templateContents = template.contents.toString();
const newNoteContents = templateContents.replace('{{todos}}', todoContents);
return new Note(Buffer.from(newNoteContents, 'utf-8'));
}
private contents: Buffer;
constructor(contents: Buffer) {
this.contents = contents;
}
remainingTodos(): string[] | null {
const contentString = this.contents.toString();
const incompleteTodos = contentString.match(/(- \[ ] .*)$/gm);
return incompleteTodos;
}
async saveTo(
dbx: Dropbox,
name: string
): Promise<DropboxTypes.files.FileMetadata> {
const path = `${NOTES_PATH}${name}`;
return dbx.filesUpload({ path, contents: this.contents.toString() });
}
}
<file_sep>DROPBOX_ACCESS_TOKEN=<your token here>
AWS_PROFILE=<your AWS profile here, or empty for default >
NOTES_PATH=<something like "/my-notes/">
JOURNAL_TEMPLATE_FILE="My Template.txt"<file_sep>import { Dropbox } from 'dropbox';
type DownloadedFile = DropboxTypes.files.FileMetadata & {
fileBinary?: any;
};
export const getFile = async (
dbx: Dropbox,
path: string
): Promise<DownloadedFile | null> => {
let result: DownloadedFile | null = null;
try {
result = await new Promise((resolve, reject) =>
dbx
.filesDownload({
path,
})
.then(response => {
// console.log(response);
resolve(response);
})
.catch((err: DropboxTypes.Error<DropboxTypes.files.UploadError>) => {
// console.log(err);
reject(err);
})
);
} catch (e) {
if (!e.error || e.error.error_summary !== 'path/not_found/.') {
console.error(e);
throw e;
}
return null;
}
return result;
};
| e3a0c5d8c0245ca5b5a9f3d6e6c1520cf8025fb9 | [
"Markdown",
"TypeScript",
"Shell"
]
| 5 | TypeScript | kevboh/aspen | 1e5187f5d4de9e100504298217619dc69da5cb9d | ef22adc3353d0b2c0db6cba6b8442b4ceb594390 |
refs/heads/main | <repo_name>Gabriela1DC/Rick-e-Morty-<file_sep>/README.md
# Rick-e-Morty
Apresentação de 50 personagens da série Rick e Morty consumindo a Api **The Rick And Morty API**
<div>
<img aling="center" src="https://github.com/Gabriela1DC/Rick-e-Morty-/blob/main/rick%20e%20morty.jpg">
</div>
<file_sep>/app.js
const geturl= id => 'https://rickandmortyapi.com/api/character/${id}'
const generateCharacterPromises = () => Array(150).fill().map((_,index)=>
fetch(geturl(index + 1)).then(response => response.json())
)
const generateHTML = characters => {characters.reduce((accumulator, {id, name, status, species, origin}) => {
const elementsOrigin=origin.map(originInfo=>originInfo.origin.name)
accumulator+='
<li class="card ${elementsOrigin[0]}">
<img class="card-img" alt='${name}' src='https://rickandmortyapi.com/api/character/avatar/${character.id}.jpg' />
<h2 class="card-title">${id}. ${name}</h2>
<p class='card-subtitle'>${status}</p>
<p class='card-subtitle'>${species}</p>
<p class="card-subtitle">${elementsOrigin.join(' | ')}</p>
</li>'
return accumulator
}, ' ')
const insertCharactersIntoPage = characters => {
const ul = document.querySelector('[data-js="rickAndmorty"]')
ul.innerHTML=characters
}
const characterPromises = generateCharacterPromises()
Promises.all(characterPromises)
.then(generateHTML)
.then(insertCharactersIntoPage) | 8c7c2d90681b42fce5d14663ad237c9218b3542c | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | Gabriela1DC/Rick-e-Morty- | 2b4b136238dfc24fc7ab7f2447256a085d935844 | 64ecbbd8d56bbf5e80bca315d884a8f2823655c4 |
refs/heads/master | <file_sep># main.utils.Radio-Kotlin<file_sep>//<NAME>
//Carnet 18540
//Fecha de creacion 08.07.2018
//Tarea de Radio con Kotlin
package main.utils
class Radio (//Clase de la Radio
var modulacion: String = "FM",
var volumen: Int = 0,
var estacion: Int = 87,
var isTurnedOn: Boolean = false
) {
fun turnOn() {//ENCIENDE LA RADIO
isTurnedOn = true
}
fun turnOff() {//APAGA LA RADIO
isTurnedOn = false
}
fun volumeUp() {//SUBE VOLUMEN
volumen += 1
}
fun volumeDown() {//BAJA VOLUMEN
volumen -= 1
}
override fun toString(): String {//IMPRIME EL ESTADO DE LA RADIO
return """
-------------------------------
Radio:
Modulacion: $modulacion
Esta encendido: $isTurnedOn
Volumen: $volumen
Estacion: $estacion
-------------------------------
""".trimIndent()
}
}
<file_sep>//<NAME>
//Carnet 18540
//Fecha de creacion 08.07.2018
//Tarea de Radio con Kotlin
package main
import main.utils.Radio
//Se importan las clases del archivo utils
fun main(args: Array<String>){
println("Bienvenido a la Radio")
val myRad = Radio()//Variable que contiene la clase, a la cual se referira en el futuro
do {//Ciclo principal del programa
if (myRad.isTurnedOn == false){//En caso de estar apagada la radio
println("Que desea hacer?:\n1.Encender\n2.Salir")
val eleccion = readLine()!!
if(eleccion == "1"){//Se enciende la radio
myRad.turnOn()
} else if (eleccion == "2"){
println("Saliendo de radio...")//Se sale del menu y corta el ciclo
break
}
} else if (myRad.isTurnedOn == true) {//si la radio esta encendida
println("")
println("""
Que desea hacer?
1.Apagar
2.Subir volumen
3.Bajar volumen
4.Cambiar de modulacion
5.Subir estacion
6.Bajar estacion
7.Ver estado de la radio
""".trimIndent())
val eleccion1 = readLine()!!
if (eleccion1 == "1") {//si decide apagar la radio
myRad.turnOff()
} else if (eleccion1 == "2") {//si decide subir volumen
if (myRad.volumen < 100){//verifica que el volumen sea menor que 100
println("Subiendo volumen...")
myRad.volumeUp()//sube volumen
} else {//en caso contrario se notifica lo siguiente
println("No se puede subir mas volumen...")
}
} else if (eleccion1 == "3") {//si decide bajar el volumen
if (myRad.volumen > 0){//verifica que el volumen sea mayor que 0
println("Bajando volumen...")
myRad.volumeDown()//baja el volumen
} else {//si no cumple, se muestra el siguiente mensaje
println("No se puede bajar mas el volumen...")
}
} else if (eleccion1 == "4") {//si decide cambiar de modulacion
println("Cambiando de modulacion...")
if (myRad.modulacion == "AM") {
myRad.modulacion = "FM"//cambia la modulacion
myRad.estacion = 87//se traslada a la estacion 87
} else if (myRad.modulacion == "FM") {
myRad.modulacion = "AM"//cambia a AM
myRad.estacion = 1000//se traslada a la estacion 1000
}
} else if (eleccion1 == "5") {//si decide subir estaciones
println("Cuantas estaciones desea subir?")
val step = readLine()!!.toInt()
if (myRad.modulacion == "AM") {
if ((myRad.estacion + step) <= 1400) {//verifica que este en el rango
println("Subiendo estacion...")
myRad.estacion += step//se suman las estaciones a la actual
} else if ((myRad.estacion + step) > 1400) {
println("No es posible subir a esa estacion...")
}
} else if (myRad.modulacion == "FM") {
if ((myRad.estacion + step) <= 147) {//verifica que este en el rango
println("Subiendo estacion...")
myRad.estacion += step//se suman las estaciones a la actual
} else if ((myRad.estacion + step) > 147) {
println("No es posible subir a esa estacion...")
}
}
} else if (eleccion1 == "6"){//si desea bajar de estacion
println("Cuantas estaciones desea bajar?")
val step = readLine()!!.toInt()
if (myRad.modulacion == "AM"){
if ((myRad.estacion - step) >= 1000){//verifica que este en el rango
println("Bajando de estacion...")
myRad.estacion -= step//resta las estaciones a la actual
} else if ((myRad.estacion - step) < 1000){
println("No es posible bajar a esa estacion...")
}
} else if (myRad.modulacion == "FM"){
if ((myRad.estacion - step) >= 87){//verifica que este en el rango
println("Bajando de estacion...")
myRad.estacion -= step//resta las estaciones a la actual
} else if ((myRad.estacion - step) < 87){
println("No es posible bajar a esa estacion...")
}
}
} else if (eleccion1 == "7"){//MOSTRAR EL ESTADO ACTUAL DE LA RADIO
println(myRad.toString())
}
}
} while (true)
} | 89e9af29379d2005ed45baf7a5862f83687c36f2 | [
"Markdown",
"Kotlin"
]
| 3 | Markdown | diegoestradaXO/Radio-Kotlin | a08daa1d4823c7af8a09d92a468640090ef48541 | dfa02843a1258ec8e340bd1ca10950d60e8f0f9a |
refs/heads/master | <repo_name>RivkaRevivo/ManagementGrades<file_sep>/Makefile
#!make -f
all: demo
./$<
demo: ManagementGradesDemo.o
clang++-5.0 -std=c++17 $^ -o demo
test: ManagementGradesTest.o
clang++-5.0 -std=c++17 $^ -o test
%.o: %.cpp Student.hpp ManagementGrades.hpp
clang++-5.0 -std=c++17 --compile $< -o $@
version:
clang++-5.0 --version
clean:
rm -f *.o demo test<file_sep>/Student.hpp
#pragma once
#include <iostream>
using namespace std;
namespace ariel{
class Student{
private:
int size;
public:
Student(){}
bool insert(int,int){
return true;}
int getgrade(int){
return 0;}
int getsize(){
return 0;}
double getav(){
return 0.0;}
};
}
<file_sep>/README.md
made by <NAME>, <NAME>, <NAME>
הוראות והסבר על המטלה נמצאים בקובץ README.PDF
המטרה במטלה זו היא תרגול בספריית התבנית STL
המטרה היא לתת לסטודנטים לבחור "מיכל מהספרייה התקנית שמתאים למטלה
להשתמש באיטרטור שלו, לשנות ולדרוס במקרה הצורך ולהשתמש באלגורתמים מהספרייה.
<file_sep>/ManagementGradesDemo.cpp
/**
* Demo file for the exercise on ManagementGrades
*
* @author
* @since
*/
#include <iostream>
#include <sstream>
#include <stdexcept>
using std::cout, std::endl, std::boolalpha, std::istringstream;
#include "ManagementGrades.hpp"
#include "Student.hpp"
using namespace ariel;
int main() {
try {
Student st1 , st2;
st1.insert(3,70);//In the third course, the score is 70
cout << st1.getgrade(3)<< endl;// prints 70
cout << st1.getsize() << endl;//prints 1
cout << st1.getav() << endl; //prints 70
st1.insert(4,80);//In the fourth course, the score is 80
cout << st1.getgrade(4)<< endl;// prints 80
cout << st1.getsize() << endl;//prints 2
cout << st1.getav() << endl; //prints 75
st1.insert(3,100);//In the third course, the score is 100
st1.insert(5,50);//In the fifth course, the score is 50
Student* pst1 = &st1;
Student* pst2 = &st2;
ManagementGrades cs;
cout << cs.size()<< endl;//prints 0
cout << cs.av(3)<< endl;//prints -1
cout << cs.allav()<< endl;//prints -1
cout << cs.range(20,78)<< endl;//prints 0
cs.add(12345678 ,pst1);// pointer to student st1 and his ID 12345678
cout << cs.size()<< endl;//prints 1
cout << cs.av(3)<< endl;//prints 70
cout << cs.allav()<< endl;//prints 75
cout << cs.range(20,78)<< endl;//prints 1
cs.student_s(12345678);//prints 75
cs.add(12345679, pst2);
cout << cs.size()<< endl;//prints 2
cout << cs.av(3)<< endl;//prints 85
cout << cs.allav()<< endl;//prints 75 (100+70+80+50)/4
cout << cs.range(20,78)<< endl;//prints 2
cs.student_s(12345679);//prints 75
}
catch (...) {
cout << "Unexpected exception!" << endl;
}
return 100;
}
<file_sep>/ManagementGradesTest.cpp
/**
* A test program for STL .
*
* @author .
* @since
*/
#include <iostream>
using namespace std;
#include "ManagementGrades.hpp"
#include "Student.hpp"
#include "badkan.hpp"
using namespace ariel;
int main() {
badkan::TestCase testcase;
int grade=0;
int signal = setjmp(badkan::longjmp_buffer);
if (signal == 0) {
testcase.setname("STUDENT");
Student st1 , st2;
st1.insert(3,70);
testcase.CHECK_EQUAL(st1.getgrade(3),70);
testcase.CHECK_EQUAL(st1.getsize(),1);
testcase.CHECK_EQUAL(st1.getav(),70);
testcase.CHECK_EQUAL(st1.getgrade(3),70);
st1.insert(4,80);
testcase.CHECK_EQUAL(st1.getgrade(4),80);
testcase.CHECK_EQUAL(st1.getsize(),2);
testcase.CHECK_EQUAL(st1.getav(),75);
testcase.CHECK_EQUAL(st1.getgrade(4),80);
st1.insert(3,100);//In the third course, the score is 100
st1.insert(5,50);//In the fifth course, the score is 50
Student* pst1 = &st1;
Student* pst2 = &st2;
testcase.setname("ManagementGrades");
ManagementGrades cs;
testcase.CHECK_EQUAL(cs.size(),0);
testcase.CHECK_EQUAL(cs.av(3),-1);
testcase.CHECK_EQUAL(cs.allav(),-1);
testcase.CHECK_EQUAL(cs.range(20,78),0);
cs.add(12345678 ,pst1);
testcase.CHECK_EQUAL(cs.size(),1);
testcase.CHECK_EQUAL(cs.av(3),70);
testcase.CHECK_EQUAL(cs.allav(),75);
testcase.CHECK_EQUAL(cs.range(20,78),1);
//CHECK_OUTPUT(cs.student_s(12345678), "75");
cs.add(12345679, pst2);
testcase.CHECK_EQUAL(cs.size(),2);
testcase.CHECK_EQUAL(cs.av(3),85);
testcase.CHECK_EQUAL(cs.allav(),75);
testcase.CHECK_EQUAL(cs.range(20,78),2);
//CHECK_OUTPUT(cs.student_s(12345679), "75")
testcase.print();
grade = testcase.grade();
} else {
testcase.print_signal(signal);
grade = 0;
}
cout << grade << " " << "sdlghljwhtycdxfhb" << endl;
return 0;
}
<file_sep>/ManagementGrades.hpp
#include <iostream>
#include <map>
#include "Student.hpp"
using namespace std;
namespace ariel{// MANAGEMENTGRADES_H_INCLUDED
class ManagementGrades{
private:
//map m<long, Student*>;
public:
ManagementGrades (){}
bool add(int,Student* S){return true;}
int size(){return 1;}
double av(int){return 1.0;}
double allav(){return 1.0;}
int range(int,int){return 1;}
void student_s(int){}
};
}
| 5e3d4686109f7cb4febc1cda1e535005b9519370 | [
"Markdown",
"Makefile",
"C++"
]
| 6 | Makefile | RivkaRevivo/ManagementGrades | 156ed193c0e11c2c908240335bc8ab49d17729a2 | b25e0a31444392674c9537631ae3d9188d8faf6a |
refs/heads/master | <repo_name>AhmedSamy97/StoreSystem<file_sep>/StoreSystem/Controllers/SubCategoryController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using StoreSystem.Core;
using StoreSystem.Models;
namespace StoreSystem.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SubCategoryController : ControllerBase
{
private readonly IUnitOfWork _unitOfWork;
public SubCategoryController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetSubCategories_ForCategory(int id)
{
return Ok(await _unitOfWork.SubCategories.GetSubCategory_ForCategory(id));
}
[HttpPost]
public async Task<IActionResult> AddSubCategories_ForCategory(SubCategory subCategory)
{
if (!await _unitOfWork.SubCategories.AddSubcategory(subCategory))
return BadRequest(new {Message = "Invalid name or Category ID"});
_unitOfWork.Complete();
return Ok(new {Message = "SubCategory Already Exists"});
}
}
}
<file_sep>/StoreSystem/Data/Seed.cs
using System;
using System.Collections.Generic;
using System.Linq;
using StoreSystem.Models;
namespace StoreSystem.Data
{
public class Seed
{
public static void SeedData(DataContext context)
{
if (!context.Categories.Any())
{
var categries = new List<Category>{
new Category{Name="Computers"},
new Category{Name="Furniture"},
new Category{Name="Pharmacy"},
};
context.Categories.AddRange(categries);
}
if (!context.SubCategories.Any())
{
var subCategories = new List<SubCategory>{
new SubCategory{CategoryId= 1,Name= "KeyBoard"},
new SubCategory{CategoryId= 1,Name= "Mouse"},
new SubCategory{CategoryId= 1,Name= "HeadPhone"}
};
context.SubCategories.AddRange(subCategories);
//run this have ForeignKey Relation
context.SaveChanges();
}
if (!context.Items.Any())
{
var items = new List<Item>{
new Item{SubCategoryId = 1 , Qty = 5,PricePerUnit = 3,MinQty=1},
new Item{SubCategoryId = 1 , Qty = 4,PricePerUnit = 1,MinQty=null},
};
context.Items.AddRange(items);
}
context.SaveChanges();
}
}
}<file_sep>/StoreSystem/Persistence/UnitOfWork.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StoreSystem.Core;
using StoreSystem.Data;
using StoreSystem.Persistence.Repositories;
namespace StoreSystem.Persistence
{
public class UnitOfWork:IUnitOfWork
{
private readonly DataContext _context;
public IcategoryRepository Categories { get; }
public ISubCategoryRepository SubCategories { get; }
public IItemRepository Items { get; }
public UnitOfWork(DataContext context)
{
_context = context;
Categories = new CategoryRepository(context);
SubCategories = new SubCategoryRepository(context);
Items = new ItemRepository(context);
}
public void Complete()
{
_context.SaveChanges();
}
}
}
<file_sep>/StoreSystem/Core/IUnitOfWork.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StoreSystem.Core
{
public interface IUnitOfWork
{
IcategoryRepository Categories { get; }
ISubCategoryRepository SubCategories { get; }
IItemRepository Items { get; }
void Complete();
}
}
<file_sep>/StoreSystem/Models/Category.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace StoreSystem.Models
{
[Table("Category")]
public class Category
{
public Category()
{
SubCategory = new HashSet<SubCategory>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<SubCategory> SubCategory { get; set; }
}
}
<file_sep>/StoreSystem/ClientApp/src/app/Services/item.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ItemService {
constructor(private http: HttpClient) { }
getItemDataPerSubCategory(id) {
return this.http.get("/api/item/" + id);
}
EditQuatity(subcategoryId, qtysArr) {
return this.http.put("/api/item", { subcategoryId, qtysArr });
}
}
<file_sep>/StoreSystem/Persistence/Repositories/SubCategoryRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using StoreSystem.Core;
using StoreSystem.Data;
using StoreSystem.Models;
namespace StoreSystem.Persistence.Repositories
{
public class SubCategoryRepository:ISubCategoryRepository
{
private readonly DataContext _context;
public SubCategoryRepository(DataContext context)
{
_context = context;
}
public async Task<IEnumerable<SubCategory>> GetSubCategory_ForCategory(int categoryId)
{
return await _context.SubCategories.Where(s => s.CategoryId == categoryId).ToListAsync();
}
public async Task<bool> AddSubcategory(SubCategory subCategory)
{
if (CheckValidSubcategory(subCategory))
{
await _context.AddAsync(subCategory);
return true;
}
return false;
}
private bool CheckValidSubcategory(SubCategory subCategory)
{
return _context.Categories.Any(s => s.Id == subCategory.CategoryId) &&
_context.SubCategories.Count(s =>
s.CategoryId == subCategory.CategoryId && s.Name == subCategory.Name) == 0;
}
}
}
<file_sep>/StoreSystem/Persistence/Repositories/CategoryRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using StoreSystem.Core;
using StoreSystem.Data;
using StoreSystem.Models;
namespace StoreSystem.Persistence.Repositories
{
public class CategoryRepository:IcategoryRepository
{
private readonly DataContext _context;
public CategoryRepository(DataContext context)
{
_context = context;
}
public async Task<IEnumerable<Category>> GetCategories()
{
return await _context.Categories.ToListAsync();
}
public async Task<bool> Add(Category category)
{
bool status = _context.Categories.Any(a => a.Name == category.Name);
await _context.Categories.AddAsync(category);
return status;
}
}
}
<file_sep>/StoreSystem/Dtos/ItemInformation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StoreSystem.Models;
namespace StoreSystem.Dtos
{
public class ItemInformation
{
public int[] Quantities { get; set; }
public int SubcategoryID { get; set; }
public string Name { get; set; }
public decimal[] Prices { get; set; }
public int Qtys { get; set; }
public int? MinQty { get; set; }
public ItemInformation(List<Item> items)
{
if (items.Count > 0)
{
Name = items[0].SubCategory.Name;
SubcategoryID = items[0].SubCategoryId;
Prices = GetPricesArray(items);
Quantities = GetQuantities(items);
}
//MinQty = items[0].MinQty.Value;
}
private decimal[] GetPricesArray(List<Item> items)
{
decimal[] prices = new Decimal[items.Count];
for (int i = 0; i < items.Count; i++)
{
prices[i] = items[i].PricePerUnit;
}
return prices;
}
private int[] GetQuantities(List<Item> items)
{
int[] qunatities = new int[items.Count];
for (int i = 0; i < items.Count; i++)
{
qunatities[i] = items[i].Qty;
}
return qunatities;
}
}
}
<file_sep>/StoreSystem/Dtos/EditItemDto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StoreSystem.Dtos
{
public class EditItemDto
{
public int subcategoryId { get; set; }
public int[] qtysArr { get; set; }
}
}
<file_sep>/StoreSystem/Controllers/ItemController.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StoreSystem.Core;
using StoreSystem.Data;
using StoreSystem.Dtos;
using StoreSystem.Models;
namespace StoreSystem.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ItemController : ControllerBase
{
private readonly IUnitOfWork _unitOfWork;
public ItemController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
[HttpGet("{subCategoryID}")]
public async Task<ItemInformation> GetAllItemsPerSubCategory(int subCategoryID)
{
return await _unitOfWork.Items.GetAllItemOfSpecificSubCategory(subCategoryID);
}
[HttpPost]
public async Task<IActionResult> AddItem(Item item)
{
if (!await _unitOfWork.Items.AddNewItem(item))
{
return BadRequest(
new { Message = "SubCategory And Price Per Unit Already Exist Try To Update Quantity" });
}
_unitOfWork.Complete();
return Ok(new { Message = "Subcategory Add SuccessFully" });
}
[HttpPut]
public IActionResult EditQuantity(EditItemDto dto)
{
_unitOfWork.Items.EditQuantityinItems(dto);
_unitOfWork.Complete();
return Ok();
}
}
}
<file_sep>/StoreSystem/Migrations/20201017203003_InitailCreate.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace StoreSystem.Migrations
{
public partial class InitailCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Category",
columns: table => new
{
ID = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Category", x => x.ID);
});
migrationBuilder.CreateTable(
name: "SubCategories",
columns: table => new
{
SubCategory_ID = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Category_ID = table.Column<int>(nullable: false),
Name = table.Column<string>(maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SubCategories", x => x.SubCategory_ID);
table.ForeignKey(
name: "FK_SubCategory_Category1",
column: x => x.Category_ID,
principalTable: "Category",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Items",
columns: table => new
{
SubCategoryID = table.Column<int>(nullable: false),
PricePerUnit = table.Column<double>(type: "money", nullable: false),
Qty = table.Column<int>(nullable: false),
MinQty = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Items", x => new { x.SubCategoryID, x.PricePerUnit });
table.ForeignKey(
name: "FK_Items_SubCategory",
column: x => x.SubCategoryID,
principalTable: "SubCategories",
principalColumn: "SubCategory_ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_SubCategories_Category_ID",
table: "SubCategories",
column: "Category_ID");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Items");
migrationBuilder.DropTable(
name: "SubCategories");
migrationBuilder.DropTable(
name: "Category");
}
}
}
<file_sep>/StoreSystem/Core/IItemRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StoreSystem.Dtos;
using StoreSystem.Models;
namespace StoreSystem.Core
{
public interface IItemRepository
{
Task<ItemInformation> GetAllItemOfSpecificSubCategory(int subcategoryId);
Task<bool> AddNewItem(Item item);
Task EditQuantityinItems(EditItemDto dto);
}
}
<file_sep>/StoreSystem/Controllers/CategoryController.cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StoreSystem.Core;
using StoreSystem.Data;
using StoreSystem.Models;
namespace StoreSystem.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CategoryController : ControllerBase
{
private readonly IUnitOfWork _unitOfWork;
public CategoryController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
[HttpGet]
public async Task<IActionResult> GetCategories()
{
return Ok(await _unitOfWork.Categories.GetCategories());
}
public async Task<IActionResult> AddCategory(Category category)
{
if (await _unitOfWork.Categories.Add(category))
return BadRequest(new {Message = "This Category Already Exist Please Choose Another Name !"});
//Save Category
_unitOfWork.Complete();
return Ok(new {Message="Category Add Successfully "});
}
}
}<file_sep>/StoreSystem/Models/Item.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace StoreSystem.Models
{
public class Item
{
// public Guid? ItemId { get; set; }
public int SubCategoryId { get; set; }
public int Qty { get; set; }
public decimal PricePerUnit { get; set; }
public int? MinQty { get; set; }
public virtual SubCategory SubCategory { get; set; }
}
}
<file_sep>/StoreSystem/Core/IcategoryRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StoreSystem.Models;
namespace StoreSystem.Core
{
public interface IcategoryRepository
{
Task<IEnumerable<Category>> GetCategories();
Task<bool> Add(Category category);
}
}
<file_sep>/StoreSystem/Models/SubCategory.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace StoreSystem.Models
{
public class SubCategory
{
public SubCategory()
{
Items = new HashSet<Item>();
}
public int SubCategoryId { get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
}
<file_sep>/StoreSystem/ClientApp/src/app/item/item.component.ts
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ItemService } from './../Services/item.service';
import { cloneDeep } from 'lodash';
import { NgbModal, ModalDismissReasons, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-item',
templateUrl: './item.component.html',
styleUrls: ['./item.component.css']
})
export class ItemComponent implements OnInit {
@ViewChild('warning', null) t1: ElementRef;
constructor(private router: ActivatedRoute, private itemService: ItemService, private r: Router, private modalService: NgbModal) { }
ItemData;
price: number = 0;
myArr;
id;
MinQty = 1;
closeResult = '';
modalReference: NgbModalRef;
ngOnInit() {
this.id = this.router.snapshot.paramMap.get('id');
this.itemService.getItemDataPerSubCategory(this.id).subscribe(d => {
this.ItemData = d;
const myClonedArray = cloneDeep(this.ItemData.quantities);
this.myArr = myClonedArray;
});
}
Add() {
if (this.ItemData != null && this.ItemData.qtys > 0) {
this.ItemData.qtys -= 1;
//Check minQty
if (this.ItemData.qtys <= this.MinQty) {
this.open(this.t1);
}
this.decrementQty();
}
}
decrementQty() {
let i = 0;
while (this.ItemData.qtys >= 0) {
if (this.ItemData.quantities[i] > 0) {
this.ItemData.quantities[i] -= 1;
break;
}
else {
i++;
}
}
}
CalculatePrice() {
if (this.ItemData != null) {
for (let index = 0; index < this.ItemData.quantities.length; index++) {
let qty = this.myArr[index] - this.ItemData.quantities[index];
this.price += qty * this.ItemData.prices[index];
}
}
}
placeOrder() {
this.itemService.EditQuatity(this.id, this.ItemData.quantities).subscribe(data => {
//Close PopUp
this.modalReference.close();
//Redirect
this.r.navigateByUrl("/");
});
}
open(content) {
this.modalReference = this.modalService.open(content);
this.modalReference.result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
//rest The Price
this.price = 0;
this.CalculatePrice();
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
}
<file_sep>/StoreSystem/Persistence/Repositories/ItemRepository.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using StoreSystem.Core;
using StoreSystem.Data;
using StoreSystem.Dtos;
using StoreSystem.Models;
namespace StoreSystem.Persistence.Repositories
{
public class ItemRepository : IItemRepository
{
private readonly DataContext _context;
public ItemRepository(DataContext context)
{
_context = context;
}
public async Task<ItemInformation> GetAllItemOfSpecificSubCategory(int subcategoryId)
{
var AllItems = await GetListSortedWithPrice(subcategoryId);
var Iteminfo = new ItemInformation(AllItems);
if (AllItems.Count() > 0)
Iteminfo.Qtys = Iteminfo.Quantities.Sum();
return Iteminfo;
}
private async Task<List<Item>> GetListSortedWithPrice(int subcategoryId)
{
return await _context.Items.Where(i => i.SubCategoryId == subcategoryId)
.Include(a => a.SubCategory).OrderBy(a => a.PricePerUnit).ToListAsync();
}
public async Task<bool> AddNewItem(Item item)
{
bool status = false;
if (CheckValidateItem(item))
{
status = true;
await _context.Items.AddAsync(item);
}
return status;
}
public async Task EditQuantityinItems(EditItemDto dto)
{
var SortedItem = await GetListSortedWithPrice(dto.subcategoryId);
for (int i = 0; i < SortedItem.Count; i++)
{
SortedItem[i].Qty = dto.qtysArr[i];
}
}
private bool CheckValidateItem(Item item)
{
return _context.Items.Count(i =>
i.SubCategoryId == item.SubCategoryId && i.PricePerUnit == item.PricePerUnit) == 0;
}
}
}
<file_sep>/StoreSystem/Data/DataContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using StoreSystem.Models;
namespace StoreSystem.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Item> Items { get; set; }
public virtual DbSet<SubCategory> SubCategories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>(entity =>
{
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
});
modelBuilder.Entity<Item>(entity =>
{
entity.HasKey(e => new { e.SubCategoryId, e.PricePerUnit });
entity.Property(e => e.SubCategoryId).HasColumnName("SubCategoryID");
entity.Property(e => e.PricePerUnit).HasColumnType("money");
entity.Property(e => e.PricePerUnit)
.HasConversion<double>();
entity.HasOne(d => d.SubCategory)
.WithMany(p => p.Items)
.HasForeignKey(d => d.SubCategoryId)
.HasConstraintName("FK_Items_SubCategory");
});
modelBuilder.Entity<SubCategory>(entity =>
{
entity.Property(e => e.SubCategoryId).HasColumnName("SubCategory_ID");
entity.Property(e => e.CategoryId).HasColumnName("Category_ID");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
entity.HasOne(d => d.Category)
.WithMany(p => p.SubCategory)
.HasForeignKey(d => d.CategoryId)
.HasConstraintName("FK_SubCategory_Category1");
});
}
}
}
<file_sep>/StoreSystem/ClientApp/src/app/sub-category/sub-category.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { SubcategoriesService } from './../Services/subcategories.service';
@Component({
selector: 'app-sub-category',
templateUrl: './sub-category.component.html',
styleUrls: ['./sub-category.component.css']
})
export class SubCategoryComponent implements OnInit {
constructor(private subcategoryService: SubcategoriesService, private router: ActivatedRoute) { }
subCategories;
ngOnInit() {
const id = this.router.snapshot.paramMap.get('id');
this.subcategoryService.getAllSubCategories(id).subscribe(sub => this.subCategories = sub);
}
}
<file_sep>/StoreSystem/Core/ISubCategoryRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StoreSystem.Models;
namespace StoreSystem.Core
{
public interface ISubCategoryRepository
{
Task<IEnumerable<SubCategory>> GetSubCategory_ForCategory(int categoryId);
Task<bool> AddSubcategory(SubCategory subCategory);
}
}
| d5a8bc7636846992f94ea2e6cc4ff17af56eb5df | [
"C#",
"TypeScript"
]
| 22 | C# | AhmedSamy97/StoreSystem | 30063b5f498b7dcbd02811adca0c27d5bf72b214 | 953761bf9dc75c8c56037a77bd12b1c1eac38287 |
refs/heads/master | <repo_name>alsonshareef/sales-crud<file_sep>/README.md
# sales-crud
<file_sep>/routes/index.js
let express = require('express');
let router = express.Router();
let userControllers = require('../controllers/user');
let landingControllers = require('../controllers/landing');
/* AUTHENTICATION */
router.get('/login', userControllers.show_login);
router.get('/signup', userControllers.show_signup);
router.post('/login', userControllers.login);
router.post('/signup', userControllers.signup);
router.post('/logout', userControllers.logout);
router.get('/logout', userControllers.logout);
/* GET home landing page. */
router.get('/', landingControllers.get_landing);
/* (CREATE) POST submit lead */
router.post('/', landingControllers.post_lead);
/* (READ) GET list of leads and individual leads */
router.get('/leads', landingControllers.get_leads);
router.get('/lead/:lead_id', landingControllers.get_individualLead);
/* (UPDATE) GET and POST for update lead page */
router.get('/lead/:lead_id/edit', landingControllers.get_updateLead);
router.post('/lead/:lead_id/edit', landingControllers.update_lead);
/* (DELETE) POST for delete lead */
router.post('/lead/:lead_id/delete', landingControllers.delete_lead);
module.exports = router;
<file_sep>/controllers/landing.js
const models = require('../models');
/* GET callbacks */
exports.get_landing = (req, res, next) => {
// username is stored in /req.user.dataValues.email/ when user is logged in
res.render('landing', { title: 'Express' });
};
/* CREATE callbacks */
exports.post_lead = (req, res, next) => {
return models.Lead.create({
email: req.body.lead_email
}).then(lead => {
res.redirect('/leads');
});
};
/* READ callbacks */
exports.get_leads = (req, res, next) => {
return models.Lead.findAll().then(leads => {
res.render('lead/leads', { title: 'Leads', leads: leads });
});
};
exports.get_individualLead = (req, res, next) => {
return models.Lead.findOne({
where: {
id: req.params.lead_id
}
}).then(lead => {
res.render('lead/individual_lead', { lead: lead });
});
};
/* UPDATE callbacks */
exports.get_updateLead = (req, res, next) => {
return models.Lead.findOne({
where: {
id: req.params.lead_id
}
}).then(lead => {
res.render('lead/update_lead', { title: 'Update lead', lead: lead });
});
};
exports.update_lead = (req, res, next) => {
return models.Lead.update(
{
email: req.body.lead_email
},
{
where: {
id: req.params.lead_id
}
}
).then(result => {
res.redirect(`/lead/${req.params.lead_id}`);
});
};
/* DELETE callbacks */
exports.delete_lead = (req, res, next) => {
return models.Lead.destroy({
where: {
id: req.params.lead_id
}
}).then(result => {
res.redirect('/leads');
});
};
| 64866c6c1f8e720e526f54b340d1fa5c67485ba7 | [
"Markdown",
"JavaScript"
]
| 3 | Markdown | alsonshareef/sales-crud | 851e42542ca8a97a2bc114cdd5172d27685bebdb | 91df83d21e7acb18a5e436279f959ca7074711fb |
refs/heads/master | <file_sep>const express=require("express");
const bodyparser=require("body-parser");
const app=express();
const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/bookDB', {useNewUrlParser: true});
app.use(bodyparser.urlencoded({extended:true}));
app.listen(3000,function(){
console.log("Server started at port 3000");
});
app.set('view engine', 'ejs');
const booksschema={
name:String,
about:String
};
const Book = mongoose.model("Book",booksschema);
const book1 = new Book({
name:"Welcome"
});
const book2 = new Book({
name:"Add"
});
const book3 = new Book({
name:"Delete"
});
const bookItems=[book1,book2,book3];
app.get("/",function(req,res){
Book.find({},function(err,foundItems){
res.render("home",{
books:foundItems,
});
});
});
app.get("/add",function(req,res){
res.render("add");
});
app.post("/add",function(req,res){
const bookName = req.body.title;
const bookAbout =req.body.about
const book=new Book({
name:bookName,
about:bookAbout
});
book.save();
res.redirect("/");
});
app.get("/delete",function(req,res){
res.render("delete");
});
app.post("/delete",function(req,res){
var deletebook=req.body.title;
console.log(deletebook);
Book.deleteOne({name:deletebook},function(err)
{
console.log("Entered");
if(err)
{
console.log(err);
}
else
{
console.log("Deleted Successfully");
}
});
res.redirect("/");
});
app.get("/book/:topic",function(req,res){
var title=req.params.topic;
Book.find({},function(err,foundItems){
foundItems.forEach(function(item){
if(item.name===title)
{
res.render("book",{
title:item.name,
about:item.about
});
}
});
});
});
<file_sep># webapp-bookstore-with-mangodb
initialise the mangodb in your system
the install the required nodejs packages
then run app.js
#link For Deplyed App using Heroku
https://morning-brushlands-35230.herokuapp.com
| a54ea5070aa023cef106c3129dbc1c8b6f94a7a8 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | jaxiodute/webapp-bookstore-with-mangodb | bf62a7f95bf0da2b9ae225687221b0fa9ebf7982 | b09cbeb56965b19eec34cb020753e13bd3794489 |
refs/heads/master | <repo_name>Harry-Kwon/katas<file_sep>/Anagram/index.js
const readline = require('readline');
const {parse} = require('./fileParser');
const {SortedTrie} = require('./word');
const {findAnagrams, findTwoWordAnagrams} = require('./anagram');
const wordlistFile = '/home/chromatk/workspace/kata_new/Anagram/words_alpha.txt';
async function createTrieFromWordlist(fileName) {
let trie = new SortedTrie();
let handleReadWord = (w) => {
if(w !== '') trie.push(w);
}
await parse(fileName, handleReadWord);
return trie;
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
function ask(trie) {
rl.question('enter a word to find an anagram\r\n', (answer) => {
let anagrams = findAnagrams(answer, trie);
console.log(`Anagrams of ${answer}: ${anagrams}`);
let twoWordAnagrams = findTwoWordAnagrams(answer, trie);
console.log(`Two word anagrams of ${answer}`);
twoWordAnagrams.forEach(c => console.log(c));
if(answer !== '-quit') {
ask(trie);
} else {
rl.close();
}
});
}
async function main() {
console.log('parsing file...');
console.time('parsed file');
let trie = await createTrieFromWordlist(wordlistFile);
console.timeEnd('parsed file');
ask(trie);
//console.log(findTwoWordAnagrams('foo', trie));
}
main();<file_sep>/Anagram/anagram.js
const {word} = require('./word.js');
function findAnagrams(target, trie) {
return trie.search(target);
}
function findTwoWordAnagrams(target, trie) {
let anagrams = {};
const targetWord = word(target);
// DFS through trie to find candidates
function searchNode(node, choices) {
this.words = node.words;
this.children = node.children;
this.choices = choices;
}
let head = new searchNode(trie.head, target.split(''));
let frontier = [head];
while(frontier.length>0) {
let current = frontier.pop();
// for each word in the node, check if an anagram of the residual exists
current.words.forEach((candidateWord) => {
let candidate = candidateWord.string;
let residual = targetWord.residual(candidateWord); // the residual of candidate an anagram of the complement
let complements = findAnagrams(residual, trie); // get anagrams of the complement
complements.forEach((complement) => {
// check for duplicates
if(!(anagrams[complement] && anagrams[complement].includes(candidate))) {
if(!anagrams[candidate]) anagrams[candidate] = [];
anagrams[candidate].push(complement);
}
})
})
// add children to stack
let choices = current.choices;
choices.forEach((c, i) => {
if((i==0 || c!=choices[i-1]) && current.children[c]) {
let nextChoices = choices.slice(0, i).concat(choices.slice(i+1));
let nextNode = new searchNode(current.children[c], nextChoices);
frontier.push(nextNode);
}
})
}
// convert anagrams to array of pairs
let pairs = [];
Object.keys(anagrams).forEach((word) => {
anagrams[word].forEach((complement) => {
pairs.push([word, complement]);
})
})
return pairs;
}
module.exports = {findAnagrams, findTwoWordAnagrams} | 20a2ec07b2218d40254ef67fad8d31d7a3ca1a2d | [
"JavaScript"
]
| 2 | JavaScript | Harry-Kwon/katas | 82f2d63d06bd7105d1bf857c428860a9e90ba09c | a55a1e0add2077def9e40c3bc571b5407ee91dfe |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
class CategoryController extends Controller {
public function getCategoryIndex() {
$categories = Category::orderBy('created_at', 'desc')->paginate(5);
return view('admin.blog.categories', ['categories' => $categories]);
}
public function postCreateCategory(Request $request) {
$this->validate($request, [
'name' => 'required'
]);
$category = new Category();
$category->name = $request['name'];
if ($category->save()) {
return redirect()->route('admin.blog.categories')->with(['success' => 'Category added']);
}
return redirect()->route('admin.blog.categories')->with(['fail' => 'Error!']);
}
} | 53493d24f64820bea13144ce6c168111e1901311 | [
"PHP"
]
| 1 | PHP | bulian1311/blog.laravel | 7e5f00daabee2c58d5ac8262164842fd0e598bfc | 864b0b2f67cb671071954b44daaa434e8d265903 |
refs/heads/master | <file_sep>package main.java.com.data.connector.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping ("/v1/data")
public class DataController {
@RequestMapping (value = "/test", method = RequestMethod.GET)
public Map<String, Object> sayHello() {
final Map<String, Object> value = new HashMap<>();
final Map<String, Object> customer = new HashMap<>();
customer.putIfAbsent("Status", "SUCCESS");
customer.putIfAbsent("FirstName", "Bruce");
customer.putIfAbsent("LastName", "Wayne");
customer.putIfAbsent("Email", "<EMAIL>");
customer.putIfAbsent("Phone", "703.555.1212");
final List<Map<String, Object>> customerList = new ArrayList<>();
customerList.add(customer);
customerList.add(customer);
value.putIfAbsent("customers", customerList);
return value;
}
} | 026c3663e40e3ad1bc84a684c8b9f4922d7156cb | [
"Java"
]
| 1 | Java | akrgos/data-connector | 14e914d0523a1d084e7943abd667a1303511eba8 | 4f4d262279f668b9eeca4c03a41a093972888b79 |
refs/heads/master | <repo_name>wang1375830242/CDN<file_sep>/nav/js/send.js
layui.use(['layer','element','form'],function(){
var form = layui.form;
var layer = layui.layer;
var element = layui.element;
/**
* 通用表单提交(AJAX方式)
*/
form.on('submit(*)', function (data) {
var loading = layer.load(0, {shade: false});
$.ajax({
url: data.form.action,
type: data.form.method,
data: $(data.form).serialize(),
success: function (info) {
layer.close(loading);
if (info.code === 1) {
setTimeout(function () {
location.href = info.url;
}, 1000);
showSuccess(info.msg);
} else {
showError(info.msg);
}
},
complete:function(){
if(data.field.verify){
$("#verify").click();
}
}
});
return false;
});
//成功提示
function showSuccess(msg){
layer.msg(msg,{
icon:1,
shade:0.3,
anim:1
});
}
//错误提示
function showError(msg){
layer.msg(msg,{
icon:2,
shade:0.3,
anim:1
});
}
});
function tc_Open() {
$("#File").click();
};
$(document).ready(function() {
$("input[type='file']").change(function(e) {
file_upload(this.files)
});
var obj = $('body');
obj.on('dragenter', function(e) {
e.stopPropagation();
e.preventDefault()
});
obj.on('dragover', function(e) {
e.stopPropagation();
e.preventDefault()
});
obj.on('drop', function(e) {
e.preventDefault();
file_upload(e.originalEvent.dataTransfer.files)
});
});
function file_upload(files){
if (files.length == 0) return msg('2','请选择图片文件!');
for(var j = 0,len = files.length; j < len; j++){
let imageData = new FormData();
imageData.append("file", 'multipart');
imageData.append("Filedata", files[j]);
$.ajax({
url: "https://api.uomg.com/api/image.ali",
type: 'POST',
data: imageData,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function (result) {
if (result.code == 1){
$('input[name=thumb]').val(result.imgurl);
mgs('1','上传成功');
}else{
msg('2','第'+j+'个图片上传失败');
}
},
error: function () {
msg('2','图片上传失败');
}
});
}
}
function isNull(str) {
if(str==undefined||str==null||str==""){
return false;
}
return true;
}
function mgs(type,msg) {
if(isNull(type) && isNull(msg)){
return layer.msg(msg,{icon:type});
}else{
return layer.msg("参数错误!",{icon:2});
}
}
<file_sep>/nav/js/ihucms.js
function scroll_news() {
$(function() {
$('#dvmq ul').eq(0).fadeOut('slow', function() {
$(this).clone().appendTo($(this).parent()).fadeIn('slow');
$(this).remove();
});
});
}
setInterval('scroll_news()', 5000);
<file_sep>/nav/js/public.js
/*导航栏目切换样式*/
$(".border-bottom").css({
"transition": "0s all"
});
var navnow = $("header nav .hover").index();
if (navnow >= 0) {
$(".border-bottom").css({
"display": "block",
"left": $("header nav div").eq(navnow).position().left + parseInt($("header nav div").eq(navnow).css("padding-left")),
"width": $("header nav div").eq(navnow).width()
});
} else {
$(".border-bottom").hide();
}
$(".border-bottom").css({
"transition": "0.2s all"
});
$("header nav div").hover(function (e) {
$(".border-bottom").show();
$("header nav .hover").removeClass("hover");
$(this).addClass("hover");
$(".border-bottom").css({
"left": $(this).position().left + parseInt($("header nav div").eq(navnow).css("padding-left")),
"width": $(this).width()
});
}, function (e) {
$("header nav .hover").removeClass("hover");
if (navnow >= 0) {
$("header nav div").eq(navnow).addClass("hover");
$(".border-bottom").css({
"left": $("header nav div").eq(navnow).position().left + parseInt($("header nav div").eq(navnow).css("padding-left")),
"width": $("header nav div").eq(navnow).width()
});
return;
}
$(".border-bottom").hide();
});
/*数值转换*/
function castNum(num) {
if (num < 100) {
return num;
} else if (num >= 1000 && num < 10000) {
var newNum = (num / 1000).toFixed(1) + "K";
return newNum;
} else if (num >= 10000 && num < 100000000) {
var newNum = (num / 100000000).toFixed(2) + "W";
return newNum;
} else if (num >= 100000000 && num < 10000000000000000) {
var newNum = (num / 100000000).toFixed(2) + "E";
return newNum;
} else {
var newNum = "亿亿以上+";
return newNum;
}
}
/*返回顶部*/
if ($(".backtop").length > 0) {
if ($(document).scrollTop() > 200) {
$(".backtop").show();
} else {
$(".backtop").hide();
}
$(document).scroll(function (e) {
if ($(this).scrollTop() > 200) {
$(".backtop").show();
} else {
$(".backtop").hide();
}
});
$(".backtop").click(function () {
$('html,body').animate({
scrollTop: 0
}, 'slow');
});
} /*是否今天*/
function isToday(date) {
date = /\s*/.test(date) ? date.split(" ")[0] : date;
var now = new Date();
var seperator1 = "-";
var month = now.getMonth() + 1;
var strDate = now.getDate();
var year = now.getFullYear();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = year + seperator1 + month + seperator1 + strDate;
return currentdate === date;
} /*加载当前时间*/
$(".time").html(getTimeHtml());
setInterval(function () {
$(".time").html(getTimeHtml());
}, 1000); /*获取当前时间段*/
function getTimeHtml() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hh = now.getHours();
var mm = now.getMinutes();
var ss = now.getSeconds();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
if (hh < 10) hh = "0" + hh;
if (mm < 10) mm = "0" + mm;
if (ss < 10) ss = "0" + ss;
return "<span>" + month + "</span> <small>月</small> <span>" + day + "</span> <small>" + hh + ":" + mm + ":" + ss + " 周" + "日一二三四五六".charAt(new Date().getDay()) + "</small>";
}
function request(option) {
if (typeof (option) !== 'object') {
console.warn("option is not a 'object'");
return false;
}
if (typeof (layer) === 'undefined') {
layui.use('layer', ajx(true));
} else {
ajx();
}
if (typeof (option.loading) !== 'boolean') {}
function ajx(o) {
if (o) {
layer = layui.layer;
}
$.ajax({
url: option.url || location.pathname,
data: option.data || null,
dataType: option.dataType || 'JSON',
type: option.type || 'post',
async: typeof (option.async) === 'boolean' ? option.async : true,
success: option.success || function (res) {
if (res.data) {
var delay = res.data.delay || 0;
delay && (delay *= 1000);
res.data.redirect && (setTimeout(function () {
location = res.data.redirect;
}, delay));
res.data.reload && (option.reload = parseFloat(res.data.reload));
if (res.data.alert) {
res.msg && layer.open({
type: 0,
shadeClose: true,
shade: ["0.6", "#7186a5"],
skin: 'atuikeLayerSkin1',
content: res.msg
});
}
}
if (!res.data || !res.data.alert) {
var cfg = typeof (res.data.icon) !== "boolean" ? {
icon: (res.code || 0),
offset: '20%'
} : {};
res.msg && layer.msg(res.msg, cfg);
}
option.done && option.done(res);
},
complete: function () {
if (typeof (option.loading) !== 'boolean') {}
setTimeout(function () {
var ret = option.reload || false;
if (ret) {
ret = (typeof (ret === 'number')) ? ret : 0;
setTimeout(function () {
location.reload();
}, ret * 1000);
}
}, 10);
},
error: option.error || function (e) {
layer.msg('网络异常:' + e.statusText || e.statusMessage);
}
});
}
}
$.fn.field = function () {
var arr_data = $(this).serializeArray();
var formData = {};
if (arr_data.length > 0) {
arr_data.forEach(function (item) {
formData[item.name] = item.value;
});
}
return formData;
};
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null
} else {
begin += 2
}
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length
}
return unescape(dc.substring(begin + prefix.length, end))
}
function setCookie(name, value, time) {
var strsec = getsec(time);
var exp = new Date();
exp.setTime(exp.getTime() + strsec * 1);
document.cookie = name + "=" + escape(value) + "; path=/;expires=" + exp.toGMTString();
}
function getsec(str) {
var str1 = str.substring(1, str.length) * 1;
var str2 = str.substring(0, 1);
if (str2 == "s") {
return str1 * 1000;
} else if (str2 == "h") {
return str1 * 60 * 60 * 1000;
} else if (str2 == "d") {
return str1 * 24 * 60 * 60 * 1000;
}
}
Array.prototype.ArrDelVal = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) {
this.splice(i, 1);
break;
}
}
};<file_sep>/nav/js/as_html.js
var layer;
layui.use('layer', function(){
layer = layui.layer;
});
/* 联系QQ弹出框 */
function lxzz(qq) {
if (qq) {
if (qq === "---") {
layer.open({
type: 0,
shadeClose: true,
skin: 'atuikeLayerSkin1',
content: '该作者由于违反本站管理规范,已被管理员封禁账号。无法联系',
btn: ['我知道了']
});
return;
}
layer.open({
type: 0,
shadeClose: true,
skin: 'atuikeLayerSkin1',
content: '请不要骚扰管理员<font color="red"> 商务合作 </font> 欢迎点击联系!',
btn: ['继续联系', '取消'],
yes: function () {
window.open("http://wpa.qq.com/msgrd?v=3&uin=" + qq + "&site=qq&menu=yes", "_blank");
layer.closeAll();
}
});
} else {
layer.open({
type: 0,
shadeClose: true,
skin: 'atuikeLayerSkin1',
content: '该管理员没有填写QQ联系方式,无法联系~',
btn: ['我知道了']
});
}
}<file_sep>/nav/js/detail.js
$("a").click(function () {
var link = $(this).attr('href');
if (!link) {
return false;
};
$.ajax({
type: "POST",
url: '/add-views-'+ web_id +'.html',
dataType: "json",
data: {
},
success: function (res) {
console.log(link);
}
});
});
request({
url: '/get-statistics-'+ web_id +'-1.html',
success: function (res) {
var data_json = [];
res.date_a.forEach(function (v, i) {
var json = {};
json.value = v;
if (i === 0) {
json.textStyle = {
align: "left"
};
} else if (i === 6) {
json.textStyle = {
align: "right"
};
} else {
json.textStyle = {
align: "center"
};
}
data_json.push(json);
}); /*渲染图表*/
var myChart = echarts.init(document.getElementById('sentiment'));
var option = {
color: ['#80e0d1'],
tooltip: {
trigger: 'axis',
enterable: !1,
extraCssText: "border-radius:0;padding:0;border:1px solid #20c4ab;background-color:rgba(255,255,255,.95);",
formatter: function (e, t, n) {
var i = e[0];
return '<dl class="x-c-t-tooltip"><dt>日期:' + i.axisValue + "</dt><dd><div><strong>点击数量<span>:" + i.data + "</span></strong></div>" + [].join("") + "</dd></dl>";
}
},
grid: {
left: '0',
top: '25px',
right: '0',
bottom: '0',
containLabel: true
},
xAxis: [{
type: 'category',
splitLine: {
show: false
},
axisLine: {
show: !1
},
axisTick: {
show: !1
},
axisLabel: {
show: true,
margin: 20,
textStyle: {
color: '#ababab',
'fontSize': 14,
}
},
boundaryGap: false,
data: data_json,
}],
yAxis: [{
type: 'value',
axisLine: {
lineStyle: {
color: ["#F8F8F8"]
}
},
axisLabel: {
show: !1,
inside: true
},
splitLine: {
lineStyle: {
color: ["#F8F8F8"]
}
}
}],
series: [{
name: '总共访问',
type: 'line',
stack: '总量',
itemStyle: {
normal: {
lineStyle: {
width: 2
}
}
},
areaStyle: {
normal: {
opacity: 1,
color: {
x: 0,
y: 0,
x2: 0,
y2: 1,
type: "linear",
global: !1,
colorStops: [{
offset: 0,
color: "#80e0d1"
}, {
offset: 1,
color: "#FFFFFF"
}]
}
}
},
data: res.date_b
}]
};
myChart.setOption(option);
}
});<file_sep>/README.md
# CDN
https://www.sakura521.cn CDN的搭建
| fd81888ccc082ab15bbef2e95a1fd2a8528eec05 | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | wang1375830242/CDN | 181b6b4b145107c9b78ae92d4b884295c7eb2a87 | c5eefa18452253c2b8111bf8ec7f8fcfd665339a |
refs/heads/master | <repo_name>RobinVanRoy/Songs<file_sep>/Songs.DataModel/Migrations/201710201356315_AddRepository.cs
namespace Songs.DataLayer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddRepository : DbMigration
{
public override void Up()
{
DropStoredProcedure("dbo.Album_Insert");
DropStoredProcedure("dbo.Album_Update");
DropStoredProcedure("dbo.Album_Delete");
}
public override void Down()
{
throw new NotSupportedException("Scaffolding create or alter procedure operations is not supported in down methods.");
}
}
}
<file_sep>/Songs.DataModel/Migrations/201710112050527_Annotations.cs
namespace Songs.DataLayer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Annotations : DbMigration
{
public override void Up()
{
RenameTable(name: "dbo.SongPerformers", newName: "PerformerSongs");
RenameColumn(table: "dbo.SongAlbums", name: "SongId", newName: "Song_SongId");
RenameColumn(table: "dbo.SongAlbums", name: "AlbumId", newName: "Album_AlbumId");
RenameColumn(table: "dbo.PerformerSongs", name: "SongId", newName: "Song_SongId");
RenameColumn(table: "dbo.PerformerSongs", name: "PerformerId", newName: "Performer_PerformerId");
RenameIndex(table: "dbo.SongAlbums", name: "IX_SongId", newName: "IX_Song_SongId");
RenameIndex(table: "dbo.SongAlbums", name: "IX_AlbumId", newName: "IX_Album_AlbumId");
RenameIndex(table: "dbo.PerformerSongs", name: "IX_PerformerId", newName: "IX_Performer_PerformerId");
RenameIndex(table: "dbo.PerformerSongs", name: "IX_SongId", newName: "IX_Song_SongId");
DropPrimaryKey("dbo.PerformerSongs");
AlterColumn("dbo.Albums", "ReleaseDate", c => c.DateTime(nullable: false));
AlterColumn("dbo.Songs", "Duration", c => c.Time(nullable: false, precision: 7));
AlterColumn("dbo.Songs", "ReleaseDate", c => c.DateTime(nullable: false));
AlterColumn("dbo.Performers", "Birthday", c => c.DateTime(nullable: false));
AddPrimaryKey("dbo.PerformerSongs", new[] { "Performer_PerformerId", "Song_SongId" });
}
public override void Down()
{
DropPrimaryKey("dbo.PerformerSongs");
AlterColumn("dbo.Performers", "Birthday", c => c.DateTime());
AlterColumn("dbo.Songs", "ReleaseDate", c => c.DateTime());
AlterColumn("dbo.Songs", "Duration", c => c.Time(precision: 7));
AlterColumn("dbo.Albums", "ReleaseDate", c => c.DateTime());
AddPrimaryKey("dbo.PerformerSongs", new[] { "SongId", "PerformerId" });
RenameIndex(table: "dbo.PerformerSongs", name: "IX_Song_SongId", newName: "IX_SongId");
RenameIndex(table: "dbo.PerformerSongs", name: "IX_Performer_PerformerId", newName: "IX_PerformerId");
RenameIndex(table: "dbo.SongAlbums", name: "IX_Album_AlbumId", newName: "IX_AlbumId");
RenameIndex(table: "dbo.SongAlbums", name: "IX_Song_SongId", newName: "IX_SongId");
RenameColumn(table: "dbo.PerformerSongs", name: "Performer_PerformerId", newName: "PerformerId");
RenameColumn(table: "dbo.PerformerSongs", name: "Song_SongId", newName: "SongId");
RenameColumn(table: "dbo.SongAlbums", name: "Album_AlbumId", newName: "AlbumId");
RenameColumn(table: "dbo.SongAlbums", name: "Song_SongId", newName: "SongId");
RenameTable(name: "dbo.PerformerSongs", newName: "SongPerformers");
}
}
}
<file_sep>/Songs.UI/Controllers/AlbumsController.cs
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Songs.Classes;
using Songs.DataLayer.Repositories;
namespace Songs.UI.Controllers
{
public class AlbumsController : Controller
{
private readonly AlbumRepository _repoAlbum = new AlbumRepository();
private readonly GenreRepository _repoGenre = new GenreRepository();
// GET: Albums
public ActionResult Index() => View(_repoAlbum.All.ToList());
// GET: Albums/Details/5
public ActionResult Details(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
Album album = _repoAlbum.Find(id);
if (album == null) return HttpNotFound();
return View(album);
}
// GET: Albums/Create
public ActionResult Create()
{
ViewBag.GenreId = new SelectList(_repoGenre.All, "GenreId", "Name");
return View();
}
// POST: Albums/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "AlbumId,Title,ReleaseDate,GenreId")] Album album)
{
if (ModelState.IsValid)
{
_repoAlbum.InsertOrUpdate(album);
_repoAlbum.Save();
return RedirectToAction("Index");
}
ViewBag.GenreId = new SelectList(_repoGenre.All, "GenreId", "Name", album.GenreId);
return View(album);
}
// GET: Albums/Edit/5
public ActionResult Edit(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
Album album = _repoAlbum.Find(id);
if (album == null) return HttpNotFound();
ViewBag.GenreId = new SelectList(_repoGenre.All, "GenreId", "Name", album.GenreId);
return View(album);
}
// POST: Albums/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "AlbumId,Title,ReleaseDate,GenreId")] Album album)
{
if (ModelState.IsValid)
{
_repoAlbum.InsertOrUpdate(album);
_repoAlbum.Save();
return RedirectToAction("Index");
}
ViewBag.GenreId = new SelectList(_repoGenre.All, "GenreId", "Name", album.GenreId);
return View(album);
}
// GET: Albums/Delete/5
public ActionResult Delete(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
Album album = _repoAlbum.Find(id);
if (album == null) return HttpNotFound();
return View(album);
}
// POST: Albums/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
_repoAlbum.Delete(id);
_repoAlbum.Save();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_repoAlbum.Dispose();
_repoGenre.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>/Songs.UI/Controllers/HomeController.cs
using System.Web.Mvc;
using Songs.DataLayer.Repositories;
using Songs.UI.Viewmodels;
namespace Songs.UI.Controllers
{
public class HomeController : Controller
{
private readonly SongRepository _repo = new SongRepository();
public ActionResult Index()
{
AllViewmodel model = new AllViewmodel
{
Songs = _repo.AllSongs,
Albums = _repo.AllAlbums,
Performers = _repo.AllPerformers,
Genres = _repo.AllGenres
};
return View(model);
}
}
}<file_sep>/Songs.DataModel/Interfaces/IGenreRepository.cs
using System;
using System.Linq;
using Songs.Classes;
namespace Songs.DataLayer.Interfaces
{
public interface IGenreRepository: IDisposable
{
IQueryable<Genre> All { get; }
Genre Find(int id);
void InsertOrUpdate(Genre genre);
void Delete(int genreId);
void Save();
}
}
<file_sep>/Songs.DataModel/Migrations/201710111857271_Initial.cs
namespace Songs.DataLayer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Albums",
c => new
{
AlbumId = c.Int(nullable: false, identity: true),
Title = c.String(nullable: false, maxLength: 50),
ReleaseDate = c.DateTime(),
GenreId = c.Int(),
})
.PrimaryKey(t => t.AlbumId)
.ForeignKey("dbo.Genres", t => t.GenreId)
.Index(t => t.GenreId);
CreateTable(
"dbo.Genres",
c => new
{
GenreId = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 50),
})
.PrimaryKey(t => t.GenreId);
CreateTable(
"dbo.Songs",
c => new
{
SongId = c.Int(nullable: false, identity: true),
Title = c.String(nullable: false, maxLength: 50),
Duration = c.Time(precision: 7),
ReleaseDate = c.DateTime(),
GenreId = c.Int(),
})
.PrimaryKey(t => t.SongId)
.ForeignKey("dbo.Genres", t => t.GenreId)
.Index(t => t.GenreId);
CreateTable(
"dbo.Performers",
c => new
{
PerformerId = c.Int(nullable: false, identity: true),
FirstName = c.String(nullable: false, maxLength: 50),
LastName = c.String(nullable: false, maxLength: 50),
NickName = c.String(maxLength: 50),
Birthday = c.DateTime(),
BirthPlace = c.String(maxLength: 50),
Country = c.String(maxLength: 50),
})
.PrimaryKey(t => t.PerformerId);
CreateTable(
"dbo.SongAlbums",
c => new
{
SongId = c.Int(nullable: false),
AlbumId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.SongId, t.AlbumId })
.ForeignKey("dbo.Songs", t => t.SongId, cascadeDelete: true)
.ForeignKey("dbo.Albums", t => t.AlbumId, cascadeDelete: true)
.Index(t => t.SongId)
.Index(t => t.AlbumId);
CreateTable(
"dbo.SongPerformers",
c => new
{
SongId = c.Int(nullable: false),
PerformerId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.SongId, t.PerformerId })
.ForeignKey("dbo.Songs", t => t.SongId, cascadeDelete: true)
.ForeignKey("dbo.Performers", t => t.PerformerId, cascadeDelete: true)
.Index(t => t.SongId)
.Index(t => t.PerformerId);
}
public override void Down()
{
DropForeignKey("dbo.Albums", "GenreId", "dbo.Genres");
DropForeignKey("dbo.Songs", "GenreId", "dbo.Genres");
DropForeignKey("dbo.SongPerformers", "PerformerId", "dbo.Performers");
DropForeignKey("dbo.SongPerformers", "SongId", "dbo.Songs");
DropForeignKey("dbo.SongAlbums", "AlbumId", "dbo.Albums");
DropForeignKey("dbo.SongAlbums", "SongId", "dbo.Songs");
DropIndex("dbo.SongPerformers", new[] { "PerformerId" });
DropIndex("dbo.SongPerformers", new[] { "SongId" });
DropIndex("dbo.SongAlbums", new[] { "AlbumId" });
DropIndex("dbo.SongAlbums", new[] { "SongId" });
DropIndex("dbo.Songs", new[] { "GenreId" });
DropIndex("dbo.Albums", new[] { "GenreId" });
DropTable("dbo.SongPerformers");
DropTable("dbo.SongAlbums");
DropTable("dbo.Performers");
DropTable("dbo.Songs");
DropTable("dbo.Genres");
DropTable("dbo.Albums");
}
}
}
<file_sep>/Songs.Test/Program.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Songs.Classes;
using Songs.DataLayer;
using Songs.DataLayer.Contexts;
namespace Songs.Test
{
internal class Program
{
static void Main(string[] args)
{
//var ini = new SongInitializer();
using (var db = new SongContext())
{
Database.SetInitializer(new DropCreateDatabaseAlways<SongContext>());
Console.WriteLine("aantal songs: " + db.Songs.Count());
Console.Read();
}
//var db = new SongContext();
//ct.Database.Delete();
//ct.Database.Create();
/*
using (var context = new SongContext())
{
Song song = context.Songs.FirstOrDefault();
Console.WriteLine("Songtitle: " + song.Title);
Console.WriteLine("Song album: " + song.Albums.First().Title);
Console.WriteLine("Song genreId: " + song.GenreId);
Console.WriteLine("Song genre: " + song.SongGenre.Name);
Console.WriteLine("song performer: " + song.Performers.First().FirstName);
Console.Read();
}
*/
}
}
}
<file_sep>/Songs.DataModel/Interfaces/ISongRepository.cs
using System;
using System.Linq;
using System.Linq.Expressions;
using Songs.Classes;
namespace Songs.DataLayer.Interfaces
{
public interface ISongRepository: IDisposable
{
IQueryable<Song> AllSongs { get; }
IQueryable<Performer> AllPerformers { get; }
IQueryable<Album> AllAlbums { get; }
IQueryable<Genre> AllGenres { get; }
Song Find(int id);
Song FindWithGenreAlbumPerformer(int id);
void InsertOrUpdate(Song song);
void Delete(int songId);
void Save();
}
}
<file_sep>/Songs.DataModel/Repositories/AlbumRepository.cs
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using Songs.Classes;
using Songs.DataLayer.Contexts;
using Songs.DataLayer.Interfaces;
namespace Songs.DataLayer.Repositories
{
public class AlbumRepository: IAlbumRepository
{
private readonly SongContext _context = new SongContext();
public IQueryable<Album> All => _context.Albums.Include(a=>a.AlbumGenre);
public Album Find(int? id)
{
return _context.Albums.Include(a => a.AlbumGenre).First(a => a.AlbumId == id);
}
public void InsertOrUpdate(Album album)
{
if (album.AlbumId == default(int))
{
SqlParameter parTitle = new SqlParameter("@Title", album.Title);
SqlParameter parReleaseDate = new SqlParameter("@ReleaseDate", album.ReleaseDate);
SqlParameter parGenreId = new SqlParameter("@GenreId", album .GenreId);
_context.Database.ExecuteSqlCommand("dbo.Album_Insert @Title, @ReleaseDate, @GenreId", parTitle, parReleaseDate,
parGenreId);
}
else
{
SqlParameter parAlbumId = new SqlParameter("@AlbumId", album.AlbumId);
SqlParameter parTitle = new SqlParameter("@Title", album.Title);
SqlParameter parReleaseDate = new SqlParameter("@ReleaseDate", album.ReleaseDate);
SqlParameter parGenreId = new SqlParameter("@GenreId", album.GenreId);
_context.Database.ExecuteSqlCommand("dbo.Album_Update @AlbumId, @Title, @ReleaseDate, @GenreId", parAlbumId, parTitle, parReleaseDate,
parGenreId);
}
}
public void Delete(int albumId)
{
var sqlpar = new SqlParameter("@AlbumId", albumId);
_context.Database.ExecuteSqlCommand("dbo.Album_Delete @AlbumId", sqlpar);
}
public void Save()
{
_context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
}
<file_sep>/Songs.UI/Controllers/SongsController.cs
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Songs.Classes;
using Songs.DataLayer.Repositories;
using Songs.UI.Viewmodels;
namespace Songs.UI.Controllers
{
public class SongsController : Controller
{
private readonly SongRepository _repoSong = new SongRepository();
// GET: Songs
public ActionResult Index() => View(_repoSong.AllSongs.ToList());
// GET: Songs/Details/5
public ActionResult Details(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
Song song = _repoSong.Find((int)id);
if (song == null) return HttpNotFound();
return View(song);
}
// GET: Songs/Create
public ActionResult Create()
{
EditCreateSong ecs = new EditCreateSong
{
EditSong = new Song(),
SelectedPerformers = new List<int>(),
SelectedAlbums = new List<int>(),
Performers = new MultiSelectList(_repoSong.AllPerformers, "PerformerId", "FullName"),
Albums = new MultiSelectList(_repoSong.AllAlbums, "AlbumId", "Title")
};
ViewBag.GenreId = new SelectList(_repoSong.AllGenres, "GenreId", "Name");
return View(ecs);
}
// POST: Songs/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EditSong, SelectedPerformers, SelectedAlbums")] EditCreateSong ecs)
{
if (ModelState.IsValid)
{
Song song = new Song
{
Title = ecs.EditSong.Title,
Duration = ecs.EditSong.Duration,
ReleaseDate = ecs.EditSong.ReleaseDate
};
if (ecs.SelectedPerformers != null)
{
foreach (var performer in _repoSong.AllPerformers)
{
if (ecs.SelectedPerformers.Contains(performer.PerformerId)) song.Performers.Add(performer);
}
}
if (ecs.SelectedAlbums != null)
{
foreach (var album in _repoSong.AllAlbums)
{
if (ecs.SelectedAlbums.Contains(album.AlbumId)) song.Albums.Add(album);
}
}
if (TryUpdateModel(song, "", new[] { "GenreId" }))
{
_repoSong.InsertOrUpdate(song);
_repoSong.Save();
return RedirectToAction("Index");
}
}
ViewBag.GenreId = new SelectList(_repoSong.AllGenres, "GenreId", "Name", ecs.EditSong.GenreId);
return View();
}
// GET: Songs/Edit/5
public ActionResult Edit(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
EditCreateSong ecs = new EditCreateSong
{
EditSong = _repoSong.FindWithGenreAlbumPerformer((int) id)
};
if (ecs.EditSong == null) return HttpNotFound();
ecs.SelectedPerformers = new List<int>(ecs.EditSong.Performers.Select(p => p.PerformerId));
ecs.SelectedAlbums = new List<int>(ecs.EditSong.Albums.Select(a=>a.AlbumId));
ecs.Performers = new MultiSelectList(_repoSong.AllPerformers, "PerformerId", "FullName", ecs.SelectedPerformers);
ecs.Albums = new MultiSelectList(_repoSong.AllAlbums, "AlbumId", "Title", ecs.SelectedAlbums);
ViewBag.GenreId = new SelectList(_repoSong.AllGenres, "GenreId", "Name", ecs.EditSong.GenreId);
return View(ecs);
}
// POST: Songs/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
//public ActionResult Edit([Bind(Include = "SongId,Title,Duration,ReleaseDate,GenreId")] Song song)
public ActionResult Edit([Bind(Include = "EditSong, SelectedPerformers, SelectedAlbums")] EditCreateSong ecs)
{
if (ModelState.IsValid)
{
Song song = _repoSong.FindWithGenreAlbumPerformer(ecs.EditSong.SongId);
song.Title = ecs.EditSong.Title;
song.Duration = ecs.EditSong.Duration;
song.ReleaseDate = ecs.EditSong.ReleaseDate;
if (ecs.SelectedPerformers != null)
{
foreach (var performer in _repoSong.AllPerformers)
{
if (ecs.SelectedPerformers.Contains(performer.PerformerId))
{
if (!song.Performers.Contains(performer)) song.Performers.Add(performer);
}
else
{
if (song.Performers.Contains(performer)) song.Performers.Remove(performer);
}
}
}
if (ecs.SelectedAlbums != null)
{
foreach (var album in _repoSong.AllAlbums)
{
if (ecs.SelectedAlbums.Contains(album.AlbumId))
{
if(!song.Albums.Contains(album)) song.Albums.Add(album);
}
else
{
if (song.Albums.Contains(album)) song.Albums.Remove(album);
}
}
}
if (TryUpdateModel(song, "", new[] {"GenreId"}))
{
_repoSong.InsertOrUpdate(song);
_repoSong.Save();
return RedirectToAction("Index");
}
}
ViewBag.GenreId = new SelectList(_repoSong.AllGenres, "GenreId", "Name", ecs.EditSong.GenreId);
return View();
}
// GET: Songs/Delete/5
public ActionResult Delete(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
Song song = _repoSong.Find((int) id);
if (song == null) return HttpNotFound();
return View(song);
}
// POST: Songs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
_repoSong.Delete(id);
_repoSong.Save();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_repoSong.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>/Songs.DataModel/Migrations/201710301333348_Initial.cs
namespace Songs.DataLayer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Albums",
c => new
{
AlbumId = c.Int(nullable: false, identity: true),
Title = c.String(nullable: false, maxLength: 50),
ReleaseDate = c.DateTime(nullable: false),
GenreId = c.Int(),
})
.PrimaryKey(t => t.AlbumId)
.ForeignKey("dbo.Genres", t => t.GenreId)
.Index(t => t.GenreId);
CreateTable(
"dbo.Genres",
c => new
{
GenreId = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 50),
})
.PrimaryKey(t => t.GenreId);
CreateTable(
"dbo.Songs",
c => new
{
SongId = c.Int(nullable: false, identity: true),
Title = c.String(nullable: false, maxLength: 50),
Duration = c.Time(nullable: false, precision: 7),
ReleaseDate = c.DateTime(nullable: false),
GenreId = c.Int(),
})
.PrimaryKey(t => t.SongId)
.ForeignKey("dbo.Genres", t => t.GenreId)
.Index(t => t.GenreId);
CreateTable(
"dbo.Performers",
c => new
{
PerformerId = c.Int(nullable: false, identity: true),
FirstName = c.String(nullable: false, maxLength: 50),
LastName = c.String(nullable: false, maxLength: 50),
NickName = c.String(maxLength: 50),
Birthday = c.DateTime(nullable: false),
BirthPlace = c.String(maxLength: 50),
Country = c.String(maxLength: 50),
})
.PrimaryKey(t => t.PerformerId);
CreateTable(
"dbo.SongAlbums",
c => new
{
Song_SongId = c.Int(nullable: false),
Album_AlbumId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Song_SongId, t.Album_AlbumId })
.ForeignKey("dbo.Songs", t => t.Song_SongId, cascadeDelete: true)
.ForeignKey("dbo.Albums", t => t.Album_AlbumId, cascadeDelete: true)
.Index(t => t.Song_SongId)
.Index(t => t.Album_AlbumId);
CreateTable(
"dbo.PerformerSongs",
c => new
{
Performer_PerformerId = c.Int(nullable: false),
Song_SongId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Performer_PerformerId, t.Song_SongId })
.ForeignKey("dbo.Performers", t => t.Performer_PerformerId, cascadeDelete: true)
.ForeignKey("dbo.Songs", t => t.Song_SongId, cascadeDelete: true)
.Index(t => t.Performer_PerformerId)
.Index(t => t.Song_SongId);
CreateStoredProcedure(
"dbo.Album_Insert",
p => new
{
Title = p.String(maxLength: 50),
ReleaseDate = p.DateTime(),
GenreId = p.Int(),
},
body:
@"INSERT [dbo].[Albums]([Title], [ReleaseDate], [GenreId])
VALUES (@Title, @ReleaseDate, @GenreId)
DECLARE @AlbumId int
SELECT @AlbumId = [AlbumId]
FROM [dbo].[Albums]
WHERE @@ROWCOUNT > 0 AND [AlbumId] = scope_identity()
SELECT t0.[AlbumId]
FROM [dbo].[Albums] AS t0
WHERE @@ROWCOUNT > 0 AND t0.[AlbumId] = @AlbumId"
);
CreateStoredProcedure(
"dbo.Album_Update",
p => new
{
AlbumId = p.Int(),
Title = p.String(maxLength: 50),
ReleaseDate = p.DateTime(),
GenreId = p.Int(),
},
body:
@"UPDATE [dbo].[Albums]
SET [Title] = @Title, [ReleaseDate] = @ReleaseDate, [GenreId] = @GenreId
WHERE ([AlbumId] = @AlbumId)"
);
CreateStoredProcedure(
"dbo.Album_Delete",
p => new
{
AlbumId = p.Int(),
},
body:
@"DELETE [dbo].[Albums]
WHERE ([AlbumId] = @AlbumId)"
);
}
public override void Down()
{
DropStoredProcedure("dbo.Album_Delete");
DropStoredProcedure("dbo.Album_Update");
DropStoredProcedure("dbo.Album_Insert");
DropForeignKey("dbo.Albums", "GenreId", "dbo.Genres");
DropForeignKey("dbo.Songs", "GenreId", "dbo.Genres");
DropForeignKey("dbo.PerformerSongs", "Song_SongId", "dbo.Songs");
DropForeignKey("dbo.PerformerSongs", "Performer_PerformerId", "dbo.Performers");
DropForeignKey("dbo.SongAlbums", "Album_AlbumId", "dbo.Albums");
DropForeignKey("dbo.SongAlbums", "Song_SongId", "dbo.Songs");
DropIndex("dbo.PerformerSongs", new[] { "Song_SongId" });
DropIndex("dbo.PerformerSongs", new[] { "Performer_PerformerId" });
DropIndex("dbo.SongAlbums", new[] { "Album_AlbumId" });
DropIndex("dbo.SongAlbums", new[] { "Song_SongId" });
DropIndex("dbo.Songs", new[] { "GenreId" });
DropIndex("dbo.Albums", new[] { "GenreId" });
DropTable("dbo.PerformerSongs");
DropTable("dbo.SongAlbums");
DropTable("dbo.Performers");
DropTable("dbo.Songs");
DropTable("dbo.Genres");
DropTable("dbo.Albums");
}
}
}
<file_sep>/Songs.UI/Viewmodels/EditCreateSong.cs
using System.Collections.Generic;
using System.Web.Mvc;
using Songs.Classes;
namespace Songs.UI.Viewmodels
{
public class EditCreateSong
{
public Song EditSong { get; set; }
public MultiSelectList Performers { get; set; }
public MultiSelectList Albums { get; set; }
public List<int> SelectedPerformers { get; set; }
public List<int> SelectedAlbums { get; set; }
}
}<file_sep>/Songs.Classes/Genre.cs
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Songs.Classes
{
public class Genre
{
[Key]
public int GenreId { get; set; }
[Required(ErrorMessage = "The Name field is required")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "The Name field has a minimum length of 3 and a maximum length of 50")]
[RegularExpression(@"^[a-zA-Z0-9 ]*$", ErrorMessage = "The Name field may only contain letters and numbers")]
public string Name { get; set; }
public virtual ICollection<Song> Songs { get; set; } = new HashSet<Song>();
public virtual ICollection<Album> Albums { get; set; } = new HashSet<Album>();
}
}
<file_sep>/Songs.DataModel/Repositories/SongRepository.cs
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using Songs.Classes;
using Songs.DataLayer.Contexts;
using Songs.DataLayer.Interfaces;
namespace Songs.DataLayer.Repositories
{
public class SongRepository: ISongRepository
{
private readonly SongContext _context = new SongContext();
public IQueryable<Song> AllSongs => _context.Songs.Include(s=>s.SongGenre);
public IQueryable<Performer> AllPerformers => _context.Performers;
public IQueryable<Album> AllAlbums => _context.Albums;
public IQueryable<Genre> AllGenres => _context.Genres;
public Song FindWithGenreAlbumPerformer(int id)
{
return _context.Songs.Include(s => s.Performers).Include(s => s.Albums).Include(s => s.SongGenre).First(s => s.SongId == id);
}
public Song Find(int id)
{
return _context.Songs.Find(id);
}
public void InsertOrUpdate(Song song)
{
if (song.SongId == default(int))
{
_context.Songs.Add(song);
}
else
{
_context.Entry(song).State = EntityState.Modified;
}
}
public void Delete(int songId)
{
Song song = _context.Songs.Find(songId);
if(song != null) _context.Songs.Remove(song);
}
public void Save()
{
_context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
}
<file_sep>/Songs.Classes/Album.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Songs.Classes
{
public class Album
{
[Key]
public int AlbumId { get; set; }
[Required(ErrorMessage = "The Title field is required")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "The Title field has a minimum length of 3 and a maximum length of 50")]
[RegularExpression(@"^[a-zA-Z0-9 ]*$", ErrorMessage = "The Title field may only contain letters and numbers")]
public string Title { get; set; }
[DataType(DataType.Date, ErrorMessage = "Releasedate is NOT a date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }
public virtual ICollection<Song> Songs { get; set; } = new HashSet<Song>();
[ForeignKey("AlbumGenre")]
public int? GenreId { get; set; }
[DisplayName("Genre")]
public Genre AlbumGenre { get; set; }
}
}
<file_sep>/Songs.Classes/Performer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Songs.Classes
{
public class Performer
{
[Key]
public int PerformerId { get; set; }
[DisplayName("First name")]
[Required(ErrorMessage = "First name is required")]
[StringLength(50, MinimumLength = 2, ErrorMessage = "First name has a minimum length of 2 and a maximum length of 50")]
[RegularExpression(@"^[a-zA-Z ]*$", ErrorMessage = "First name may only contain letters")]
public string FirstName { get; set; }
[DisplayName("Surname")]
[Required(ErrorMessage = "Surname is required")]
[StringLength(50, ErrorMessage = "Surname has a minimum length of 2 and a maximum length of 50")]
[RegularExpression(@"^[a-zA-Z ]*$", ErrorMessage = "Surname may only contain letters")]
public string LastName { get; set; }
[DisplayName("Alias")]
[StringLength(50, MinimumLength = 1, ErrorMessage = "Alias has a minimum length of 1 and a maximum length of 50")]
[RegularExpression(@"^[a-zA-Z0-9 ]*$", ErrorMessage = "Alias may only contain letters and numbers")]
public string NickName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Birthday { get; set; }
[DisplayName("Birthplace")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "Birthplace has a minimum length of 3 and a maximum length of 50")]
[RegularExpression(@"^[a-zA-Z ]*$", ErrorMessage = "Birthplace may only contain letters")]
public string BirthPlace { get; set; }
[StringLength(50, MinimumLength = 3, ErrorMessage = "Country has a minimum length of 3 and a maximum length of 50")]
[RegularExpression(@"^[a-zA-Z ]*$", ErrorMessage = "First name may only contain letters")]
public string Country { get; set; }
public virtual ICollection<Song> Songs { get; set; } = new HashSet<Song>();
[NotMapped]
public string FullName => $"{FirstName} {LastName}";
}
}
<file_sep>/Songs.DataModel/Interfaces/IPerformerRepository.cs
using System;
using System.Linq;
using Songs.Classes;
namespace Songs.DataLayer.Interfaces
{
public interface IPerformerRepository: IDisposable
{
IQueryable<Performer> All { get; }
Performer Find(int id);
void InsertOrUpdate(Performer performer);
void Delete(int performerId);
void Save();
}
}
<file_sep>/Songs.UI/Viewmodels/AllViewmodel.cs
using System.Collections.Generic;
using Songs.Classes;
namespace Songs.UI.Viewmodels
{
public class AllViewmodel
{
public IEnumerable<Song> Songs { get; set; }
public IEnumerable<Genre> Genres { get; set; }
public IEnumerable<Album> Albums { get; set; }
public IEnumerable<Performer> Performers { get; set; }
}
}<file_sep>/Songs.Classes/Song.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Songs.Classes
{
public class Song
{
[Key]
public int SongId { get; set; }
[Required]
[StringLength(50, MinimumLength = 1, ErrorMessage = "The Title has a minimum length of 1 and a maximum length of 50")]
[RegularExpression(@"^[a-zA-Z0-9 ]*$", ErrorMessage = "The Title may only contain letters and numbers")]
public string Title { get; set; }
public TimeSpan Duration { get; set; }
[DataType(DataType.Date, ErrorMessage = "Releasedate is NOT a date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime ReleaseDate { get; set; }
[Display(Name = "Albums")]
public virtual ICollection<Album> Albums { get; set; } = new HashSet<Album>();
[Display(Name = "Performers")]
public virtual ICollection<Performer> Performers { get; set; } = new HashSet<Performer>();
[ForeignKey("SongGenre")]
public int? GenreId { get; set; }
[DisplayName("Genre")]
public virtual Genre SongGenre { get; set; }
}
}
<file_sep>/Songs.DataModel/Repositories/PerformerRepository.cs
using System.Data.Entity;
using System.Linq;
using Songs.Classes;
using Songs.DataLayer.Contexts;
using Songs.DataLayer.Interfaces;
namespace Songs.DataLayer.Repositories
{
public class PerformerRepository: IPerformerRepository
{
private readonly SongContext _context = new SongContext();
public IQueryable<Performer> All => _context.Performers;
public Performer Find(int id)
{
return _context.Performers.Find(id);
}
public void InsertOrUpdate(Performer performer)
{
if (performer.PerformerId == default(int))
{
_context.Performers.Add(performer);
}
else
{
_context.Entry(performer).State = EntityState.Modified;
}
}
public void Delete(int performerId)
{
Performer performer = _context.Performers.Find(performerId);
if (performer != null) _context.Performers.Remove(performer);
}
public void Save()
{
_context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
}
<file_sep>/Songs.DataModel/Repositories/GenreRepository.cs
using System.Data.SqlClient;
using System.Linq;
using Songs.Classes;
using Songs.DataLayer.Contexts;
using Songs.DataLayer.Interfaces;
namespace Songs.DataLayer.Repositories
{
public class GenreRepository: IGenreRepository
{
private readonly SongContext _context = new SongContext();
public IQueryable<Genre> All => _context.Genres;
public Genre Find(int id)
{
var sqlQuery = "SELECT * FROM dbo.Genres WHERE GenreId=@GenreId";
SqlParameter parGenreId = new SqlParameter("@GenreId", id);
var result = _context.Genres.SqlQuery(sqlQuery, parGenreId).SingleOrDefault();
return result;
}
public void InsertOrUpdate(Genre genre)
{
if (genre.GenreId == default(int))
{
var sqlQuery = "INSERT INTO dbo.Genres (Name) VALUES(@Name)";
SqlParameter parName = new SqlParameter("@Name", genre.Name);
_context.Database.ExecuteSqlCommand(sqlQuery, parName);
}
else
{
var sqlQuery = "UPDATE dbo.Genres SET Name=@Name WHERE GenreId=@GenreId";
SqlParameter parName = new SqlParameter("@Name", genre.Name);
SqlParameter parGenreId = new SqlParameter("@GenreId", genre.GenreId);
_context.Database.ExecuteSqlCommand(sqlQuery,parName,parGenreId);
}
}
public void Delete(int genreId)
{
var sqlQuery = "DELETE FROM dbo.Genres WHERE GenreId=@GenreId";
SqlParameter parGenreId = new SqlParameter("@GenreId", genreId);
_context.Database.ExecuteSqlCommand(sqlQuery, parGenreId);
}
public void Save()
{
_context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
}
<file_sep>/Songs.DataModel/Interfaces/IAlbumRepository.cs
using System;
using System.Linq;
using Songs.Classes;
namespace Songs.DataLayer.Interfaces
{
public interface IAlbumRepository:IDisposable
{
IQueryable<Album> All { get; }
Album Find(int? id);
void InsertOrUpdate(Album album);
void Delete(int albumId);
void Save();
}
}
<file_sep>/Songs.DataModel/Migrations/201710191928004_DropCreateDB.cs
namespace Songs.DataLayer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class DropCreateDB : DbMigration
{
public override void Up()
{
CreateStoredProcedure(
"dbo.Album_Insert",
p => new
{
Title = p.String(maxLength: 50),
ReleaseDate = p.DateTime(),
GenreId = p.Int(),
},
body:
@"INSERT [dbo].[Albums]([Title], [ReleaseDate], [GenreId])
VALUES (@Title, @ReleaseDate, @GenreId)
DECLARE @AlbumId int
SELECT @AlbumId = [AlbumId]
FROM [dbo].[Albums]
WHERE @@ROWCOUNT > 0 AND [AlbumId] = scope_identity()
SELECT t0.[AlbumId]
FROM [dbo].[Albums] AS t0
WHERE @@ROWCOUNT > 0 AND t0.[AlbumId] = @AlbumId"
);
CreateStoredProcedure(
"dbo.Album_Update",
p => new
{
AlbumId = p.Int(),
Title = p.String(maxLength: 50),
ReleaseDate = p.DateTime(),
GenreId = p.Int(),
},
body:
@"UPDATE [dbo].[Albums]
SET [Title] = @Title, [ReleaseDate] = @ReleaseDate, [GenreId] = @GenreId
WHERE ([AlbumId] = @AlbumId)"
);
CreateStoredProcedure(
"dbo.Album_Delete",
p => new
{
AlbumId = p.Int(),
},
body:
@"DELETE [dbo].[Albums]
WHERE ([AlbumId] = @AlbumId)"
);
}
public override void Down()
{
DropStoredProcedure("dbo.Album_Delete");
DropStoredProcedure("dbo.Album_Update");
DropStoredProcedure("dbo.Album_Insert");
}
}
}
<file_sep>/Songs.DataModel/Contexts/SongContext.cs
using System.Data.Entity;
using Songs.Classes;
namespace Songs.DataLayer.Contexts
{
public class SongContext : DbContext
{
public SongContext(): base("Songs"){}
public DbSet<Album> Albums { get; set; }
public DbSet<Song> Songs { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Performer> Performers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Album>().MapToStoredProcedures();
}
}
}
<file_sep>/Songs.DataModel/Migrations/Configuration.cs
using System.Data.Entity;
using System.Linq;
using Songs.DataLayer.Contexts;
namespace Songs.DataLayer.Migrations
{
using System;
using System.Data.Entity.Migrations;
using Classes;
internal sealed class Configuration : DbMigrationsConfiguration<SongContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
//Database.SetInitializer(new DropCreateDatabaseAlways<SongContext>());
}
protected override void Seed(SongContext context)
{
Genre genre1 = new Genre
{
Name = "Rock"
};
context.Genres.AddOrUpdate(genre1);
Performer performer1 = new Performer
{
FirstName = "Ikke",
LastName = "Testing",
NickName = "Ananas",
Birthday = new DateTime(1980, 10, 19),
BirthPlace = "Antwerpen",
Country = "Belgie"
};
context.Performers.AddOrUpdate(performer1);
Album album1 = new Album
{
Title = "Testalbum",
ReleaseDate = new DateTime(2000, 11, 20)
};
context.Albums.AddOrUpdate(album1);
Song song1 = new Song
{
Title = "Baracuda",
ReleaseDate = new DateTime(1999, 05, 05),
Duration = new TimeSpan(0, 2, 30)
};
context.Songs.AddOrUpdate(song1);
context.SaveChanges();
Song song = context.Songs.FirstOrDefault();
Genre genre = context.Genres.FirstOrDefault();
Album album = context.Albums.FirstOrDefault();
Performer performer = context.Performers.FirstOrDefault();
//System.Diagnostics.Debug.WriteLine(song.Title);
if (song != null)
{
song.Performers.Add(performer);
song.Albums.Add(album);
if (genre != null)
{
song.GenreId = genre.GenreId;
song.SongGenre = genre;
}
}
if (album != null && genre != null)
{
album.GenreId = genre.GenreId;
album.AlbumGenre = genre;
}
context.SaveChanges();
}
}
}
| e152ccb7feb2b0a77d48ffaa76baf2fcec69a63a | [
"C#"
]
| 25 | C# | RobinVanRoy/Songs | 452792df3a0729060f295bd9367490b2d4b00d76 | 70e41b4e9f6b0351982ebb19e8b0afbbb112b449 |
refs/heads/master | <repo_name>NekitoSP/spider<file_sep>/README.markdown
## Spider
Spider is a Drupal module for my University project. It searches for IT jobs on job boards, adds the new jobs into the database, and shows them on the site with neat statistic information for further analysis, which can be a good starting point for considering to change the study plans in the University to match the modern technologies, and detect new trends in IT workers demand in our local area.
Created with the collaboration of my good friend/colleague, [<NAME>](https://github.com/NekitoSP). He is responsible for parsing job boards and saving everything into the database. I'm responsible for the Drupal module itself: settings, custom widget, custom page, and how the data is shown on the site.
**Disclaimer:** We're not Drupal Experts or Pros :-)<file_sep>/parser.php
<?php
abstract class SiteParser {
abstract protected function parse(); // for parse
/*
C:\web server\htdocs\vmk\test\sites\all\modules\spider>schtasks /create /tn "spi
der_update" /tr "C:\web server\htdocs\vmk\test\update-task.bat" /sc minute /mo 1
5
http://www.microsofttranslator.com/BV.aspx?ref=CSSKB&lo=SS&from=en&to=ru&a=http://support.microsoft.com/kb/823093/en-us?fr=1
http://serverfault.com/questions/9038/run-a-bat-file-in-a-scheduled-task-without-a-window
*/
function parseEng($strDesc){
$strDesc = preg_replace("/\<style\>.*?\<\/style\>/i",'',$strDesc);//убираем тег <style> с его содержимым
$strDesc = preg_replace("/\<xml\>.*?\<\/xml\>/i",'',$strDesc); //аналогично с <xml>
$strDesc = preg_replace("/ \+ /i",'Ё',$strDesc); //разделяем строки подобные "html + css + js" на отдельные части
$strDesc = htmlspecialchars_decode($strDesc); //декодируем html-сущности
$strDesc = preg_replace("/\<\!\-\-[^>]*\>/i",'',$strDesc);//убираем html комменты
$strDesc = preg_replace("/\<li\>/i","<li> Ё ",$strDesc);
$strDesc = strip_tags($strDesc); //убираем теги, но оставляет "li"
$strDesc = str_replace("\r", ' ', $strDesc);//
$strDesc = str_replace("\n", ' ', $strDesc);//убираем всякие левые символы в т.ч. переносы строк
$strDesc = str_replace("\t", ' ', $strDesc);//
$arr = preg_match_all("/([a-zA-Z][\w\d\-\:\+\#\. ]{1,})/i",$strDesc,$res);//ищем слова с англ.буквы, в т.ч. и последовательности слов
$strArr = array();
foreach ($res[1] as $key => $value){//и заполняем результирующий массив
$value = trim($value,"-. ");//очищаем с начала строки и с конца все дефисы точки и пробелы
if (!isset($strArr) || !in_array($value, $strArr))
$strArr[] = strtolower($value);//lowercase
}
return $strArr;
}
public function xmlObjToArr($obj) {
$namespace = $obj->getDocNamespaces(true);
$namespace[NULL] = NULL;
$children = array();
$attributes = array();
$name = strtolower((string)$obj->getName());
$text = trim((string)$obj);
if( strlen($text) <= 0 ) {
$text = NULL;
}
// get info for all namespaces
if(is_object($obj)) {
foreach( $namespace as $ns=>$nsUrl ) {
// atributes
$objAttributes = $obj->attributes($ns, true);
foreach( $objAttributes as $attributeName => $attributeValue ) {
$attribName = strtolower(trim((string)$attributeName));
$attribVal = trim((string)$attributeValue);
if (!empty($ns)) {
$attribName = $ns . ':' . $attribName;
}
$attributes[$attribName] = $attribVal;
}
// children
$objChildren = $obj->children($ns, true);
foreach( $objChildren as $childName=>$child ) {
$childName = strtolower((string)$childName);
if( !empty($ns) ) {
$childName = $ns.':'.$childName;
}
$children[$childName][] = $this::xmlObjToArr($child);
}
}
}
if (!$text==NULL) $ret['text'] = $text;
if (count($attributes)>=1) $ret['attributes'] = $attributes;
if (count($children)>=1) $ret['children'] = $children;
return $ret;
}
}
class HHParser extends SiteParser{
private $region; //регион
private $professionalField; //проф.область
public function HHParser($params){
//Регион: Башкортостан - 1347
//проф.область: IT - 1
}
public function parse(){
$proxyhost = variable_get('spider_proxy_host', "proxy.ugatu.ac.ru");
$proxyport = variable_get('spider_proxy_port', "8008");
$proxy = $proxyhost.":".$proxyport;
$region = variable_get('spider_region', "1347")."";
$professionalField = variable_get('spider_category', "1")."";
//$region = "1347";
//$professionalField = "1";
//$fp = fopen('spiderdump.txt', 'a+'); // Текстовый режим
$spiderName = "hhunt";
//качаем страничку с hh.ru, пока без пагинации, последние 1000 записей
if( $curl = curl_init() ) {
curl_setopt($curl, CURLOPT_URL, "http://api.hh.ru/1/xml/vacancy/search/?region=".$region."&order=2&field=".$professionalField."&items=200");
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_PROXY,$proxy);
$out = curl_exec($curl);
//echo $out;
curl_close($curl);
}
//парсим файл
$doc = new SimpleXMLElement($out);
$parsedArr = parent::xmlObjToArr($doc);
//получаем дату последнго апдейта из БД по последней записи
$result = db_query_range('SELECT updated FROM {spider_joblist} ORDER BY updated DESC', 0, 1);
$accLast = db_fetch_array($result);
//цикл по скачанным вакансиям
foreach($parsedArr["children"]["vacancies"][0]["children"]["vacancy"] as $k => $val){
$jobId = $val["attributes"]["id"];
$jobCompanyId = 0;
if (isset($val["children"]["employer"][0]["attributes"]["id"])){
$jobCompanyId = $val["children"]["employer"][0]["attributes"]["id"];
}
//скачаем описание вакансии
unset($out);
if( $curl = curl_init() ) {
curl_setopt($curl, CURLOPT_URL, 'http://api.hh.ru/1/xml/vacancy/'.$jobId.'/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_PROXY,$proxy);
$out = curl_exec($curl);
curl_close($curl);
}
$doc = new SimpleXMLElement($out);
$jobPage = parent::xmlObjToArr($doc);
$jobDescription = '';
if (isset($jobPage["children"]["description"][0]["text"])){
$jobDescription = $jobPage["children"]["description"][0]["text"];
}
$jobCaption = '';
if (isset($val["children"]["name"][0]["text"])){
$jobCaption = $val["children"]["name"][0]["text"];
}
$jobLastUpdateTime = 0;
if (isset($val["children"]["update"][0]["attributes"]["timestamp"])){
$jobLastUpdateTime = $val["children"]["update"][0]["attributes"]["timestamp"];
}
$jobWageFrom = 0;
if (isset( $val["children"]["salary"][0]["children"]["from"][0]["text"] )){
$jobWageFrom = $val["children"]["salary"][0]["children"]["from"][0]["text"];
}
$jobWageTo = 0;
if (isset( $val["children"]["salary"][0]["children"]["to"][0]["text"] )){
$jobWageTo = $val["children"]["salary"][0]["children"]["to"][0]["text"];
}
$jobWageCurrency = "N/A";
if (isset( $val["children"]["salary"][0]["children"]["currency"][0]["text"] )){
$jobWageCurrency = $val["children"]["salary"][0]["children"]["currency"][0]["text"];
}
//проверить наличие данной компании в таблице компаний, иначе - распарсим и добавим
$companyExists = db_fetch_array(db_query("SELECT * FROM {spider_companies} WHERE id=%d",$jobCompanyId));
//echo $companyExists;
if($companyExists == FALSE){
if( $curl = curl_init() ) {
curl_setopt($curl, CURLOPT_URL, 'http://api.hh.ru/1/xml/employer/'.$jobCompanyId.'/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_PROXY,$proxy);
$outCompany = curl_exec($curl);
curl_close($curl);
}
$doc = new SimpleXMLElement($outCompany);
$companyPage = parent::xmlObjToArr($doc);
$companyName = "";
if(isset($companyPage["children"]["name"][0]["text"])){
$companyName = $companyPage["children"]["name"][0]["text"];
}
$companyLogo = "";
if(isset($companyPage["children"]["logos"][0]["children"]["link"][1]["attributes"]["href"])){
$companyLogo = $companyPage["children"]["logos"][0]["children"]["link"][1]["attributes"]["href"];
}
$companyUrl = "";
if(isset($companyPage["children"]["link"][2]["attributes"]["href"])){
$companyUrl = $companyPage["children"]["link"][2]["attributes"]["href"];
}
$companyDescription = "";
if(isset($companyPage["children"]["full-description"][0]["text"])){
$companyDescription = $companyPage["children"]["full-description"][0]["text"];
}
//добавим работодателя в базу
db_query("INSERT INTO {spider_companies} (`id`, `name`, `site`, `logo`, `about`) VALUES (%d, '%s','%s','%s','%s');",$jobCompanyId, $companyName, $companyUrl, $companyLogo, $companyDescription);
}
$engKeywords = parent::parseEng($jobDescription);
$insKewords = $engKeywords;
//fwrite($fp,"DUMP OF $jobId :\n");
//fwrite($fp, print_r($engKeywords,true));
//fwrite($fp,"\n");
//вакансия "свежа", добавим в базу или обновим если есть
if (!isset($accLast["updated"]) || $accLast["updated"]<$jobLastUpdateTime){
$res = db_query('SELECT * FROM {spider_joblist} WHERE id = %d',$jobId);
$arr = db_fetch_array($res);
//if not exist = INSERT NEW, else = update existing
if ($arr == FALSE){
db_query("INSERT INTO {spider_joblist} (`id`, `spidername`,`name`, `companyid`, `updated`, `wagefrom`, `wageto`, `wagecurrency`, `jobdescription`) VALUES (%d, '%s', '%s', %d, %d, %d, %d, '%s', '%s');",$jobId, $spiderName,$jobCaption, $jobCompanyId, $jobLastUpdateTime, $jobWageFrom, $jobWageTo, $jobWageCurrency, $jobDescription);
} else {
db_query("UPDATE {spider_joblist} SET `name`='$jobCaption', `companyid`='$jobCompanyId', `updated`='$jobLastUpdateTime', `wagefrom`='$jobWageFrom', `wageto`='$jobWageTo', `wagecurrency`='$jobWageCurrency', `jobdescription`='$jobDescription' WHERE `id`='$jobId' ");
}
$selectMeansQuery = "SELECT * FROM {portfolio_means} WHERE ";
$insertMeansQuery = "INSERT INTO {portfolio_means} (`type`,`name`) VALUES ";
if(count($engKeywords)>0){
for($i = 0; $i<count($engKeywords);$i++){
$keyword = $engKeywords[$i];
if($i>0){
$selectMeansQuery .= " OR ";
}
$selectMeansQuery .= " name = '".$keyword."'";
}
$res = db_query($selectMeansQuery);
while($arr = db_fetch_object($res)){
$i = 0;
while($i<count($insKewords)){
if (strcmp($arr->Name,$insKewords[$i])==0){
array_splice($insKewords,$i,1);
} else {
$i++;
}
}
}
if(count($insKewords)>0){
for($i = 0; $i<count($insKewords);$i++){
$keyword = $insKewords[$i];
if($i>0){
$insertMeansQuery .= " , ";
}
$insertMeansQuery .= "(0,'".$keyword."')";
}
db_query($insertMeansQuery);
}
}
db_query("DELETE FROM {spider_relation} WHERE jobid = %d",$jobId);
$insQuery = "INSERT INTO {spider_relation} (`jobid`,`meanid`) VALUES ";
for($i = 0; $i<count($engKeywords);$i++){
$q = db_query("SELECT id FROM {portfolio_means} WHERE name = '%s'",$engKeywords[$i]);
$tag = db_fetch_object($q);
if(strpos($insQuery,"(".$jobId.",".$tag->id.")")==FALSE){
if(isset($tag->id)){
if ($i>0)
$insQuery .= ",";
$insQuery .= " (".$jobId.",".$tag->id.")";
}
}
}
if(count($engKeywords)>0)
db_query($insQuery);//вставляем отношения в таблицу
}
//var_dump($accLast["updated"]);
/*
$retnArr[$k]["id"] = $jobId;
$retnArr[$k]["text"] = $jobCaption;
$retnArr[$k]["compid"] = $jobCompanyId;
$retnArr[$k]["update"] = $jobLastUpdateTime;
$retnArr[$k]["wagefrom"] = $jobWageFrom;
$retnArr[$k]["wageto"] = $jobWageTo;
$retnArr[$k]["wagecurrency"] = $jobWageCurrency;
$retnArr[$k]["jobdescription"] = $jobDescription;
*/
}
//fclose($fp);
}
}
//$params = "{'region' = '1347', 'field' = '1'}";
//$parser = new HHParser(json_decode($params));
//$parser->parse();
<file_sep>/update-spider.php
<?php
include("parser.php");
$params = '{"region" : "1347", "field" : "1"}';
$parser = new HHParser(json_decode($params));
$parser->parse();
?> | dbac6eb736ea095b65019ac2549a45aef6690def | [
"Markdown",
"PHP"
]
| 3 | Markdown | NekitoSP/spider | c285a062aaaeb621f307bdb437c6c7c247e9d379 | 4ae28807393c752c71497543958b59845b966837 |
refs/heads/master | <repo_name>wyyyy/Vue<file_sep>/src/common/js/myjavescript.js
window.onload = function () {
var datalist = {
counter: 0,
classvalue: 'red',
message: 'hello this is my first app',
arrs: ['apple', 'banana', 'orange', 'pear'],
minput: ''
};
new Vue({
el: '#box',
data: datalist,
created: function () {
console.log("created-:实例已经创建" + (new Date()));
},
beforeCompile: function () {
console.log("beforeCompile:编译之前" + (new Date()));
},
compiled: function () {
console.log("compiled-:编译之后");
},
ready: function () {
console.log("ready-:插入到文档中");
},
methods: {
add: function () {
console.log(this.arrs);
},
mKeydown: function (ev, index) {
if (index == 1) {
console.log("mKeydown-:keyCode" + ev.keyCode);
} else {
console.log("keyup-:keyCode" + ev.keyCode);
}
}
}
});
}; | d6fc5115df3ad982d135052c85261c5e2c7ed5dd | [
"JavaScript"
]
| 1 | JavaScript | wyyyy/Vue | b82299ba64d9c12daac11d64db00b06887331851 | 3a5449825fefd5888212aa0ac90eea144300252f |
refs/heads/main | <file_sep>import React from "react";
const Search = ({ handleKeyword, keyword }) => {
return (
<>
<div className="mt-2 mx-auto flex justify-center border block rounded shadow-sm w-11/12 ">
<div className="absolute inset-y-0 left-0 pl-3 pointer-events-none"></div>
<input
type="search"
className="relative w-full bg-white border border-gray-300 rounded-md shadow-sm pl-3 pr-10 py-2 text-left cursor-default focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
placeholder="Search.."
onChange={handleKeyword}
value={keyword}
/>
</div>
</>
);
};
export default Search;
<file_sep>import React, { useState } from "react";
import data from "./utills/data";
import Select from "./components/Select";
import Search from "./components/Search";
import Actions from "./components/Actions";
import List from "./components/List";
import Products from "./components/Products";
const App = () => {
const [products, setProducts] = useState(JSON.parse(JSON.stringify(data)));
const [selectedCategory, setSelectedCategory] = useState("All");
const [keyword, setKeyword] = useState("");
const handleSelected = (event) => setSelectedCategory(event.target.value);
const handleKeyword = (event) => setKeyword(event.target.value);
const buyItem = (id) => {
let newData = products;
newData = newData.map((obj) => {
if (obj._id === id) obj.amount = obj.amount + 1;
return obj;
});
setProducts(newData);
};
const deleteItem = (id) => {
let newData = products;
newData = newData.map((obj) => {
if (obj._id === id) obj.amount = obj.amount - 1;
return obj;
});
setProducts(newData);
};
const handleReset = () => {
setProducts(JSON.parse(JSON.stringify(data)));
setSelectedCategory("All");
setKeyword("");
};
const handleDone = () => {
console.log(
"You have bought this items : ",
products
.filter((p) => p?.amount !== 0)
.map((a) => `${a?.name} X ${a?.amount}`)
.join(" ")
);
};
const getPurchasedProductsAmount = () =>
products.reduce((a, b) => a + (b["amount"] || 0), 0);
return (
<>
<div className="container mx-auto border rounded w-1/4 h-full mt-2">
<p className="text-2xl py-4 px-6 bg-gray-100 h-16 ">Shopping list</p>
<Select handleSelected={handleSelected} value={selectedCategory} />
<Search handleKeyword={handleKeyword} keyword={keyword} />
<Products
keyword={keyword}
products={products}
selectedCategory={selectedCategory}
buyItem={buyItem}
></Products>
<div className="bg-gray-100 ">
<hr></hr>
<List products={products} deleteItem={deleteItem} />
<hr className="flex flex-wrap content-center w-5/6 ml-10 mt-4"></hr>
<Actions
handleReset={handleReset}
keyword={keyword}
handleDone={handleDone}
getPurchasedProductsAmount={getPurchasedProductsAmount}
/>
</div>
</div>
</>
);
};
export default App;
<file_sep>import React from "react";
const Select = ({ handleSelected, value }) => {
return (
<div>
<div className="flex justify-center mt-4 mx-auto relative w-11/12 object-center">
<select
value={value}
onChange={handleSelected}
className="relative w-full bg-white border border-gray-300 rounded-md shadow-sm pl-3 pr-10 py-2 text-left cursor-default focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
>
<option disabled defaultValue={"All"} hidden>
Show all categories
</option>
<option value="All">Show all categories</option>
<option value="Food Appels">Food Appels</option>
<option value="Home Appels">Home Appels</option>
<option value="Computer Accessories">Computer Accessories</option>
</select>
</div>
</div>
);
};
export default Select;
<file_sep>How to run?
Simply clone or donwload the project.
Go to project folder with your code editor
"npm install" in terminal.
run "npm start" , web browser will automatically open with address http://localhost:3000/
| 5375b913c2c5d25ea62bda3ba9afe1ec274e41d0 | [
"JavaScript",
"Markdown"
]
| 4 | JavaScript | amirai92/shop | bb6890bcce17d6530ffa1648c9bdddb6621a9ac8 | 264c8b1e922d9fcb2ed8ca5a50e95f3dedbd3bee |
refs/heads/main | <file_sep>const todos=(state=[], action )=> {
switch (action.type) {
case 'ADD_TODO':
return[
...state,
todo(undefined, action)
];
case 'TOGGLE_TODO':
return state.map(t => todo(t, action));
default:
return state ;
}
};
const visibilityFilter = (
state= 'SHOW_ALL' ,
action
) => {
switch (action.type) {
case'SET_VISIBLITY_FILTER':
return action.filter;
}
};
const { combineReducers }= Redux;
const todoApp = combineReducers({
todos,
visibilityFilter
});
const {createStore} = Redux ;
const store= createStore(todoApp);
const {component} = React ;
const Filter Link = ({
filter ,
children
}) => {
return {
<a href='a'
onClick={e =>{
e.preventDefault();
store.dispatch({
type:'SET_VISIBILITY_FILTER',
filter
});
}}
>
{children}
</a>
};
};
let nextTodoId=0;
class TodoApp extends component {
render () {
const {
todos,
visibilityFilter
} = this.props;
const visibleTodos= getVisibleTodos(
this.props.todos,
this.props.visibilityFilter
);
return (
<div>
<input ref={node => {
this.input= node;
}}/>
<button onClick={() => {
store.dispatch({
type: 'ADD_TODO',
text:this.input.value,
id:nextTodoId++
});
this.input .value='';
}}>
Add Todo
</button>
<ul>
{visibleTodos.map(todo =>
<li key={todo.id}
onClick={() => {
store.dispatch({
type:'TOGGLE_TODO',
id:todo.id
});
}}
style={{
textDecoration:
todo.completed?
'line-throught';
'none'
}}>
{todo.text}
</li>
)}
</ul>
<p>
show:
{''}
<Filter='SHOW_ALL'
currentFilter={visibilityFilter}
>
All
</FilterLink>
{''}
<FilterLink
filter='SHOW_ACTIVE'
>
Active
</FilterLink>
{''}
<FilterLink
filter='SHOW_COMPLETED'
currentFilter={visibilityFilter}
>
completed
</FilterLink>
</p>
</div>
)
};
}<file_sep>/**
* Constants, or all actions that can happen within this app
*/
export const TOGGLE_FILTER = 'redux-filter/TOGGLE_FILTER';
export const KEYWORD_SEARCH = 'redux-filter/KEYWORD_SEARCH';
export const TOGGLE_FILTER_ONLY = 'redux-filter/TOGGLE_FILTER_ONLY';
export const CLEAR_FILTERS = 'redux-filter/CLEAR_FILTERS';
export const APPLY_SORT = 'redux-filter/APPLY_SORT';
export const CLEAR_ALL_FILTERS = 'redux-filter/CLEAR_ALL_FILTERS';
export const GO_TO_PAGE = 'redux-filter/GO_TO_PAGE';
export const UPDATE_SUBJECTS = 'redux-filter/UPDATE_SUBJECTS';
export const INIT = 'redux-filter/INIT';<file_sep>import { collection } from './filter.js';
export default function buildSelector(stateResolver = state => state) {
return function mapStateToProps(state) {
const result = {
collection: collection(stateResolver(state)),
optionGroups: stateResolver(state).optionGroups,
appliedFilters: stateResolver(state).appliedFilters,
keyword: stateResolver(state).keywordSearch,
sortFn: stateResolver(state).sortFn,
currentPage: stateResolver(state).page
};
return result;
};
}<file_sep>import { TOGGLE_FILTER, KEYWORD_SEARCH, TOGGLE_FILTER_ONLY, CLEAR_FILTERS, APPLY_SORT, CLEAR_ALL_FILTERS, GO_TO_PAGE, UPDATE_SUBJECTS, INIT } from '../constants.js';
export function toggleFilter(attribute, value) {
return {
type: TOGGLE_FILTER,
filter: { attribute, value }
};
}
export function toggleOnly(attribute, value) {
return {
type: TOGGLE_FILTER_ONLY,
filter: { attribute, value }
};
}
export function clearFilters(attribute) {
return {
type: CLEAR_FILTERS,
filter: { attribute }
};
}
export function keywordSearch(search) {
return {
type: KEYWORD_SEARCH,
search
};
}
export function applySort(func) {
return {
type: APPLY_SORT,
func
};
}
export function clearAllFilters() {
return {
type: CLEAR_ALL_FILTERS
};
}
export function goToPage(page) {
return {
type: GO_TO_PAGE,
page
};
}
export function updateSubjects(subjects) {
return {
type: UPDATE_SUBJECTS,
subjects
};
}
export function init() {
return {
type: INIT
};
} | 90d886a9c2101434dcf1cce294cd98aa0d24d7ae | [
"JavaScript"
]
| 4 | JavaScript | AHMED369-CREATOR/workshop-react-redux | d2d3c382a536ca77f6ea1eaff5b1daa0db3c5f8f | e86769dc41cf25220e94063a1576c9019fc6a57e |
refs/heads/master | <file_sep># html-course
I'm learning the basics of HTML
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="keywords" content="html, basics, tutorial, course">
<meta name="description" content="This website show you the basics of HTML">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My first web page</title>
<link rel="stylesheet" type="text/css" href="../css/main.css">
</head>
<body>
<h1>Types of lists</h1>
<dl>
<dt>Unordered list</dt>
<dd>Unordered list is a list without any consideration to order</dd>
<dt>Ordered list</dt>
<dd>This is a list in which order is important</dd>
<dt>Definition list</dt>
<dd>Definition list contains terms and descriptions, much like a dictionary</dd>
</dl>
<a href="news.html">Go back to news</a>
</body>
</html><file_sep>alert("Welcome to my first website!") | e7d70dc5f9985d982d25333cbbeaabffd95ec4a9 | [
"Markdown",
"JavaScript",
"HTML"
]
| 3 | Markdown | agnieszka-krawczenko/html-course | de0e8e978077f8a47287a86887f09142ee8cc759 | 9a4ab9b434af95d098b6e7e3f9eb787e0ca3e050 |
refs/heads/master | <file_sep>package com.young.youngnews.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import com.young.youngnews.InitApp;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String TAG = "DatabaseHelper";
private static String DB_NAME = "YoungNews";
private static int DB_VERSION = 1;
private static DatabaseHelper instance = null;
private static SQLiteDatabase db = null;
private DatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
private static synchronized DatabaseHelper getInstance() {
if (instance == null) {
instance = new DatabaseHelper(InitApp.appContext, DB_NAME, null, DB_VERSION);
}
return instance;
}
public static synchronized SQLiteDatabase getDatabase() {
if (db == null) {
db = getInstance().getWritableDatabase();
}
return db;
}
}
<file_sep>include ':app'
rootProject.name = "YoungNews"<file_sep>package com.young.youngnews.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import com.young.youngnews.InitApp;
import com.young.youngnews.R;
public class SettingUtil {
private static final SettingUtil instance = new SettingUtil();
private SharedPreferences setting = InitApp.appContext.getSharedPreferences("setting", Context.MODE_PRIVATE);
public static SettingUtil getInstance() {
return instance;
}
public int getColor() {
int defaultColor = InitApp.appContext.getResources().getColor(R.color.colorPrimary);
int color = setting.getInt("color", defaultColor);
if (color != 0 && Color.alpha(color) != 255) {
return defaultColor;
}
return color;
}
}
<file_sep>package com.young.youngnews.database.dao;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.young.youngnews.Constant;
import com.young.youngnews.InitApp;
import com.young.youngnews.R;
import com.young.youngnews.bean.news.NewsChannelBean;
import com.young.youngnews.database.DatabaseHelper;
import com.young.youngnews.database.table.NewsChannelTable;
import java.util.ArrayList;
import java.util.List;
public class NewsChannelDao {
private SQLiteDatabase db;
public NewsChannelDao() {
db = DatabaseHelper.getDatabase();
}
public void initData() {
String[] categoryId = InitApp.appContext.getResources().getStringArray(R.array.mobile_news_id);
String[] categoryName = InitApp.appContext.getResources().getStringArray(R.array.mobile_news_name);
//TODO 不一样
for (int i = 0; i < categoryId.length; i++) {
add(categoryId[i], categoryName[i], Constant.NEWS_CHANNEL_ENABLE, i);
}
}
public boolean add(String channelId, String channelName, int enable, int position) {
ContentValues values = new ContentValues();
values.put(NewsChannelTable.ID, channelId);
values.put(NewsChannelTable.NAME, channelName);
values.put(NewsChannelTable.IS_ENABLE, enable);
values.put(NewsChannelTable.POSITION, position);
long result = db.insert(NewsChannelTable.TABLE_NAME, null, values);
return result != -1;
}
public List<NewsChannelBean> query(int isEnable) {
Cursor cursor = db.query(NewsChannelTable.TABLE_NAME, null, NewsChannelTable.IS_ENABLE + "=?",
new String[]{isEnable + ""}, null, null, null);
List<NewsChannelBean> list = new ArrayList<>();
while (cursor.moveToNext()) {
NewsChannelBean bean = new NewsChannelBean();
bean.setChannelId(cursor.getString(NewsChannelTable.ID_ID));
bean.setChannelName(cursor.getString(NewsChannelTable.ID_NAME));
bean.setIsEnable(cursor.getInt(NewsChannelTable.ID_IS_ENABLE));
bean.setPosition(cursor.getInt(NewsChannelTable.ID_POSITION));
list.add(bean);
}
cursor.close();
return list;
}
}
<file_sep>package com.young.youngnews.module.wenda.article;
import androidx.annotation.NonNull;
public class WendaArticleView {
public static WendaArticleView newInstance() {
return new WendaArticleView();
}
@NonNull
@Override
public String toString() {
return super.toString();
}
}
<file_sep>package com.young.youngnews;
public class Constant {
public static final int NEWS_CHANNEL_ENABLE = 1;
public static final int NEWS_CHANNEL_DISABLE = 0;
}
<file_sep>package com.young.youngnews.module.news.channel;
import com.young.youngnews.module.base.BaseActivity;
public class NewsChannelActivity extends BaseActivity {
}
| dfcc87d326081628221b88f569dac613470931ae | [
"Java",
"Gradle"
]
| 7 | Java | wandereryoungg/YoungNews | 38356b477488c73f152558aad3877c626aa97c75 | bbfca67d8926c9978c9c3cb9e79229b70c857f65 |
refs/heads/master | <repo_name>51627434/ams<file_sep>/src/main/java/dong/example/ams/TestController.java
package dong.example.ams;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
@RequestMapping("/login000")
public String hello(Model model){
model.addAttribute("username","董学强");
model.addAttribute("password","<PASSWORD>");
return "login";
}
}
| cfa9ccf62415af3f869853d3dd8127f8a9c3c0c2 | [
"Java"
]
| 1 | Java | 51627434/ams | bf9d265ca35847f9fa2f2c7cb7ddff3bbbbdc781 | b08889438874cdd6c0957d78eb8465d3b900ff83 |
refs/heads/main | <file_sep>package numny.numnyRefactoring.app.subui.datepicker
import android.R
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.content.Context
import android.content.DialogInterface
import android.view.MotionEvent
import android.view.View
import android.widget.DatePicker
import android.widget.EditText
import android.widget.TimePicker
import java.text.SimpleDateFormat
import java.util.*
internal class SetDatePicker(private val editText: EditText, val context: Context) :OnTimeSetListener, DatePickerDialog.OnDateSetListener, View.OnTouchListener {
private val myCalendar: Calendar
private val fmtTimeOnly = SimpleDateFormat("HH:mm:ss", Locale.US)
override fun onDateSet(view: DatePicker?, year: Int, monthOfYear: Int, dayOfMonth: Int) {
editText.setText("")
val myFormat = "yyyy-MM-dd" //In which you need put here
val sdformat = SimpleDateFormat(myFormat, Locale.US)
myCalendar.set(Calendar.YEAR, year)
myCalendar.set(Calendar.MONTH, monthOfYear)
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
editText.setText(sdformat.format(myCalendar.time))
}
init {
editText.keyListener = null
editText.setOnTouchListener(this)
myCalendar = Calendar.getInstance()
}
override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
val cal = Calendar.getInstance()
cal[Calendar.HOUR_OF_DAY] = hourOfDay
cal[Calendar.MINUTE] = minute
cal[Calendar.SECOND] = 0
val date = cal.time
val time = fmtTimeOnly.format(date)
editText.setText(StringBuilder(editText.text).append(" ").append(time))
}
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
if(event?.action == MotionEvent.ACTION_UP){
val timePicker= TimePickerDialog(context,this,0,0,true)
timePicker.show()
val datePickerDialog: DatePickerDialog = DatePickerDialog(context, this, myCalendar[Calendar.YEAR], myCalendar[Calendar.MONTH],
myCalendar[Calendar.DAY_OF_MONTH])
datePickerDialog.datePicker.maxDate = Date().time
datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE,context. getString(R.string.cancel), DialogInterface.OnClickListener { dialog, which ->
if (which == DialogInterface.BUTTON_NEGATIVE) {
timePicker.cancel()
}
})
datePickerDialog.show()
}
return true
}
} | 9df07bda5fb04dbf1458479b8fec310f17396703 | [
"Kotlin"
]
| 1 | Kotlin | periva101/Easy-Android-Date-TimePicker | d3e55837ff6167e0a8040766bdc0a397ca189c15 | e663b862d75dd968c65ef5c60410b51f9c4c4fbb |
refs/heads/master | <repo_name>azproduction/1css<file_sep>/spec/2-selector.md
## Селекторы
Поддерживаются все CSS селекторы из любого препроцессора. Для каждого из тегов в селекторах 1CSS есть однозначно одно свойство CSS. Таблица соответствий преведены ниже.
### Соответствие тегам в селекторах 1CSS тегам HTML
Тег | Тег HTML | Описание
--- | --- | ---
я | a | Defines a hyperlink
аббр | abbr | Defines an abbreviation
акроним | acronym | Not supported in HTML5. Defines an acronym
адрес | address | Defines contact information for the author/owner of a document
апплет | applet | Not supported in HTML5. Deprecated in HTML 4.01. Defines an embedded applet
зона | area | Defines an area inside an image-map
статья | article | Defines an article
вcтороне | aside | Defines content aside from the page content
аудио | audio | Defines sound content
ж | b | Defines bold text
база | base | Specifies the base URL/target for all relative URLs in a document
базовыйшрифт| basefont | Not supported in HTML5. Deprecated in HTML 4.01.Specifies a default color, size, and font for all text in a document
бси | bdi | Isolates a part of text that might be formatted in a different direction from other text outside it
бсп | bdo | Overrides the current text direction
большой | big | Not supported in HTML5. Defines big text
блочнаяцитата | blockquote | Defines a section that is quoted from another source
тело | body | Defines the document's body
рз | br | Defines a single line break
кнопка | button | Defines a clickable button
холст | canvas | Used to draw graphics, on the fly, via scripting (usually JavaScript)
подпись | caption | Defines a table caption
центр | center | Not supported in HTML5. Deprecated in HTML 4.01. Defines centered text
цитата | cite | Defines the title of a work
код | code | Defines a piece of computer code
колонка | col | Specifies column properties for each column within a <colgroup> element
группаколонок | colgroup | Specifies a group of one or more columns in a table for formatting
команда | command | Defines a command button that a user can invoke
наборданных | datalist | Specifies a list of pre-defined options for input controls
оз | dd | Defines a description/value of a term in a description list
удал | del | Defines text that has been deleted from a document
детали | details | Defines additional details that the user can view or hide
опр | dfn | Defines a definition term
диалог | dialog | Defines a dialog box or window
спис | dir | Not supported in HTML5. Deprecated in HTML 4.01. Defines a directory list
див | div | Defines a section in a document
со | dl | Defines a description list
оп | dt | Defines a term/name in a description list
подч | em | Defines emphasized text
вставлен{ный} | embed | Defines a container for an external (non-HTML) application
наборполей | fieldset | Groups related elements in a form
фигзаголовок | figcaption | Defines a caption for a <figure> element
фигура | figure | Specifies self-contained content
шрифт | font | Not supported in HTML5. Deprecated in HTML 4.01. Defines font, color, and size for text
подвал | footer | Defines a footer for a document or section
форма | form | Defines an HTML form for user input
рамка | frame | Not supported in HTML5. Defines a window (a frame) in a frameset
наборрамок | frameset | Not supported in HTML5. Defines a set of frames
з1 | h1 | Defines HTML headings
з2 | h2 | Defines HTML headings
з3 | h3 | Defines HTML headings
з4 | h4 | Defines HTML headings
з5 | h5 | Defines HTML headings
з6 | h6 | Defines HTML headings
голова | head | Defines information about the document
заголовок | header | Defines a header for a document or section
гл | hr | Defines a thematic change in the content
ягтр | html | Defines the root of an HTML document
н | i | Defines a part of text in an alternate voice or mood
айрамка | iframe | Defines an inline frame
крт | img | Defines an image
ввод | input | Defines an input control
вст | ins | Defines a text that has been inserted into a document
клав | kbd | Defines keyboard input
генключа | keygen | Defines a key-pair generator field (for forms)
метка | label | Defines a label for an <input> element
легенда | legend | Defines a caption for a <fieldset> element
эс | li | Defines a list item
ссылка | link | Defines the relationship between a document and an external resource (most used to link to style sheets)
карта | map | Defines a client-side image-map
пометка | mark | Defines marked/highlighted text
меню | menu | Defines a list/menu of commands
мета | meta | Defines metadata about an HTML document
метр | meter | Defines a scalar measurement within a known range (a gauge)
нав | nav | Defines navigation links
нетрамок | noframes | Not supported in HTML5.Defines an alternate content for users that do not support frames
нетскрипта | noscript | Defines an alternate content for users that do not support client-side scripts
объект | object | Defines an embedded object
ус | ol | Defines an ordered list
группаопц | optgroup | Defines a group of related options in a drop-down list
опция | option | Defines an option in a drop-down list
вывод | output | Defines the result of a calculation
п | p | Defines a paragraph
парам | param | Defines a parameter for an object
пре | pre | Defines preformatted text
прогресс | progress | Represents the progress of a task
ц | q | Defines a short quotation
рп | rp | Defines what to show in browsers that do not support ruby annotations
рт | rt | Defines an explanation/pronunciation of characters (for East Asian typography)
руби | ruby | Defines a ruby annotation (for East Asian typography)
з | s | Defines text that is no longer correct
прим | samp | Defines sample output from a computer program
скрипт | script | Defines a client-side script
раздел | section | Defines a section in a document
выбор | select | Defines a drop-down list
маленький | small | Defines smaller text
источник | source | Defines multiple media resources for media elements (<video> and <audio>)
спан | span | Defines a section in a document
зачеркнут | strike | Not supported in HTML5. Deprecated in HTML 4.01. Defines strikethrough text
сильный | strong | Defines important text
стиль | style | Defines style information for a document
под | sub | Defines subscripted text
сводка | summary | Defines a visible heading for a <details> element
над | sup | Defines superscripted text
таблица | table | Defines a table
ттело | tbody | Groups the body content in a table
тя | td | Defines a cell in a table
текстовоеполе | textarea | Defines a multiline input control (text area)
тнога | tfoot | Groups the footer content in a table
тз | th | Defines a header cell in a table
тголова | thead | Groups the header content in a table
время | time | Defines a date/time
название | title | Defines a title for the document
тс | tr | Defines a row in a table
трек | track | Defines text tracks for media elements (<video> and <audio>)
тт | tt | Not supported in HTML5. Defines teletype text
пдч | u | Defines text that should be stylistically different from normal text
нс | ul | Defines an unordered list
пер | var | Defines a variable
видео | video | Defines a video or movie
рзр | wbr | Defines a possible line-break
### Дополнительные теги
Тег | Тег HTML | Описание
--- | --- | ---
шаблон | template | Defines a template
главный | main |
згруппа | hgroup |
### Медия и прочие
Тег | Тег HTML | Описание
--- | --- | ---
@носитель | @media | ???
<file_sep>/tasks/extract-data-from-spec.js
var path = require('path'),
fs = require('fs'),
spec = require('../lib/specParser');
var SPEC_FILE = path.join(__dirname, '../data/spec.json');
var json = JSON.stringify(spec(), null, 4);
fs.writeFileSync(SPEC_FILE, json);
<file_sep>/spec/4.2-units.md
### Единицы измерения и цвета
Единица | Единица в CSS | Описание
--- | --- | ---
рм | em | font size of the element
вх | ex | x-height of the element's font
чх | ch | width of the "0" (ZERO, U+0030) glyph in the element's font
крм | rem | font size of the root element
пш | vw | 1% of viewport's width
пв | vh | 1% viewport's height
пмин | vmin | 1% of viewport's smaller dimension
пмакс | vmax | 1% of viewport's larger dimension
см | cm | centimeters
мм | mm | millimeters
дю | in | nches; 1in is equal to 2.54cm
тч | px | pixels; 1px is equal to 1/96th of 1in
пои | pt | oints; 1pt is equal to 1/72nd of 1in
пик | pc | picas; 1pc is equal to 12pt
градус | deg | Degrees. There are 360 degrees in a full circle.
град | grad | Gradians, also known as "gons" or "grades". There are 400 gradians in a full circle.
рад | rad | Radians. There are 2π radians in a full circle.
пов | turn | Turns. There is 1 turn in a full circle.
сек | s | Seconds.
мсек | ms | Milliseconds. There are 1000 milliseconds in a second.
твд | dpi | dots per inch
твсм | dpcm | dots per centimeter
твтч | dppx | dots per `px` unit
Гц | Hz| It represents the number of occurrences per second.
кГц | kHz| A kiloHertz is 1000 Hertz.
<file_sep>/spec/4-vals.md
## Значение свойств
Поддерживаются все CSS значения свойств в том числе вычисляемые.
### Константные и вычисляемые свойства
Значение | Значение в CSS
--- | ---
выше | above
абсолютн{ый,ая,ое} | absolute
после | after
псевдоним | alias
вс{е,ё} | all
свободный-скролл | all-scroll
все{е,ё}-капителью | all-small-caps
позволить-конец | allow-end
алфавитн{ый,ая,ое} | alphabetic
альтернативн{ый,ая,ое} | alternate
альтернативн{ый,ая,ое}-инвертированн | alternate-reverse
всегда | always
армянск{ий,ая,ое} | armenian
авто | auto
избегать | avoid
избегать-колонку | avoid-column
избегать-страницу | avoid-page
назад | backwards
баланс | balance
базоваялиния | baseline
перед | before
ниже | below
отменить-биди | bidi-override
мигать | blink
блок{,ировать} | block
жирный | bold
более-жирный | bolder
по-границе | border-box
оба | both
нижний | bottom
перенос-всего | break-all
перенос-слов | break-word
капитализировать | capitalize
ячейка | cell
центр | center
круг | circle
обрезать | clip
клонировать | clone
закрывающие-кавычки | close-quote
ресайз-колонки | col-resize
схлопнуть | collapse
колонка | column
инвертировать-колонки | column-reverse
насыщенный | condensed
содерж{ать,ит} | contain
по-содержимому | content-box
контекстное-меню | context-menu
копи{я,ровать} | copy
покрыть | cover
перекрестие | crosshair
пунктирная | dashed
десятичный | decimal
десятичный-ведущий-ноль | decimal-leading-zero
обычный | default
потомки | descendants
диск | disc
распростран{ять,ить} | distribute
точка | dot
точечный | dotted
двойной | double
двойной-круг | double-circle
в-ресайз | e-resize
легкость | ease
легкость-в | ease-in
легкость-в-из | ease-in-out
легкость-из | ease-out
края | edges
эллипсис | ellipsis
вставлен{ный} | embed
конец | end
зв-ресайз | ew-resize
расширен | expanded
экстра-конденсирован | extra-condensed
экстра-расширен | extra-expanded
заполнение | fill
заполнен | filled
первый | first
фиксирован | fixed
плоский | flat
флекс | flex
флекс-конец | flex-end
флекс-старт | flex-start
форсированный-конец | force-end
вперед | forwards
полной-ширины | full-width
грузинский | georgian
канавка | groove
помощь | help
скрытый | hidden
спрятать | hide
горизонтальный | horizontal
горизонтальный-тб | horizontal-tb
иконка | icon
бесконечн{ый,ая,ое} | infinite
наследовать | inherit
начальн{ый,ая,ое} | initial
чернила | ink
строчный | inline
строчный-блок | inline-block
строчный-флекс | inline-flex
строчная-таблица | inline-table
вставка | inset
внутри | inside
между-кластером | inter-cluster
между-иероглифом | inter-ideograph
между-словом | inter-word
инвертированн{ый,ая,ое} | invert
курсив{,ный} | italic
выключитьстроку | justify
кашида | kashida
сохранить-все | keep-all
большое | large
больше | larger
последн{ий,яя,ее} | last
{слева,левый} | left
легче | lighter
зачеркнуть | line-through
линейн{ый,ая,ое} | linear
последний-пункт | list-item
локальн{ый,ая,ое} | local
свободн{ый,ая,ое} | loose
нижний-буквенный | lower-alpha
нижний-греческий | lower-greek
нижний-латинский | lower-latin
нижний-романский | lower-roman
нижний-регистр | lowercase
лнп | ltr
ручной | manual
соответствует-родителю | match-parent
средн{ий,яя,ее} | medium
посередине | middle
смешенный-справа | mixed-right
двигать | move
с-ресайз | n-resize
св-ресайз | ne-resize
свюз-ресайз | nesw-resize
не-закрывать-кавычки | no-close-quote
не-сбрасывать | no-drop
не-открывать-кавычки | no-open-quote
не-повторять | no-repeat
{нет,ничего,нету} | none
нормальный | normal
не-разрешен | not-allowed
безобтекания | nowrap
сю-ресайз | ns-resize
сз-ресайз | nw-resize
сзюв-ресайз | nwse-resize
объекты | objects
наклонн{ый,ая,ое} | oblique
открыт| open
открывающие-кавычки | open-quote
начало | outset
снаружи | outside
оверлайн | overline
по-отбивке | padding-box
страница | page
пауза | paused
указатель | pointer
пре | pre
пре-линия | pre-line
пре-обертка | pre-wrap
прогресс | progress
относительн{ый,ая,ое} | relative
повтор | repeat
повтор-икс | repeat-x
повтор-игрек | repeat-y
обратн{ый,ая,ое} | reverse
хребет | ridge
{справа,превый} | right
кругл{ый,ая,ое} | round
ряд | row
ряд-ресайз | row-resize
обратный-ряд | row-reverse
пнл | rtl
бегущ{ий,яя,ее} | running
ю-ресайз | s-resize
{уменьшить,уменьшать} | scale-down
скролл | scroll
юв-ресайз | se-resize
полу-конденсирован | semi-condensed
полу-расширен | semi-expanded
отдельн{ый,ая,ое} | separate
кунжут | sesame
показать | show
боком | sideways
боком-лева | sideways-left
боком-права | sideways-right
нарезать | slice
маленький | small
капитель | small-caps
меньше | smaller
сплошной | solid
пробел | space
пробел-вокруг | space-around
пробел-между | space-between
пробелы | spaces
квадрат | square
старт | start
статический | static
шаг-конец | step-end
шаг-старт | step-start
растягивать | stretch
строг{ий,ая,ое} | strict
стиль | style
суб | sub
над | super
юз-ресайз | sw-resize
таблица | table
заголовок-таблицы | table-caption
ячейка-таблицы | table-cell
колонка-таблицы | table-column
группа-колонок-талицы | table-column-group
группа-футера-таблицы | table-footer-group
группа-заголовка-таблицы | table-header-group
ряд-таблицы | table-row
группа-ряда-таблицы | table-row-group
текст | text
текст-внизу | text-bottom
текст-наверху | text-top
толстый | thick
тонкий | thin
начертание-титров | titling-caps
верх | top
прозрачн{ый,ая,ое} | transparent
треугольн{ый,ая,ое} | triangle
сверх-конденсирован | ultra-condensed
сверх-расширен | ultra-expanded
под | under
подчеркнут | underline
однорегистров{ый,ая,ое} | unicase
отключенн{ый,ая,ое} | unset
верхний-буквенный | upper-alpha
верхний-латинский | upper-latin
верхний-романский | upper-roman
верхний-регистр | uppercase
вертикально | upright
использовать-ориентуцию-знака | use-glyph-orientation
вертикальн{ый,ая,ое} | vertical
вертикальный-лп | vertical-lr
вертикальный-пл | vertical-rl
вертикальный-текст | vertical-text
видимый | visible
з-ресайз | w-resize
ждать | wait
волнист{ый,ая,ое} | wavy
вес | weight
обернуть | wrap
обернуть-обратный | wrap-reverse
оч-большой | x-large
оч-маленький | x-small
очоч-большой | xx-large
очоч-большой | xx-small
призумить | zoom-in
отзумить | zoom-out
!важно | !important
цвет-кольца-фокусировки | focus-ring-color
касание | touch
### Значения псевдоселекторов
Значение | Значение в CSS
--- | ---
нечетный | odd
четный | even
### Всякое ололо
Значение | Значение в CSS
--- | ---
идпрог | progid
ДХТрансформацияКартинки | DXImageTransform
Майкрософт | Microsoft
<file_sep>/spec/4.3-colors.md
### Цвета
Единица | Единица в CSS | Описание
--- | --- | ---
марон | maroon | #800000
красн{ый,ая,ое} | red | #ff0000
оранжев{ый,ая,ое} | orange | #ffA500
желт{ый,ая,ое} | yellow | #ffff00
оливков{ый,ая,ое} | olive | #808000
пурпурн{ый,ая,ое} | purple | #800080
фуксия | fuchsia | #ff00ff
бел{ый,ая,ое} | white | #ffffff
лимонн{ый,ая,ое} | lime | #00ff00
зелён{ый,ая,ое} | green | #008000
темносин{ий,яя,ее} | navy | #000080
син{ий,яя,ее} | blue | #0000ff
водян{ой,ая,ое} | aqua | #00ffff
бирюзов{ый,ая,ое} | teal | #008080
черн{ый,ая,ое} | black | #000000
серебрян{ый,ая,ое} | silver | #c0c0c0
сер{ый,ая,ое} | gray | #80808
Цвет, представленный в виде `№123456` и `№123` соответствуют `#123456` и `#123`.
<file_sep>/index.js
module.exports = process.env._1CSS_COVERAGE ?
require('./lib-cov') :
require('./lib');
<file_sep>/spec/4.1-function-vals.md
### Вычисляемые значение
Значение | Значение в CSS
--- | ---
кзс() | rgb()
вычс() | calc()
кзсп() | rgba()
урл() | url()
аттр() | attr()
остановка-цвета() | color-stop()
от() | from()
до() | to()
градиент() | gradient()
линейный-градиент() | linear-gradient()
радиальный-градиент() | radial-gradient()
повторяющийся-линейный-градиент() | repeating-linear-gradient()
повторяющийся-радиальный-градиент() | repeating-radial-gradient()
кубический-безье() | cubic-bezier()
шаги() | steps()
матрица() | matrix()
матрица3д() | matrix3d()
перспектива() | perspective()
поворот() | rotate()
поворот3д() | rotate3d()
поворотИкс() | rotateX()
поворотИгрек() | rotateY()
поворотЗед() | rotateZ()
масштаб() | scale()
масштаб3д() | scale3d()
масштабИкс() | scaleX()
масштабИгрек() | scaleY()
масштабЗед() | scaleZ()
наклон() | skew()
наклонИкс() | skewX()
наклонИгрек() | skewY()
смещение() | translate()
смещение3д() | translate3d()
смещениеИкс() | translateX()
смещениеИгрек() | translateY()
смещениеЗэд() | translateZ()
блюр() | blur()
яркость() | brightness()
контраст() | contrast()
отбрасывание-тени() | drop-shadow()
чернобелый() | grayscale()
поворот-оттенка() | hue-rotate()
инвертировать() | invert()
непрозрачность() | opacity()
насыщать() | saturate()
сепия() | sepia()
альфаканал() | alpha()
формат() | format()
<file_sep>/lib/specParser.js
var path = require('path'),
fs = require('fs'),
expandProperty = require('./propertyExpander'),
_ = require('lodash'),
lexer = require('marked').lexer;
var SPEC_DIR = path.join(__dirname, '../spec');
var reAllBadCharacters = /\(|\)|:|!|@/g;
var rules = [
{
// html tag selector
// eg html.div
before: '\\b',
after: '\\b',
prefixed: false,
content: [
path.join(SPEC_DIR, '2-selector.md')
]
},
{
// pseudo selector
// :after
before: ':',
after: '\\b',
prefixed: true,
content: [
path.join(SPEC_DIR, '2.1-pseudo-selector.md')
]
},
{
// property
// font:
before: '\\b',
after: '\\s*:',
prefixed: true,
content: [
path.join(SPEC_DIR, '3-props.md')
]
},
{
// value
// red
before: '(?:\\b)?',
after: '\\b',
prefixed: true,
content: [
path.join(SPEC_DIR, '4-vals.md'),
path.join(SPEC_DIR, '4.3-colors.md'),
path.join(SPEC_DIR, '4.4-fonts.md')
]
},
{
// function-vals
// attr()
before: '\\b',
after: '\\(',
prefixed: false,
content: [
path.join(SPEC_DIR, '4.1-function-vals.md')
]
},
{
// units
// 1px
before: '[0-9]?\\.?[0-9]+',
after: '\\b',
prefixed: false,
content: [
path.join(SPEC_DIR, '4.2-units.md')
]
}
];
/**
*
* @param {String} markdownText
* @returns {Object.<String, (Array|String)>}
*/
function extractValuesFrom(markdownText) {
var values = {};
var jsonMl = lexer(markdownText);
jsonMl.forEach(function (block) {
if (block.type !== 'table') {
return;
}
block.cells.forEach(function (cell) {
var key = cell[1].replace(reAllBadCharacters, ''),
value = cell[0].replace(reAllBadCharacters, '');
if (value === '???') {
return;
}
values[key] = expandProperty(value);
});
});
return values;
}
/**
* @return {Array.<object>}
*/
function parseSpec() {
return rules.map(function (rule) {
var content = rule.content.reduce(function (content, specFile) {
var markdownText = fs.readFileSync(specFile, 'utf8');
return _.extend(content, extractValuesFrom(markdownText));
}, {});
return {
before: rule.before,
after: rule.after,
prefixed: rule.prefixed,
content: content
};
});
}
module.exports = parseSpec;
<file_sep>/spec/2.1-pseudo-selector.md
### Соответствие псевдо селекторов 1CSS псевдоселекторам CSS
Псевдоселектор | Псевдоселектор в CSS | Описание
--- | --- | ---
:ссылка | :link | Selects all unvisited links
:посещен | :visited | Selects all visited links
:активнен | :active | Selects the active link
:завис | :hover | Selects links on mouse over
:фокус | :focus | Selects the input element which has focus
:первая-буква | :first-letter | Selects the first letter of every element
:первая-строка | :first-line | Selects the first line of every element
:первый-ребенок | :first-child | Selects every elements that is the first child of its parent
:до | :before | Insert content before every element
:после | :after | Insert content after every element
:яз() | :lang() | Selects every element with a lang attribute value starting with "it"
:не() | :not() | ???
:корень | :root | ???
:пустой | :empty | ???
:последний-ребенок | :last-child | ???
:вон-тот-ребенок | :nth-child | ???
<file_sep>/README.md
# 1CSS
[]
(https://npmjs.org/package/1css)
[]
(https://travis-ci.org/azproduction/1css)
[]
(https://coveralls.io/r/azproduction/1css)
[]
(https://gemnasium.com/azproduction/1css)
[Live example](http://azproduction.ru/1css/)
Название читается как «один, эс-как-русская-эс, эс-как-доллар, эс-как-доллар».
1CSS это революционно новый язык, который компилируется в CSS, Stylus, SASS, LESS и любые другие форматы препроцессоров CSS.
В отличие от всех существующих препроцессоров CSS для его написания используется кириллица и слова русского языка.
Планируется поддержка склонения слов в значениях свойств (синий, синяя, синее) и правильный порядок слов и склонение в свойствах (тень-текста вместо текст-тень).
## Install
`npm i 1css` for node.js and `<script src="dist/1css.min.js"></script>` for browser
## Usage
Node
```js
var oneCss = require('1css');
oneCss.decode(oneCss.encode('div{font: Arial 1px red;}'));
```
Browser
```js
window['1css'].decode(window['1css'].encode('div{font: Arial 1px red;}'));
```
## Authors
* @azproduction
* @axlerk
* @outring
* @olmokhov_ru
<file_sep>/spec/3-props.md
## Свойства
Поддерживаются все CSS свойства и любые миксины из других препроцессоров. Для каждого из свойств 1CSS есть однозначно одно свойство CSS. Таблицы соответствий преведены ниже.
###Animation Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
@ключевыекадры | @keyframes | Specifies the animation
анимация | animation | A shorthand property for all the animation properties below, except the animation-play-state property
имя-анимации | animation-name | Specifies a name for the @keyframes animation
длительность-анимации | animation-duration | Specifies how many seconds or milliseconds an animation takes to complete one cycle
функция-времени-анимации | animation-timing-function | Specifies the speed curve of the animation
задержка-анимации | animation-delay | Specifies when the animation will start
число-повторов-анимации | animation-iteration-count | Specifies the number of times an animation should be played
направление-анимации | animation-direction | Specifies whether or not the animation should play in reverse on alternate cycles
статус-проигрывания-анимации | animation-play-state | Specifies whether the animation is running or paused
###Background Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
фон | background | Sets all the background properties in one declaration
положение-фона | background-attachment | Sets whether a background image is fixed or scrolls with the rest of the page
цвет-фона | background-color | Sets the background color of an element
изображение-фона | background-image | Sets the background image for an element
позиция-фона | background-position | Sets the starting position of a background image
повтор-фона | background-repeat | Sets how a background image will be repeated
обрезка-фона | background-clip | Specifies the painting area of the background
начало-фона | background-origin | Specifies the positioning area of the background images
размер-фона | background-size | Specifies the size of the background images
###Border and Outline Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
граница | border | Sets all the border properties in one declaration
нижняя-граница | border-bottom | Sets all the bottom border properties in one declaration
цвет-нижней-границы | border-bottom-color | Sets the color of the bottom border
стиль-нижней-границы | border-bottom-style | Sets the style of the bottom border
толщина-нижней-границы | border-bottom-width | Sets the width of the bottom border
цвет-границы | border-color | Sets the color of the four borders
левая-граница | border-left | Sets all the left border properties in one declaration
цвет-левой-границы | border-left-color | Sets the color of the left border
стиль-левой-границы | border-left-style | Sets the style of the left border
толщина-левой-границы | border-left-width | Sets the width of the left border
правая-граница | border-right | Sets all the right border properties in one declaration
цвет-правой-границы | border-right-color | Sets the color of the right border
стиль-правой-границы | border-right-style | Sets the style of the right border
толщина-правой-границы | border-right-width | Sets the width of the right border
стиль-границы | border-style | Sets the style of the four borders
верхняя-граница | border-top | Sets all the top border properties in one declaration
цвет-верхней-границы | border-top-color | Sets the color of the top border
стиль-верхней-границы | border-top-style | Sets the style of the top border
толщина-верхней-границы | border-top-width | Sets the width of the top border
толщина-границы | border-width | Sets the width of the four borders
контур | outline | Sets all the outline properties in one declaration
цвет-контура | outline-color | Sets the color of an outline
стиль-контура | outline-style | Sets the style of an outline
толщина-контура | outline-width | Sets the width of an outline
радиус-нижней-левой-рамки | border-bottom-left-radius | Defines the shape of the border of the bottom-left corner
радиус-нижней-правой-рамки | border-bottom-right-radius | Defines the shape of the border of the bottom-right corner
изображение-рамки | border-image | A shorthand property for setting all the border-image-* properties
начало-изображения-рамки | border-image-outset | Specifies the amount by which the border image area extends beyond the border box
повтор-изображения-рамки | border-image-repeat | Specifies whether the image-border should be repeated, rounded or stretched
смещение-изображения-рамки | border-image-slice | Specifies the inward offsets of the image-border
источник-изображения-рамки | border-image-source | Specifies an image to be used as a border
толщина-изображения-рамки | border-image-width | Specifies the widths of the image-border
радиус-рамки | border-radius | A shorthand property for setting all the four border-*-radius properties
радиус-верхней-левой-рамки | border-top-left-radius | Defines the shape of the border of the top-left corner
радиус-верхней-правой-рамки | border-top-right-radius | Defines the shape of the border of the top-right corner
разрыв-оформления-блока | box-decoration-break |
тень-блока | box-shadow | Attaches one or more drop-shadows to the box
###Box Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
переполнение-икс | overflow-x | Specifies whether or not to clip the left/right edges of the content, if it overflows the element's content area
переполнение-игрек | overflow-y | Specifies whether or not to clip the top/bottom edges of the content, if it overflows the element's content area
стиль-переполнения | overflow-style | Specifies the preferred scrolling method for elements that overflow
поворот | rotation | Rotates an element around a given point defined by the rotation-point property
точка-поворота | rotation-point | Defines a point as an offset from the top left border edge
###Color Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
цветовой-профиль | color-profile | Permits the specification of a source color profile other than the default
непрозрачность | opacity | Sets the opacity level for an element
намерение-отрисовки | rendering-intent | Permits the specification of a color profile rendering intent other than the default
###Content for Paged Media Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
метка-зякладки | bookmark-label | Specifies the label of the bookmark
уровень-закладки | bookmark-level | Specifies the level of the bookmark
цель-закладки | bookmark-target | Specifies the target of the bookmark link
плавающий-сдвиг | float-offset | Pushes floated elements in the opposite direction of the where they have been floated with float
дефисный-после | hyphenate-after | Specifies the minimum number of characters in a hyphenated word after the hyphenation character
дефисный-до | hyphenate-before | Specifies the minimum number of characters in a hyphenated word before the hyphenation character
дефисный-символ | hyphenate-character | Specifies a string that is shown when a hyphenate-break occurs
дефисный-стрики | hyphenate-lines | Indicates the maximum number of successive hyphenated lines in an element
дифисный-ресурс | hyphenate-resource | Specifies a comma-separated list of external resources that can help the browser determine hyphenation points
дифисы | hyphens | Sets how to split words to improve the layout of paragraphs
разрешение-изображения | image-resolution | Specifies the correct resolution of images
маркировка | marks | Adds crop and/or cross marks to the document
набор-строк | string-set |
###Dimension Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
высота | height | Sets the height of an element
макс-высота | max-height | Sets the maximum height of an element
макс-ширина | max-width | Sets the maximum width of an element
мин-высота | min-height | Sets the minimum height of an element
мин-ширина | min-width | Sets the minimum width of an element
ширина | width | Sets the width of an element
###Flexible Box Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
выравнивание-блока | box-align | Specifies how to align the child elements of a box
направление-блока | box-direction | Specifies in which direction the children of a box are displayed
флекс-блок | box-flex | Specifies whether the children of a box is flexible or inflexible in size
группа-флекс-блока | box-flex-group | Assigns flexible elements to flex groups
линии0блока | box-lines | Specifies whether columns will go onto a new line whenever it runs out of space in the parent box
порядок-группы-бокса | box-ordinal-group | Specifies the display order of the child elements of a box
ориентация-бокса | box-orient | Specifies whether the children of a box should be laid out horizontally or vertically
пак-бокса | box-pack | Specifies the horizontal position in horizontal boxes and the vertical position in vertical boxes
###Font Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
шрифт | font | Sets all the font properties in one declaration
семейство-шрифта | font-family | Specifies the font family for text
размер-шрифта | font-size | Specifies the font size of text
стиль-шрифта | font-style | Specifies the font style for text
вид-шрифта | font-variant | Specifies whether or not a text should be displayed in a small-caps font
вес-шрифта | font-weight | Specifies the weight of a font
@определение-шрифта | @font-face | A rule that allows websites to download and use fonts other than the "web-safe" fonts
подгонка-размера-шрифта | font-size-adjust | Preserves the readability of text when font fallback occurs
разрядка-шрифта | font-stretch | Selects a normal, condensed, or expanded face from a font family
###Generated Content Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
содержимое | content | Used with the :before and :after pseudo-elements, to insert generated content
инкремент-счетчика | counter-increment | Increments one or more counters
сброс-счетчика | counter-reset | Creates or resets one or more counters
кавычки | quotes | Sets the type of quotation marks for embedded quotations
обрезка | crop | Allows a replaced element to be just a rectangular area of an object, instead of the whole object
сдвинуть-на | move-to | Causes an element to be removed from the flow and reinserted at a later point in the document
политика-страницы | page-policy | Determines which page-based occurance of a given element is applied to a counter or string value
###Grid Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
колонки-сетки | grid-columns | Specifies the width of each column in a grid
ряды-сетки | grid-rows | Specifies the height of each column in a grid
###Hyperlink Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
цель | target | A shorthand property for setting the target-name, target-new, and target-position properties
имя-цели | target-name | Specifies where to open links (target destination)
новая-цель | target-new | Specifies whether new destination links should open in a new window or in a new tab of an existing window
позиция-цели | target-position | Specifies where new destination links should be placed
###Linebox Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
подгонка-выравнивания | alignment-adjust | Allows more precise alignment of elements
выравнивание-базовой | alignment-baseline | Specifies how an inline-level element is aligned with respect to its parent
сдвиг-базовой | baseline-shift | Allows repositioning of the dominant-baseline relative to the dominant-baseline
домининация-базовой | dominant-baseline | Specifies a scaled-baseline-table
??? | drop-initial-after-adjust | Sets the alignment point of the drop initial for the primary connection point
??? | drop-initial-after-align | Sets which alignment line within the initial line box is used at the primary connection point with the initial letter box
??? | drop-initial-before-adjust | Sets the alignment point of the drop initial for the secondary connection point
??? | drop-initial-before-align | Sets which alignment line within the initial line box is used at the secondary connection point with the initial letter box
??? | drop-initial-size | Controls the partial sinking of the initial letter
??? | drop-initial-value | Activates a drop-initial effect
выравнивание-строчного-блока | inline-box-align | Sets which line of a multi-line inline block align with the previous and next inline elements within a line
??? | line-stacking | A shorthand property for setting the line-stacking-strategy, line-stacking-ruby, and line-stacking-shift properties
??? | line-stacking-ruby | Sets the line stacking method for block elements containing ruby annotation elements
??? | line-stacking-shift | Sets the line stacking method for block elements containing elements with base-shift
??? | line-stacking-strategy | Sets the line stacking strategy for stacked line boxes within a containing block element
высота-текста | text-height | Sets the block-progression dimension of the text content area of an inline box
###List Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
стиль-списка | list-style | Sets all the properties for a list in one declaration
изображение-стиля-списка | list-style-image | Specifies an image as the list-item marker
позиция-стиля-списка | list-style-position | Specifies if the list-item markers should appear inside or outside the content flow
тип-стиля-списка | list-style-type | Specifies the type of list-item marker
###Margin Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
поле | margin | Sets all the margin properties in one declaration
поле-снизу | margin-bottom | Sets the bottom margin of an element
поле-слева | margin-left | Sets the left margin of an element
поле-справа | margin-right | Sets the right margin of an element
поле-сверху | margin-top | Sets the top margin of an element
###Marquee Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
направление-шатра | marquee-direction | Sets the direction of the moving content
количество-повторов-шатра | marquee-play-count | Sets how many times the content move
скорость-шатра | marquee-speed | Sets how fast the content scrolls
стиль-шатра | marquee-style | Sets the style of the moving content
###Multi-column Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
количество-колонок | column-count | Specifies the number of columns an element should be divided into
заполнение-колонок | column-fill | Specifies how to fill columns
зазор-колонок | column-gap | Specifies the gap between the columns
направляющая-колонок | column-rule | A shorthand property for setting all the column-rule-* properties
цвет-направляющей-колонок | column-rule-color | Specifies the color of the rule between columns
стиль-направляющей-колонок | column-rule-style | Specifies the style of the rule between columns
ширина-направляющей-колонок | column-rule-width | Specifies the width of the rule between columns
охват-колонок | column-span | Specifies how many columns an element should span across
ширина-колонок | column-width | Specifies the width of the columns
колонки | columns | A shorthand property for setting column-width and column-count
###Padding Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
отбивка | padding | Sets all the padding properties in one declaration
отбивка-снизу | padding-bottom | Sets the bottom padding of an element
отбивка-слева | padding-left | Sets the left padding of an element
отбивка-справа | padding-right | Sets the right padding of an element
отбивка-сверху | padding-top | Sets the top padding of an element
###Paged Media Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
??? | fit | Gives a hint for how to scale a replaced element if neither its width nor its height property is auto
??? | fit-position | Determines the alignment of the object inside the box
ориентация-изображения | image-orientation | Specifies a rotation in the right or clockwise direction that a user agent applies to an image
страница | page | Specifies a particular type of page where an element SHOULD be displayed
размер | size | Specifies the size and orientation of the containing box for page content
###Positioning Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
снизу | bottom | Specifies the bottom position of a positioned element
очистить | clear | Specifies which sides of an element where other floating elements are not allowed
обрезать | clip | Clips an absolutely positioned element
курсор | cursor | Specifies the type of cursor to be displayed
отображение | display | Specifies how a certain HTML element should be displayed
обтекание | float | Specifies whether or not a box should float
слева | left | Specifies the left position of a positioned element
переполнение | overflow | Specifies what happens if content overflows an element's box
положение | position | Specifies the type of positioning method used for an element (static, relative, absolute or fixed)
справа | right | Specifies the right position of a positioned element
сверху | top | Specifies the top position of a positioned element
видимость | visibility | Specifies whether or not an element is visible
зед-индекс | z-index | Sets the stack order of a positioned element
###Print Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
сироты | orphans | Sets the minimum number of lines that must be left at the bottom of a page when a page break occurs inside an element
разрыв-страницы-после | page-break-after | Sets the page-breaking behavior after an element
разрыв-страницы-до | page-break-before | Sets the page-breaking behavior before an element
разрыв-страницы-внутри | page-break-inside | Sets the page-breaking behavior inside an element
вдовы | widows | Sets the minimum number of lines that must be left at the top of a page when a page break occurs inside an element
###Ruby Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
??? | ruby-align | Controls the text alignment of the ruby text and ruby base contents relative to each other
??? | ruby-overhang | Determines whether, and on which side, ruby text is allowed to partially overhang any adjacent text in addition to its own base, when the ruby text is wider than the ruby base
??? | ruby-position | Controls the position of the ruby text with respect to its base
??? | ruby-span | Controls the spanning behavior of annotation elements
###Speech Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
??? | mark | A shorthand property for setting the mark-before and mark-after properties
??? | mark-after | Allows named markers to be attached to the audio stream
??? | mark-before | Allows named markers to be attached to the audio stream
??? | phonemes | Specifies a phonetic pronunciation for the text contained by the corresponding element
??? | rest | A shorthand property for setting the rest-before and rest-after properties
??? | rest-after | Specifies a rest or prosodic boundary to be observed after speaking an element's content
??? | rest-before | Specifies a rest or prosodic boundary to be observed before speaking an element's content
??? | voice-balance | Specifies the balance between left and right channels
??? | voice-duration | Specifies how long it should take to render the selected element's content
??? | voice-pitch | Specifies the average pitch (a frequency) of the speaking voice
??? | voice-pitch-range | Specifies variation in average pitch
??? | voice-rate | Controls the speaking rate
??? | voice-stress | Indicates the strength of emphasis to be applied
??? | voice-volume | Refers to the amplitude of the waveform output by the speech synthesises
###Table Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
схлапывание-границ | border-collapse | Specifies whether or not table borders should be collapsed
расстояние-границ | border-spacing | Specifies the distance between the borders of adjacent cells
сторона-подписи | caption-side | Specifies the placement of a table caption
пустые-ячейки | empty-cells | Specifies whether or not to display borders and background on empty cells in a table
макет-таблицы | table-layout | Sets the layout algorithm to be used for a table
###Text Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
цвет | color | Sets the color of text
направние | direction | Specifies the text direction/writing direction
мужбуквенный-пробел | letter-spacing | Increases or decreases the space between characters in a text
высота-строки | line-height | Sets the line height
выравнивание-текста | text-align | Specifies the horizontal alignment of text
оформление-текста | text-decoration | Specifies the decoration added to text
отступ-текста | text-indent | Specifies the indentation of the first line in a text-block
трансформация-текста | text-transform | Controls the capitalization of text
уникод-биди | unicode-bidi | Used together with the direction property to set or return whether the text should be overridden to support multiple languages in the same document
вертикальное-выравнивание | vertical-align | Sets the vertical alignment of an element
пробелы | white-space | Specifies how white-space inside an element is handled
межсловный-пробел | word-spacing | Increases or decreases the space between words in a text
висячая-пунктуация | hanging-punctuation | Specifies whether a punctuation character may be placed outside the line box
обрезка-пунктуации | punctuation-trim | Specifies whether a punctuation character should be trimmed
выравнивание-последней-строки | text-align-last | Describes how the last line of a block or a line right before a forced line break is aligned when text-align is "justify"
выключка-текста | text-justify | Specifies the justification method used when text-align is "justify"
контур-текста | text-outline | Specifies a text outline
переполнение-текста | text-overflow | Specifies what should happen when text overflows the containing element
тень-текста | text-shadow | Adds shadow to text
подгонка-размера-текста | text-size-adjust | ???
обертка-текста | text-wrap | Specifies line breaking rules for text
разрыв-слова | word-break | Specifies line breaking rules for non-CJK scripts
обертка-слова | word-wrap | Allows long, unbreakable words to be broken and wrap to the next line
###2D/3D Transform Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
трансформация | transform | Applies a 2D or 3D transformation to an element
точка-трансформации | transform-origin | Allows you to change the position on transformed elements
стиль-трансформации | transform-style | Specifies how nested elements are rendered in 3D space
перспектива | perspective | Specifies the perspective on how 3D elements are viewed
точка-перспективы | perspective-origin | Specifies the bottom position of 3D elements
видимость-задника | backface-visibility | Defines whether or not an element should be visible when not facing the screen
###Transition Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
переход | transition | A shorthand property for setting the four transition properties
свойство-перехода | transition-property | Specifies the name of the CSS property the transition effect is for
длительность-перехода | transition-duration | Specifies how many seconds or milliseconds a transition effect takes to complete
функция-вренеми-перехода | transition-timing-function | Specifies the speed curve of the transition effect
задержка-перехода | transition-delay | Specifies when the transition effect will start
###User-interface Properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
представление | appearance | Allows you to make an element look like a standard user interface element
калибровка-блока | box-sizing | Allows you to define certain elements to fit an area in a certain way
иконка | icon | Provides the author the ability to style an element with an iconic equivalent
нав-вниз | nav-down | Specifies where to navigate when using the arrow-down navigation key
нав-индекс | nav-index | Specifies the tabbing order for an element
нав-влево | nav-left | Specifies where to navigate when using the arrow-left navigation key
нав-вправо | nav-right | Specifies where to navigate when using the arrow-right navigation key
нав-вверх | nav-up | Specifies where to navigate when using the arrow-up navigation key
смещение-контура | outline-offset | Offsets an outline, and draws it beyond the border edge
ресайз | resize | Specifies whether or not an element is resizable by the user
###Extra properties
Свойство | Свойство в CSS | Описание
--- | --- | ---
зум | zoom | ???
фильтр | filter | ???
выделение-пользователем | user-select | ???
сглаживание-шрифта | font-smoothing | ???
осх-сглаживание-шрифта | osx-font-smoothing | ???
переполнение-прокрутки | overflow-scrolling | ???
ист | src | ???
<file_sep>/spec/4.4-fonts.md
### Ключевые слова шрифтов
Единица | Единица в CSS | Описание
--- | --- | ---
моношитрый | monospace
c-засечками | serif
без-засечек | sans-serif
фантазийный | fantasy
рукописный | cursive
| f76962a92911fa3fcb91bf49e877bccfb6216960 | [
"Markdown",
"JavaScript"
]
| 12 | Markdown | azproduction/1css | 5d35406c4f58a44bb8e6265d70bad0a16ff15f5f | 050a3407859a8bb461967f0acc29ed3d6ca05454 |
refs/heads/master | <file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
vec=np.zeros((7,20))
ii=0
for x in [27,28,29,30,31,32,33]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/f%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
xs=np.arange(-0.75,4.25,0.25)
plt.xlabel('bias current I')
plt.ylabel('Fano factor')
#plt.yscale('log')
plt.xlim(0.5, 1.5)
plt.ylim(400, 700)
plt.plot(xs,vec[0,:],label='D=2.7')
plt.plot(xs,vec[1,:],label='D=2.8')
plt.plot(xs,vec[2,:],label='D=2.9')
plt.plot(xs,vec[3,:],label='D=3')
plt.plot(xs,vec[4,:],label='D=3.1')
plt.plot(xs,vec[5,:],label='D=3.2')
plt.plot(xs,vec[6,:],label='D=3.3')
plt.legend()
plt.savefig('fneurpmaxclose.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
from scipy.optimize import curve_fit
matplotlib.rcParams.update({'font.size': 14}) #18
def func(x, a, b):
return a * np.exp(-b * x)
def r(r0,U,D):
return r0*np.exp(-U/D)
def snr(r0p,r0m,up,um,ups,ums,D,av,v0):
return (r(r0m,um,D)*(r(r0p,up,D)+r(r0m,um,D))/(v0**2*r(r0p,up,D)))*(((ups-ums)*r(r0p,up,D)*v0)/(D*(r(r0p,up,D)+r(r0m,um,D)))+av)**2
def rprime(r0,r0s,Us,D):
return (r0s/r0-Us/D)
def snrcor(r0p,r0m,up,um,ups,ums,D,av,v0,r0ps,r0ms):
return ((av*r(r0m,um,D)*(r(r0m,um,D)+r(r0p,up,D))+v0*(rprime(r0m,r0ms,ums,D)-rprime(r0p,r0ps,ups,D))*r(r0p,up,D)*r(r0m,um,D))**2)/((r(r0p,up,D)+r(r0m,um,D))*v0**2*r(r0p,up,D)*r(r0m,um,D))
date2='realanhopf11flog'
date3='realanhopf19flog'
ivalues=14
D1=[20,25,30,35]
D2=[]
D3=[]
Dvar=[]
D=D1+D2+D3+Dvar
l=len(D1)
Da=np.array(D)
#btoeq=np.zeros((l,ivalues))
#eqtob=np.zeros((l,ivalues))
#params=np.zeros((4,ivalues))
#for k2 in range(0,ivalues):
# x=[]
# ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/rate%s%d.txt' %(date3+date2,k2),'r')
# for k4 in ratefile:
# row=k4.split()
# x.append(float(row[0]))
# ax=np.array(x)
# for k in range(0,l):
# btoeq[k][k2]=1/ax[k]
# eqtob[k][k2]=1/ax[k+l]
#xs=np.zeros(l)
#for b in range(0,l):
# xs[b]=100/Da[b]
#for k2 in range(0,ivalues):
# popt,pcov = curve_fit(func, xs, btoeq[:,k2])
# params[0][k2]=popt[0]
# params[1][k2]=popt[1]
# popt,pcov = curve_fit(func, xs, eqtob[:,k2])
# params[2][k2]=popt[0]
# params[3][k2]=popt[1]
#rbte=np.mean(params[0,:])
#retb=np.mean(params[2,:])
rbtoeq=np.zeros(ivalues)
ubtoeq=np.zeros(ivalues)
reqtob=np.zeros(ivalues)
ueqtob=np.zeros(ivalues)
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/param%s%d.txt' %(date3+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
rbtoeq[k2]=x[0]
ubtoeq[k2]=x[1]
reqtob[k2]=x[2]
ueqtob[k2]=x[3]
ups=np.zeros(ivalues-2)
ums=np.zeros(ivalues-2)
r0ms=np.zeros(ivalues-2)
r0ps=np.zeros(ivalues-2)
istart=4
istep=0.25
xnew=np.arange(172+istart,172+istart+ivalues)*istep
for k3 in range(0,ivalues-2):
ups[k3]=(ubtoeq[k3+2]-ubtoeq[k3])/(2*istep)
ums[k3]=(ueqtob[k3+2]-ueqtob[k3])/(2*istep)
r0ps[k3]=(rbtoeq[k3+2]-rbtoeq[k3])/(2*istep)
r0ms[k3]=(reqtob[k3+2]-reqtob[k3])/(2*istep)
N0=50000000
dt0=0.005
T0=N0*dt0
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countanhopf.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
cola=np.array(col)/T0
colxa=np.array(colx)
lenx=len(colxa)
ratenew=np.zeros(ivalues)
dratenew=np.zeros(ivalues)
for ls in range(0,ivalues):
x=xnew[ls]
for m in range(0,lenx-1):
b=colxa[m+1]
a=colxa[m]
if x<=b and x>a:
ratenew[ls]=cola[m]+((x-a)/(b-a))*(cola[m+1]-cola[m])
dratenew[ls]=(cola[m+1]-cola[m])/(b-a)
break
ll=0
lm=5
SNR=np.zeros((lm,ivalues))
snrfile=open('snrealanhopffile3.txt','r')
for s in snrfile:
row=s.split()
for t in range(istart-1-1,istart+ivalues-1-1):
SNR[ll][t-istart+1+1]=float(row[t])
ll=ll+1
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Signal-to-noise ratio SNR')
Dtot=np.array([10,15,20,25,30])
#Dtot=np.array([1,2,3,4,5])
l2=len(Dtot)
t=np.arange(-18,-8,0.1)
#xs=np.arange(-21.25+istart,-21.25+istart+ivalues)*0.8
#xs=np.arange(-20+istart,-20+istart+ivalues)*0.6
plt.yscale('log')
#plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
plt.ylim(10**(-6),10**(-2))
colorv=['r','#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'] # 6 colors
#colorv=['y','g','b'] # 3 colors
#colorv=['y','c','g','k','b'] # 5 colors
#for n in range(1,2):
# plt.plot(xnew[1:ivalues-1],SNR[n,1:ivalues-1],'o',label='D=%.2f' %(Dtot[n]*0.01))
#plt.plot(xnew[1:ivalues-1],snrcor(rbtoeq[1:ivalues-1],reqtob[1:ivalues-1],ubtoeq[1:ivalues-1],ueqtob[1:ivalues-1],ups,ums,Dtot[n]*0.01,dratenew[1:ivalues-1],ratenew[1:ivalues-1],r0ps,r0ms)/8,colorv[n])
#plt.plot(xnew[1:ivalues-1],snrcor(rbtoeq[1:ivalues-1],reqtob[1:ivalues-1],ubtoeq[1:ivalues-1],ueqtob[1:ivalues-1],ups,ums,10*0.01,dratenew[1:ivalues-1],ratenew[1:ivalues-1],r0ps,r0ms)/8,'purple',label='D=0.1')
for n in range(1,l2):
plt.plot(xnew[1:ivalues-1],SNR[n,1:ivalues-1],label='D=%.2f' %(Dtot[n]*0.01))
#plt.plot(xnew[1:ivalues-1],snrcor(rbtoeq[1:ivalues-1],reqtob[1:ivalues-1],ubtoeq[1:ivalues-1],ueqtob[1:ivalues-1],ups,ums,Dtot[n]*0.01,dratenew[1:ivalues-1],ratenew[1:ivalues-1],r0ps,r0ms)/8,colorv[n],label='D=%.2f' %(Dtot[n]*0.01))#plt.plot(xnew,ratenew,colorv[n])
#for n in range(1,2):
# plt.plot(xnew[1:ivalues-3],SNR[n,1:ivalues-3],'o',label='D=%.2f*' %(Dtot[n]*0.01))
# plt.plot(xnew[1:ivalues-3],snrcor(rbtoeq[1:ivalues-3],reqtob[1:ivalues-3],ubtoeq[1:ivalues-3],ueqtob[1:ivalues-3],ups[0:ivalues-4],ums[0:ivalues-4],Dtot[n]*0.01,dratenew[1:ivalues-3],ratenew[1:ivalues-3],r0ps[0:ivalues-4],r0ms[0:ivalues-4])/8,colorv[n])
#for n in range(2,l2):
# plt.plot(xnew[1:ivalues-3],SNR[n,1:ivalues-3],'o',label='D=%.2f' %(Dtot[n]*0.01))
#plt.plot(xnew[1:ivalues-3],snrcor(rbtoeq[1:ivalues-3],reqtob[1:ivalues-3],ubtoeq[1:ivalues-3],ueqtob[1:ivalues-3],ups[0:ivalues-4],ums[0:ivalues-4],Dtot[n]*0.01,dratenew[1:ivalues-3],ratenew[1:ivalues-3],r0ps[0:ivalues-4],r0ms[0:ivalues-4])/8,colorv[n])
#plt.plot([46.1, 46.1], [10**(-48), 10**(37)], color='black', linestyle='-',label='$I_{crit}$')
plt.plot([46.1, 46.1], [3*10**(-8),5*10**(-1)], color='black', linestyle='-',label='$I_{crit}$')
plt.plot([45.3, 45.3], [3*10**(-8),5*10**(-1)], color='black', linestyle='--',label='$I_{max}$')
#plt.text(45.4,0.5*10**(-6),'$I_{max}$',fontsize='20')
#plt.text(46.2,0.5*10**(-6),'$I_{crit}$',fontsize='20')
#plt.legend(loc='upper left')
plt.legend()
plt.tight_layout()
#plt.savefig('snrtwostatecompanhopf7mnofit4big.pdf')
#plt.savefig('snranhopfpred2big.pdf')
plt.savefig('snranhopfdef.pdf')
#plt.savefig('snrinzelonly.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b):
return a * np.exp(-b * x)
def func2(x, a, b):
return a * x + b
def func3(x, a):
return a
timefac=1000
matplotlib.rcParams.update({'font.size': 22})
D2=[]
D1=[20,25,30,35]
D3=[]
Dvar=[]
D=D1+D2+D3+Dvar
l1=len(D1)
l2=len(D2)
l3=len(D3)
lvar=len(Dvar)
l=l1+l2+l3+lvar
date2='realanhopf11flog'
date1='realanhopf19flog'
date3='new'+'realfast11jjem2st'
datevar=['new'+'realfast11jjem2','new'+'realfast11jjem2sh','new'+'realfast11jjem2']
istart=4
ivalues=14
params2=np.zeros(6)
params=np.zeros((4,ivalues))
changespertime=np.zeros((l,ivalues))
eqtottime=np.zeros((l,ivalues))
eqreltime=np.zeros((l,ivalues))
btottime=np.zeros((l,ivalues))
breltime=np.zeros((l,ivalues))
cve=np.zeros((l,ivalues))
cvb=np.zeros((l,ivalues))
ii=0
for x in D1:
for y in range(istart,istart+ivalues):
avalues,jrvalues,j2values,state=[],[],[],[]
file=open('/home/richard/outhome/timenew%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
avalues.append(float(row[0]))
jrvalues.append(float(row[1]))
j2values.append(float(row[2]))
state.append(float(row[3]))
j2valuesa=np.array(j2values)
jrvaluesa=np.array(jrvalues)
avaluesa=np.array(avalues)
statea=np.array(state)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date1,x,y),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
Ndiff=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
runs=value[name.index('runs')]
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
inteq[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
intb[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
intb[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
inteq[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
counts=counteq+countb
countsrel=counts/Ndiff
changespertime[ii][y-istart]=countsrel/(repetitions*runs)
plt.figure()
plt.xlabel('interval length [s]')
plt.ylabel('number of intervals')
plt.hist(intbt/timefac, bins=50)
plt.yscale('log')
plt.title("sp. intervals, $I=%.2f$, $D=%.2f$" %(43+0.25*y,x/100), fontsize=22)
plt.tight_layout()
plt.savefig('bdistajrj2%s%d%d.pdf' %(date1,x,y))
plt.figure()
plt.xlabel('interval length [s]')
plt.ylabel('number of intervals')
plt.hist(inteqt/timefac, bins=50)
plt.yscale('log')
plt.title("eq. intervals, $I=%.2f$, $D=%.2f$" %(43+0.25*y,x/100),fontsize=22)
plt.tight_layout()
plt.savefig('eqdistajrj2%s%d%d.pdf' %(date1,x,y))
eqtot=np.sum(inteqt)
btot=np.sum(intbt)
eqrel=eqtot/(eqtot+btot)
brel=btot/(eqtot+btot)
eqtottime[ii][y-istart]=eqtot/counteq
btottime[ii][y-istart]=btot/countb
eqreltime[ii][y-istart]=eqrel
breltime[ii][y-istart]=brel
cve[ii][y-istart]=np.sqrt(np.sum(inteqt**2)/counteq-(np.sum(inteqt)/counteq)**2)/(np.sum(inteqt)/counteq)
cvb[ii][y-istart]=np.sqrt(np.sum(intbt**2)/countb-(np.sum(intbt)/countb)**2)/(np.sum(intbt)/countb)
ii=ii+1
for x in D2:
for y in range(istart,istart+ivalues):
avalues,jrvalues,j2values,state=[],[],[],[]
file=open('/home/richard/outhome/timenew%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
avalues.append(float(row[0]))
jrvalues.append(float(row[1]))
j2values.append(float(row[2]))
state.append(float(row[3]))
j2valuesa=np.array(j2values)
jrvaluesa=np.array(jrvalues)
avaluesa=np.array(avalues)
statea=np.array(state)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date2,x,y),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
Ndiff=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
runs=value[name.index('runs')]
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
inteq[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
intb[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
intb[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
inteq[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
counts=counteq+countb
countsrel=counts/Ndiff
changespertime[ii][y-istart]=countsrel/(repetitions*runs)
plt.figure()
plt.xlabel('interval length [ms]')
plt.ylabel('number of intervals')
plt.hist(intbt, bins=50)
plt.yscale('log')
plt.title("distribution of bursting time intervals")
plt.savefig('bdistajrj2big%s%d%d.pdf' %(date2,x,y))
plt.figure()
plt.xlabel('interval length [ms]')
plt.ylabel('number of intervals')
plt.hist(inteqt, bins=50)
plt.yscale('log')
plt.title("distribution of equilibrium time intervals")
plt.savefig('eqdistajrj2big%s%d%d.pdf' %(date2,x,y))
eqtot=np.sum(inteqt)
btot=np.sum(intbt)
eqrel=eqtot/(eqtot+btot)
brel=btot/(eqtot+btot)
eqtottime[ii][y-istart]=eqtot/counteq
btottime[ii][y-istart]=btot/countb
eqreltime[ii][y-istart]=eqrel
breltime[ii][y-istart]=brel
ii=ii+1
cvbfile = open('cvb%s.txt' % (date1+date2),'w')
for kh in range(0,l):
for kl in range(0,ivalues):
cvbfile.write('%.6f '%cvb[kh][kl])
cvbfile.write('\n')
cvbfile.close()
cvefile = open('cve%s.txt' % (date1+date2),'w')
for kh in range(0,l):
for kl in range(0,ivalues):
cvefile.write('%.6f '%cve[kh][kl])
cvefile.write('\n')
cvefile.close()
#xs=np.arange(0.25,4.25,0.25)
#for k in range(0,20):
# plt.figure()
# xs=[1/2,1/3,1/4,1/5]
# plt.xlabel('inverse noise intensity 1/D')
# plt.ylabel('transition rate')
# plt.yscale('log')
# plt.plot(xs,1/breltime[:,k],label='burst to eq')
#plt.plot(xs,breltime[1,:],label='D=3,burst')
#plt.plot(xs,breltime[2,:],label='D=4,burst')
#plt.plot(xs,eqreltime[3,:],label='D=4,burst')
# plt.plot(xs,1/eqreltime[:,k],label='eq to burst')
#plt.plot(xs,eqreltime[1,:],label='D=3,equilibrium')
#plt.plot(xs,eqreltime[2,:],label='D=4,equilibrium')
#plt.plot(xs,breltime[3,:],label='D=4,equilibrium')
# plt.legend()
# plt.savefig('arrhenius%d.pdf' %(k))
matplotlib.rcParams.update({'font.size': 16})
if l > 1:
for k2 in range(0,ivalues):
plt.figure()
axs = plt.subplot(111)
xs=np.zeros(l)
for xf in range(0,l):
xs[xf]=100/D[xf]
plt.suptitle('I=%.2f$\mu A/cm^2$' %(43+0.25*(k2+istart)))
plt.xlabel('inverse noise intensity 1/D')
plt.ylabel('ln of transition rate ln(r $[s^{-1}]$)')
#plt.yscale('log')
plt.plot(xs,np.log(timefac/btottime[:,k2]),'bo',label='sp. to eq.')
#plt.plot(xs,breltime[1,:],label='D=3,burst')
#plt.plot(xs,breltime[2,:],label='D=4,burst')
#plt.plot(xs,eqreltime[3,:],label='D=4,burst')
plt.plot(xs,np.log(timefac/eqtottime[:,k2]),'ro',label='eq. to sp.')
#plt.plot(xs,eqreltime[1,:],label='D=3,equilibrium')
#plt.plot(xs,eqreltime[2,:],label='D=4,equilibrium')
#plt.plot(xs,breltime[3,:],label='D=4,equilibrium')
popt,pcov = curve_fit(func, xs, 1/btottime[:,k2])
plt.plot(np.array(xs), np.log(timefac*func(np.array(xs), *popt)), 'b-')#,label='fit burst to eq: r_0=%5.3f, U_+=%5.3f' % tuple(popt))
params[0][k2]=popt[0]
params[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, 1/eqtottime[:,k2])
plt.plot(np.array(xs), np.log(timefac*func(np.array(xs), *popt)), 'r-')#,label='fit eq to burst: r_0=%5.3f, U_-=%5.3f' % tuple(popt))
params[2][k2]=popt[0]
params[3][k2]=popt[1]
plt.legend()
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
plt.tight_layout()
plt.savefig('arrheniustotbig%sfit%d.pdf' %(date1+date2,k2))
eqfile = open('param%s%d.txt' % (date1+date2,k2),'w')
for k3 in range(0,4):
eqfile.write('%.6f\n'%params[k3][k2])
eqfile.close()
ratefile = open('rate%s%d.txt' %(date1+date2,k2),'w')
for k4 in range(0,l):
ratefile.write('%.6f\n'%btottime[k4][k2])
for k4 in range(0,l):
ratefile.write('%.6f\n'%eqtottime[k4][k2])
ratefile.close()
plt.figure()
plt.xlabel('inverse noise intensity 1/D')
plt.ylabel('correlation time')
plt.yscale('log')
plt.plot(xs,1/(1/btottime[:,k2]+1/eqtottime[:,k2]))
plt.savefig('cortimebig%s%d.pdf' %(date1+date2,k2))
plt.figure()
#xold=np.arange(-21.25+istart,-21.25+istart+ivalues)*0.8
xold=np.arange(172+istart,172+istart+ivalues)*0.25
plt.xlabel('bias current I')
plt.ylabel('correlation time')
plt.yscale('log')
for n in range(0,l1):
plt.plot(xold,1/(1/btottime[n,:]+1/eqtottime[n,:]),label='D=%f' %(D1[n]*0.01))
for n in range(l1,l1+l2):
plt.plot(xold,1/(1/btottime[n,:]+1/eqtottime[n,:]),label='D=%f' %(D2[n-l1]*0.01))
plt.savefig('altcortimebig%s.pdf' %(date1+date2))
plt.figure()
#xnew=np.arange(-21.25+istart,-21.25+istart+ivalues)*0.8
xnew=np.arange(172+istart,172+istart+ivalues)*0.25
plt.xlabel('bias current')
plt.ylabel('prefactor')
plt.plot(xnew,params[0,:],label='burst to eq')
plt.plot(xnew,params[2,:],label='eq to burst')
plt.legend()
plt.savefig('prefacbig%s.pdf' %(date1+date2))
plt.figure()
plt.xlabel('bias current')
plt.ylabel('potential barrier')
plt.plot(xnew,params[1,:],label='burst to eq')
plt.plot(xnew,params[3,:],label='eq to burst')
plt.plot(xnew,2*params[1,:],label='2x burst to eq')
plt.plot(xnew,2*params[3,:],label='2x eq to burst')
plt.legend()
plt.savefig('barrierbig2%s.pdf' %(date1+date2))
eqfile3 = open('barrierex%s.txt' %(date1+date2),'w')
for k3 in range(0,ivalues):
eqfile3.write('%.6f %.6f %.6f %.6f %.6f\n'%(xnew[k3],params[0][k3],params[1][k3],params[2][k3],params[3][k3]))
eqfile3.close()
popt,pcov = curve_fit(func2, xnew, params[1,:])
params2[0]=popt[0]
params2[1]=popt[1]
popt,pcov = curve_fit(func2, xnew, params[3,:])
params2[3]=popt[0]
params2[4]=popt[1]
popt,pcov = curve_fit(func3, xnew, params[0,:])
params2[2]=popt[0]
popt,pcov = curve_fit(func3, xnew, params[2,:])
params2[5]=popt[0]
eqfile2 = open('parambarrier%s.txt' %(date1+date2),'w')
for k4 in range(0,6):
eqfile2.write('%.6f\n'%params2[k4])
eqfile2.close()
t=np.arange(43,48,0.01)
plt.figure()
plt.xlabel('bias current')
plt.ylabel('potential barrier')
plt.plot(t,func2(t,params2[0],params2[1]),'y')
plt.plot(t,func2(t,params2[3],params2[4]),'y')
plt.plot(t,2*func2(t,params2[0],params2[1]),'y')
plt.plot(t,2*func2(t,params2[3],params2[4]),'y')
plt.plot(xnew,params[1,:],label='burst to eq')
plt.plot(xnew,params[3,:],label='eq to burst')
plt.plot(xnew,2*params[1,:],label='2x burst to eq')
plt.plot(xnew,2*params[3,:],label='2x eq to burst')
plt.legend()
plt.savefig('barrierbigcomp%s.pdf' %(date1+date2))
#plt.figure()
#xs1=np.arange(-0.75,4.25,0.25)
#xs2=np.arange(0.2,4.2,0.2)
#plt.xlabel('bias current')
#plt.ylabel('changes over time steps')
#plt.yscale('log')
#plt.plot(xs2,changespertime[0,:],label='D=1.2')
#plt.plot(xs1,changespertime[1,:],label='D=2')
#plt.plot(xs2,changespertime[2,:],label='D=3')
#plt.plot(xs2,changespertime[3,:],label='D=4')
#plt.plot(xs2,changespertime[4,:],label='D=5')
#plt.legend()
#plt.savefig('changespertime.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
vec=np.zeros((3,20))
vecv=np.zeros((3,20))
ii=0
for x in [30]:
col,colv=[],[]
for y in range(1,19):
file=open('/home/richard/outhome/f1m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
file=open('/home/richard/outhome/g1m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
colv.append(row[1])
for y in range(18,19):
file=open('/home/richard/outhome/f1m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
col.append(row[1])
file=open('/home/richard/outhome/g1m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
colv.append(row[1])
colv.append(row[1])
cola=np.array(col)
colva=np.array(colv)
for z in range(0,20):
vec[ii][z]=cola[z]
vecv[ii][z]=colva[z]
ii=ii+1
for x in [40,50]:
col,colv=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/f1m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
file=open('/home/richard/outhome/g1m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
colv.append(row[1])
cola=np.array(col)
colva=np.array(colv)
for z in range(0,20):
vec[ii][z]=cola[z]
vecv[ii][z]=colva[z]
ii=ii+1
#for x in [40]:
# col=[]
# for y in range(5,21):
# file=open('/home/richard/outhome/g17a%d%d.txt' % (x,y),"r")
# for k in file:
# row=k.split()
# col.append(row[1])
# cola=np.array(col)
# for z in range(0,16):
# vec[ii][z]=cola[z]
# ii=ii+1
xso=np.arange(0.25,4.25,0.25)
xs=np.arange(-0.75,4.25,0.25)
xsh=np.arange(1,4.2,0.2)
plt.xlabel('bias current I')
plt.ylabel('Fano factor')
plt.yscale('log')
#plt.plot(xsh,veco[0,:],label='D=1.2')
plt.plot(xso,100*veco[1,:],label='D=2')
plt.plot(xs,vec[0,:],label='D=3')
plt.plot(xs,vec[1,:],label='D=4')
plt.plot(xs,vec[2,:],label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('fneurp1mcor.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
file=open('/home/richard/mastergit/NetBeansProjects/realstatevar/realstaterinzelnb2.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
axs = plt.subplot(111)
plt.suptitle('$I$=-15$\mu A/cm^2$')
#plt.suptitle('I=0')
plt.xlabel('time [s]')
#plt.ylabel('recovery variable W')
plt.ylabel('membrane voltage V [mV]')
plt.xlim(0,0.1)
axs.plot(ax/1000,ay)
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
plt.tight_layout()
plt.savefig('realstatedetrinzelnblue2.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def deff(rp,rm,v):
return (v**2*rp*rm)/((rp+rm)**3)
first=5
total=11
deffs=4
btoeq=np.zeros((deffs,total))
eqtob=np.zeros((deffs,total))
for k2 in range(first,first+total):
x=[]
ratefile = open('rate16m%d.txt' %k2,'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,deffs):
btoeq[k][k2-first]=1/ax[k]
eqtob[k][k2-first]=1/ax[k+deffs]
v=1.33
veco=np.zeros((1,16))
vec=np.zeros((3,20))
ii=0
for x in [20]:
col=[]
for y in range(5,21):
file=open('/home/richard/outhome/d16m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,16):
veco[0][z]=cola[z]
for x in [30,40,50]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/d7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
#for x in [40]:
# col=[]
# for y in range(5,21):
# file=open('/home/richard/outhome/g17a%d%d.txt' % (x,y),"r")
# for k in file:
# row=k.split()
# col.append(row[1])
# cola=np.array(col)
# for z in range(0,16):
# vec[ii][z]=cola[z]
# ii=ii+1
xfit=np.arange(0.5,3.25,0.25)
xso=np.arange(0.25,4.25,0.25)
xs=np.arange(-0.75,4.25,0.25)
xsh=np.arange(1,4.2,0.2)
plt.xlabel('bias current I')
plt.ylabel('$D_{eff}$')
plt.xlim(0.5,3)
plt.ylim(5*10**(-2),2*10**3)
plt.yscale('log')
plt.plot(xfit,deff(btoeq[2-2,:],eqtob[2-2,:],v),'y')#,label='D=2,theory' )
plt.plot(xfit,deff(btoeq[3-2,:],eqtob[3-2,:],v),'g')#,label='D=3,theory' )
plt.plot(xfit,deff(btoeq[4-2,:],eqtob[4-2,:],v),'b')#,label='D=4,theory' )
plt.plot(xfit,deff(btoeq[5-2,:],eqtob[5-2,:],v),'r')#,label='D=5,theory' )
#plt.plot(xsh,veco[0,:],label='D=1.2')
plt.plot(xso,veco[0,:],'yo',label='D=2')
plt.plot(xs,vec[0,:],'go',label='D=3')
plt.plot(xs,vec[1,:],'bo',label='D=4')
plt.plot(xs,vec[2,:],'ro',label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('dcomppw16m.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
fil1=open('/home/richard/outhome2/outhome/Fano33sh2.txt',"r")
x1,y1=[],[]
for k in fil1:
row=k.split()
x1.append(float(row[0]))
y1.append(float(row[1]))
x1s,y1s = zip(*sorted(zip(x1,y1)))
col=[]
for y in range(1,31):
file=open('/home/richard/outhome/mechf%d.txt' % (y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
x1sa=np.arange(0.56,0.86,0.01)
fil2=open('/home/richard/outhome2/outhome/Fano43sh2.txt',"r")
x2,y2=[],[]
for k in fil2:
row=k.split()
x2.append(float(row[0]))
y2.append(float(row[1]))
x2s,y2s = zip(*sorted(zip(x2,y2)))
fil3=open('/home/richard/outhome2/outhome/Fano56sh.txt',"r")
x3,y3=[],[]
for k in fil3:
row=k.split()
x3.append(float(row[0]))
y3.append(float(row[1]))
x3s,y3s = zip(*sorted(zip(x3,y3)))
fil4=open('/home/richard/outhome2/outhome/Fano72sh.txt',"r")
x4,y4=[],[]
for k in fil4:
row=k.split()
x4.append(float(row[0]))
y4.append(float(row[1]))
x4s,y4s = zip(*sorted(zip(x4,y4)))
fil5=open('/home/richard/outhome2/outhome/Fano94sh.txt',"r")
x5,y5=[],[]
for k in fil5:
row=k.split()
x5.append(float(row[0]))
y5.append(float(row[1]))
x5s,y5s = zip(*sorted(zip(x5,y5)))
#xsa=np.array(xs)
#ysa=np.array(ys)
plt.xlabel('bias Force F')
plt.ylabel('Fano factor')
plt.yscale('log')
plt.plot(x1s,y1s,label='kT=0.033')
plt.plot(x2s,y2s,label='kT=0.043')
plt.plot(x3s,y3s,label='kT=0.056')
plt.plot(x4s,y4s,label='kT=0.072')
plt.plot(x5s,y5s,label='kT=0.094')
plt.legend()
plt.savefig('mechfsh.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def comp(x,b,c,d,e):
return b*x**3+c*x**2+d*x+e
matplotlib.rcParams.update({'font.size': 20})
timefac=1000
N=5000000
dt=0.005
T=N*dt
dvalues=6
ivalues2=51
count=np.zeros((dvalues,ivalues2))
ii=0
file=open('/home/richard/NetBeansProjects/detrinzel/countrinzelnoise5.txt',"r")
colx=[]
for k in file:
col=[]
row=k.split()
colx.append(float(row[0]))
for l in range(1,dvalues+1):
col.append(float(row[l]))
cola=np.array(col)
for l in range(0,dvalues):
count[l][ii]=cola[l]
ii=ii+1
colxa=np.array(colx)
date=['realrinzelrangelong26d1','realrinzelrange26d1','realrinzelrange26d1','realrinzelrangeshort26d1','realrinzelrangeshort26d1']
D=[200,250,300,400,500]
l=len(D)
istart=1
ivalues=10
vec=np.zeros((l,ivalues))
vecx=np.zeros((l,ivalues))
ii=0
offset=np.zeros(l,dtype=int)
for m in range(0,l):
x=D[m]
col1,colx1=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date[m],x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
if len(col1)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola1[z]*timefac
vecx[ii][z]=colxa1[z]
ii=ii+1
colorv=['y','g','b','r','c','k']
t=np.arange(-21,-6,0.1)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('firing rate <v> [$s^{-1}$]')
plt.xlim(-16.2,-9)
#plt.ylim(1.2,1.4)
#plt.yscale('log')
for n in range(0,dvalues-1):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl],label='D=%.0f' %(D[n]/10))
plt.plot(colxa,count[n+1,:]/T*timefac,color='black')#,label='D=%s' %(D[n]/10))
#plt.plot(t,comp(t,b[n],c[n],d[n],e[n]),colorv[n])
#plt.plot(t,comp(t,popt[0],popt[1]),label='linear appr %f %f'%(popt[0],popt[1]))
plt.legend()
plt.tight_layout()
plt.savefig('detmocountrinzelcompnew2big.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on March 18, 2019, 6:14 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
using namespace std;
double average(long long int x[],int n);
double square(long long int x[],int n);
double ninf(double V, double k, double Vh);
double init(long long int x[],int n);
double initd(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
//ofstream myfile2;
//ofstream myfile3;
myfile.open ("inaprealanhopfnb2.txt");
//myfile2.open ("statechange.txt");
//myfile3.open (argv[4]
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
double I0=46; // 0
double dI=0.5;
double gL=1; // 8
double EL=-78; // -80
double gNa=4; // 20
double ENa=60; // 60
double gK=4; // 9
double EK=-90; // -90
//double gM=5; // 5
/*//slow K+ current
double kinf=5; // 5
double vinf=-20; // -20
double tauM=30; // 20*/
//Na current
double km=7; // 15
double vm=-30; // -20
//fast K+ current
double kn=5; // 5
double vn=-45; // -20
double tau=1; // 0.152
//int N=500000;
int Neq=3000000; //30000000
int points=100000;//100000
int sampling=Neq/points;
int j,f;
double dt=0.005;
double D=0;
//int spikes=100;
//double* spike=new double[spikes];
double th=-25;
double thn=0.5;
int runs=1;
int Ivalues=1;
long long int count[runs],sqcount[runs];
double Nav,N2av,T;
double mx,nx,nx2,v[runs],nf[runs],nfs[runs],vs[runs],uGe[Ivalues],uFano[Ivalues],uDeff[Ivalues],Deff,Deff2,deff[Ivalues],vav[Ivalues],Fano[Ivalues],vout[points],nout[points],bvout[points],cout[points],lastcount,prelastchange,lastchange;
int p=0;
int bv,bvp,sv;
lastcount=0;
prelastchange=0;lastchange=0;
sv=0;
//for(s=0;s<Ivalues;s++){
//initd(nfs,runs);
nfs[0]=0.432;
vs[0]=-50;
mx=0.0285-0.0006*I0;
nx=1.5-I0/80;
nx2=1.6-I0/80;
if(nfs[0]>mx*vs[0]+nx2){
bv=0;
}
else{
bv=1;
}
init(count,runs);
for(j=0;j<Neq;j++){
for(int a=0;a<runs;a++){
v[a]=I0*dt+vs[a]-gL*(vs[a]-EL)*dt-gNa*ninf(vs[a],km,vm)*(vs[a]-ENa)*dt-gK*nfs[a]*(vs[a]-EK)*dt+sqrt(2*D*dt)*n(gen);
nf[a]=nfs[a]+(ninf(vs[a],kn,vn)-nfs[a])*dt/tau;
if(v[a] > th && vs[a] < th){
sv=1;
}
if(sv==1 && nf[a] > thn && nfs[a] < thn){
count[a]=count[a]+1;
sv=0;
lastcount=j;
}
if(( bv==1 && nf[a]>mx*v[a]+nx2) || (j-lastcount)*dt>2){
if((j-lastchange)*dt<0.4){
bv=0;
lastchange=prelastchange;
}
else{
bv=0;
prelastchange=lastchange;
lastchange=j;
}
}
if(bv==0 && nf[a]<mx*v[a]+nx){
if((j-lastchange)*dt<0.4){
bv=1;
lastchange=prelastchange;
}
else{
bv=1;
prelastchange=lastchange;
lastchange=j;
}
}
if(j==p*sampling){vout[p]=v[a];
nout[p]=nf[a];
bvout[p]=bv;
cout[p]=count[a];
p=p+1;
}
vs[a]=v[a];
nfs[a]=nf[a];
}
}
for(f=0;f<points;f++){
myfile << f*sampling*dt << " " << vout[f] << " "<< nout[f] << " "<< bvout[f]<<" " << cout[f] << "\n";
}
myfile.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(long long int x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
double square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
double init(long long int x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def comp(x,b,c,d,e):
return b*x**3+c*x**2+d*x+e
timefac=1000
date=['realrinzelrange26d1','realrinzelrange26d1','realrinzelrangeshort26d1','realrinzelrangeshort26d1']
D=[250,300,400,500]
l=len(D)
istart=1
ivalues=10
rbtoeq=np.zeros(ivalues)
ubtoeq=np.zeros(ivalues)
reqtob=np.zeros(ivalues)
ueqtob=np.zeros(ivalues)
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/param%s%d.txt' %(date[0]+date[1],k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
rbtoeq[k2]=x[0]
ubtoeq[k2]=x[1]
reqtob[k2]=x[2]
ueqtob[k2]=x[3]
date=['realrinzelrangelong26d1','realrinzelrange26d1','realrinzelrange26d1','realrinzelrangeshort26d1','realrinzelrangeshort26d1']
D=[200,250,300,400,500]
l=len(D)
istart=1
ivalues=10
vec=np.zeros((l,ivalues))
vecx=np.zeros((l,ivalues))
ii=0
offset=np.zeros(l,dtype=int)
for m in range(0,l):
x=D[m]
col1,colx1=[],[]
for y in range(istart,istart+ivalues):
param=open('/home/richard/outhome/param%s%d%d.txt' %(date[m],x,y),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
Ndiff=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
T=dt*Ndiff*repetitions
file=open('/home/richard/outhome/g%s%d%d.txt' % (date[m],x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
if len(col1)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola1[z]*timefac
vecx[ii][z]=colxa1[z]
ii=ii+1
colorv=['y','g','b','r','c','k']
t=np.arange(-21,-6,0.1)
plt.xlabel('bias current I')
plt.ylabel('firing rate <v>$')
plt.xlim(-16.2,-9)
#plt.ylim(1.2,1.4)
#plt.yscale('log')
for n in range(0,dvalues-1):
nl=round(ivalues-offset[n])
#plt.plot(vecx[n,0:nl],vec[n,0:nl],label='D=%.0f' %(D[n]/10))
plt.plot(colxa,count[n+1,:]/T*timefac,color='black')#,label='D=%s' %(D[n]/10))
plt.plot(t,comp(t,b[n],c[n],d[n],e[n]),colorv[n])
#plt.plot(t,comp(t,popt[0],popt[1]),label='linear appr %f %f'%(popt[0],popt[1]))
plt.legend()
plt.savefig('detmocountrinzelcompfit.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def comp(x,a,b):
return a/x+b
matplotlib.rcParams.update({'font.size': 18})
D=np.array([25,30,40,50])
params=4
dvalues=6
b=np.zeros((params,dvalues))
ii=0
eqfile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/detmocountparam5.txt','r')
for k in eqfile:
col=[]
row=k.split()
for lll in range(0,params):
col.append(float(row[lll]))
cola=np.array(col)
for kk in range(0,params):
b[kk][ii]=cola[kk]
ii=ii+1
eqfile.close()
a1=np.zeros(params)
a2=np.zeros(params)
eqfile = open('detmocountparamparam3.txt','w')
for n in range(0,params):
popt,pcov = curve_fit(comp, D, b[n,2:6])
a1[n]=popt[0]
a2[n]=popt[1]
for k3 in range(0,2):
eqfile.write('%.6f '%popt[k3])
eqfile.write('\n')
eqfile.close()
t=np.arange(25,50,0.1)
plt.xlabel('bias current I')
plt.ylabel('firing rate')
#plt.xlim(0,4)
#plt.ylim(1.2,1.4)
#plt.yscale('log')
names=['a','b','c','d']
for n in range(0,params):
plt.figure()
plt.xlabel('noise intensity D')
plt.ylabel('%s' %names[n])
plt.plot(D,b[n,2:6],'bx')
plt.plot(t,comp(t,a1[n],a2[n]),'b')
plt.tight_layout()
plt.savefig('detmocountrinzelparam3%.0f.pdf' %n)
for n in range(0,params):
plt.figure()
plt.xlabel('inverse noise intensity 1/D')
plt.ylabel('%s' %names[n])
plt.plot(1/t,comp(t,a1[n],a2[n]),'b')
plt.plot(1/D,b[n,2:6],'bx')
plt.tight_layout()
plt.savefig('detmocountrinzelparaminv3%.0f.pdf' %n)
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b):
return a * np.exp(-b * x)
def func2(x, a, b):
return a * x + b
def func3(x, a):
return a
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def deffana(t,r0p,r0m,ap,am,bp,bm):
return (r(r0p,ap,bp,t,30)*r(r0m,am,bm,t,30))/((r(r0p,ap,bp,t,30)+r(r0m,am,bm,t,30))**3)
D=[20]
l=len(D)
Da=np.array(D)
d=Da[0]/100
#def deffana(t,r0p,r0m,ap,am,bp,bm):
# return (r(r0p,ap,bp,t,0.5)*r(r0m,am,bm,t,0.5))/((r(r0p,ap,bp,t,0.5)+r(r0m,am,bm,t,0.5))**3)
date='realfast11jjem2'
params2=np.zeros(6)
params=np.zeros((4,11))
changespertime=np.zeros((l,20))
eqtottime=np.zeros((l,20))
eqreltime=np.zeros((l,20))
btottime=np.zeros((l,20))
breltime=np.zeros((l,20))
countstot=np.zeros((l,20))
ii=0
dt=0.0001
N=120000000
Neq=20000000
Ndiff=N-Neq
repetitions=20
runs=500
T=runs*repetitions
for x in D:
for y in range(1,21):
times,avalues,jrvalues,j2values,state=[],[],[],[],[]
file=open('/home/richard/outhome/time%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
avalues.append(float(row[0]))
jrvalues.append(float(row[1]))
j2values.append(float(row[2]))
state.append(float(row[3]))
j2valuesa=np.array(j2values)
jrvaluesa=np.array(jrvalues)
avaluesa=np.array(avalues)
statea=np.array(state)
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
inteq[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
intb[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
intb[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
inteq[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
counts=counteq+countb
countsrel=counts/Ndiff
if counts<9999:
changespertime[ii][y-1]=counts
else:
changespertime[ii][y-1]=(counts/(avaluesa[9999]*repetitions+jrvaluesa[9999]+j2valuesa[9999]/Ndiff))*T
# plt.figure()
# plt.hist(intbt, bins=50)
# plt.yscale('log')
# plt.title("distribution of bursting time intervals")
# plt.savefig('bdistajrj2%s%d%d.pdf' %(date,x,y))
# plt.figure()
# plt.hist(inteqt, bins=50)
# plt.yscale('log')
# plt.title("distribution of equilibrium time intervals")
# plt.savefig('eqdistajrj2%s%d%d.pdf' %(date,x,y))
# eqtot=np.sum(inteqt)
# btot=np.sum(intbt)
# eqrel=eqtot/(eqtot+btot)
# brel=btot/(eqtot+btot)
# eqtottime[ii][y-1]=eqtot/counteq
# btottime[ii][y-1]=btot/countb
# eqreltime[ii][y-1]=eqrel
# breltime[ii][y-1]=brel
ii=ii+1
plt.figure()
xs2=np.arange(-0.175,0.325,0.025)
popt,pcov = curve_fit(deffana, xs2, changespertime[0,:])
params2[0]=popt[0]
params2[1]=popt[1]
params2[2]=popt[2]
params2[3]=popt[3]
params2[4]=popt[4]
params2[5]=popt[5]
eqfile2 = open('changesfit%s%d.txt' %(date,D[0]),'w')
for k4 in range(0,6):
eqfile2.write('%.6f\n'%params2[k4])
eqfile2.close()
t=np.arange(-0.2,0.3,0.01)
plt.xlabel('bias current')
plt.ylabel('changes')
plt.yscale('log')
for n in range(0,l):
plt.plot(xs2,changespertime[n,:],label='D=%s' %D[n])
plt.plot(t,deffana(t,popt[0],popt[1],popt[2],popt[3],popt[4],popt[5]),label='fit')
plt.legend()
plt.savefig('totalchanges%s%2.0f.pdf' %(date,D[0]))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
file=open('/home/richard/mastergit/NetBeansProjects/realstatevar/realstaterinzel16100.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[1]))
y.append(float(row[2]))
ax=np.array(x)
ay=np.array(y)
def an(V):
return (10-V)/(100*(np.exp((10-V)/10)-1))
def ah(V):
return 7*np.exp(-V/20)/100
def bn(V):
return np.exp(-V/80)/8
def bh(V):
return 1/(np.exp((30-V)/10)+1)
def hinf(V):
return ah(V)/(ah(V)+bh(V))
def ninf(V):
return an(V)/(an(V)+bn(V))
def winf(S,V):
return S*(ninf(V)+S*(1-hinf(V)))/(1+S**2) # entspricht w-isokline
gL=0.3
VL=10
gNa=120
VNa=115
gK=36
VK=12 #12
phi=3.82
Iapp=-15 #-12
SV=1.27
v=np.arange(-50,110,0.01)
vrinzelfile = open('vncrinzel%d.txt' %Iapp, "r")
colx,col=[],[]
for k in vrinzelfile:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
edgepointfile= open('edgerinzel%d.txt' %Iapp, "r")
edge=[]
for k2 in edgepointfile:
row2=k2.split()
edge.append(int(row2[0]))
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
axs = plt.subplot(111)
plt.suptitle('$I$=-16$\mu A/cm^2$')
#plt.suptitle('I=0')
#plt.xlabel('time [s]')
plt.ylabel('recovery variable W')
plt.xlabel('membrane voltage V [mV]')
plt.plot(colx[edge[0]:edge[1]],col[edge[0]:edge[1]],'blue',label='V-nullcline')
plt.plot(colx[edge[2]:edge[3]],col[edge[2]:edge[3]],'blue')
plt.plot(v,winf(SV,v),'orange',label='W-nullcline')
#plt.xlim(-50,10)
axs.plot(ax[78334:81668],ay[78334:81668],'black')
#plt.legend()
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
plt.tight_layout()
plt.savefig('realstatedetrinzelp16100shnn.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
file=open('/home/richard/mastergit/NetBeansProjects/realstatevar/realstateanhopf52.txt',"r")
x,y,z,a=[],[],[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
z.append(float(row[2]))
#a.append(float(row[4]))
ax=np.array(x)
ay=np.array(y)
az=np.array(z)
#aa=-np.array(a)/40
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
axs = plt.subplot(111)
plt.suptitle('$I$=45$\mu A/cm^2$')
#plt.suptitle('I=0')
plt.xlabel('time [s]')
plt.ylabel('membrane voltage [mV]')
plt.xlim(39.97,40.17)
axs.plot(ax/1000,ay,'black')
#plt.plot(ax/1000,az)
#plt.plot(ax,aa)
#axs.spines['right'].set_visible(False)
#axs.spines['top'].set_visible(False)
plt.tight_layout()
plt.savefig('realstateanhopf52sh.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on December 29, 2018, 9:27 PM
*/
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <random>
using namespace std;
/*
*
*/
double average(double x[],int n);
double square(double x[],int n);
double init(double x[],int n);
int main(int argc, char** argv) {
std::random_device rd;
std::mt19937 gen(rd(10));
std::normal_distribution<> n(0,1);
/*double filename=atof(argv[1]);
//filename << std::setprecision(3);
ostringstream filename_convert;
filename_convert << filename;
string filename_str = filename_convert.str();
filename_str="aha"+filename_str;
filename_str=filename_str+".txt";
ofstream myfile;
myfile.open(filename_str);*/
double ra[10];
/*double vec[5] = { 1.4, 2.2, 3.9, 4.5, 5};
int s=sizeof(vec)/sizeof(vec[3]);
double x=average(vec,s);
square(vec,s);
double z=average(vec,s);
init(vec,s);
double a=average(vec,s);
double testets=atof(argv[2]);
std::cout << x << " " << z << " " << a << testets << "\n";
int start=1;
double* test=new double[start];
double var[]={1,2,3,4,5};
int i;
for(i=0;i<5;i++){
int length=sizeof(test)/sizeof(test[0]);
if (i >= length) {
start= start*2; // double the previous size
double* temp= new double[start]; // create new bigger array.
for (int j=0; j<i; j++) {
temp[j] = test[j]; // copy values to new array.
}
delete [] test; // free old array memory.
test = temp; // now a points to new array.
}
if(var[i] < 3 && var[i] > 1){
test[i]=0.1;
}
else if(var[i] < 3 && var[i] <= 1){
test[i]=-0.9;
}
else{
test[i]=1.1;
}
}
int k=0;
while(test[k]!=0){
k++;
}
double testfinal[k]; // create array of right size.
for (int j=0; j<k; j++) {
testfinal[j] = test[j]; // copy values to new array.
}
delete [] test; // free old array memory.
int k2=sizeof(testfinal)/sizeof(testfinal[0]);
double ave=average(testfinal,k);
double dividend=0;
double divisor=21766;
double test123=(0.0+0)/21766+0;*/
for (int j=0; j<10; j++) {
ra[j] = n(gen)[j]; // copy values to new array.
}
std::cout << ra[5];
/*myfile << filename;
myfile.close();*/
return 0;
}
double average(double x[],int n){
int i;
double sum=0;
for(i=0;i<n;i++){
sum=sum+x[i];
}
double av=sum/n;
return av;
}
double square(double x[],int n){
int j;
for(j=0;j<n;j++){
x[j]*=x[j];
}
}
double init(double x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def snr(r0p,r0m,ap,am,bp,bm,t,D):
return (ap-am)**2/(D**2*(r(r0p,ap,bp,t,D)**(-1)+r(r0m,am,bm,t,D)**(-1)))
bp = 1.74
ap = 5.64
r0p = 0.0075
bm = 3.15
am = -10.76
r0m = 0.012
date='realrinzel20ninv0'
date2='realrinzel20ninv1'
date1='realrinzel15ninv0'
date3='realrinzel15ninv1'
D=[200,300]
D1=[500]
D2=[200,300]
D3=[500]
Dtot=D+D1+D2+D3
l=len(D)+len(D1)+len(D2)+len(D3)
points=1000000
length=500000
istart=2
ivalues=8
SNR=np.zeros((l,ivalues))
scale=np.zeros((l,ivalues))
ii=0
for c in D:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date,c,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date,c,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart]=epsilon**2*T
omegaind=round(omega*T)
if c==200 and z==9:
omegaind=2105
SNR[ii][z-istart]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
for c1 in D1:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date1,c1,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date1,c1,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart]=epsilon**2*T
omegaind=round(omega*T)
SNR[ii][z-istart]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
for c2 in D2:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date2,c2,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
if len(x)==0:
SNR[ii][z-istart]=SNR[ii][z-istart-1]
scale[ii][z-istart]=scale[ii][z-istart-1]
else:
param=open('/home/richard/outhome/param%s%d%d.txt' %(date2,c2,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart]=epsilon**2*T
omegaind=round(omega*T)
SNR[ii][z-istart]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
for c3 in D3:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date3,c3,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date3,c3,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart]=epsilon**2*T
omegaind=round(omega*T)
SNR[ii][z-istart]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('SNR')
t=np.arange(-0.1,0.3,0.01)
xs=np.arange(-15.4,-9,0.8)
plt.yscale('log')
#plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
plt.ylim(10**(-7),10**(-3))
colorv=['y','g','b','r','c']
for n in range(0,3):
plt.plot(xs,abs((SNR[n,:]-1)/scale[n,:]),label='D=%.2f, rest' %(Dtot[n]*0.1))
for n in range(3,l):
plt.plot(xs,abs((SNR[n,:]-1)/scale[n,:]),label='D=%.2f, run' %(Dtot[n]*0.1))
#for n in range(0,l):
# plt.plot(t,snr(r0p,r0m,ap,am,bp,bm,t,Dtot[n]*0.01),colorv[n]+'o')
#plt.plot(xs,SNR[2,:],label='D=3')
#plt.plot(xs,SNR[1,:],label='D=2.5')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [0,2,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
#plt.plot(sax2,say2/T2,label='e6')
plt.legend()
plt.savefig('snronlyrinzel%s.pdf' %date)
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on December 27, 2018, 1:15 PM
*/
#include <cstdlib>
#include <cstdio>
//#include <stdlib.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
//#include <math.h>
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
FILE *ft;
FILE *fp;
FILE *fu;
fu=fopen("deffaven4.txt","w");//gemitteltes D_eff
ft=fopen("geschwn4.txt","w");
fp=fopen("deffn4.txt","w");
//Initialisierung rng
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T=gsl_rng_default;
r=gsl_rng_alloc (T);
char *eptr;
//int N=strtol(argv[1], &eptr,10);
int N=200000;//Anzahl Zeitschritte
int O=400;//Anzahl der Kraftschritte
int P=50000;//Zeitschritte, über die gemittelt wird
double df=0.001;
double sigma=1;
//Speicherplatz reservieren
double *v;
v= (double *) malloc((N+1) *100* sizeof(double));
double *x;
x= (double *) malloc((N+1) *100 * sizeof(double));
double deff[O];
deff[0]=0;
double deff2[O];
deff2[0]=0;
double vav[O];
/*
double dt=strtod(argv[2], &eptr);
double F=strtod(argv[3], &eptr);
double gam=strtod(argv[4], &eptr);
double kT=strtod(argv[5], &eptr);
*/
double dt=0.1;
double F0=0.5;//kleinste Kraft
double kT=0.094;
double gam=0.4;
int h;
int i;
int j;
int l;
int a,b,c,a2,b2,c2;
double F;
double xav[O];
xav[0]=0;
double x2av[O];
x2av[0]=0;
double vavt[N+1],xavt[N+1],x2avt[N+1],defft[N+1];
int s;
//Schleife über versch Kräfte
for(s=0;s<O;s++){
F=F0+s*df;
//Schleife über alle Zeitschritte
for(j=0;j<N;j++){
//Initialisierung von x
for(h=0;h<100;h++){
x[0+h]=0;
}
//Initialisierung von v
for(i=0;i<100;i++){
v[0+i]=0;
}
//Schleife über alle Teilchen
for(l=0;l<100;l++){
v[(j+1)*100+l]=v[j*100+l]-gam*v[j*100+l]*dt+F*dt-sin(x[j*100+l])*dt+sqrt(2*kT*gam*dt)*gsl_ran_gaussian(r,sigma);
x[(j+1)*100+l]=x[j*100+l]+v[j*100+l]*dt;
}
double sum4=0;
for(a2=0;a2<100;a2++){
sum4=sum4+v[(j+1)*100+a2];
}
vavt[j+1]=sum4/100;//mittl Geschwindigkeit
double sum5=0;
for(b2=0;b2<100;b2++){
sum5=sum5+x[(j+1)*100+b2];
}
xavt[j+1]=sum5/100;//mittl Position
double sum6=0;
for(c2=0;c2<100;c2++){
sum6=sum6+x[(j+1)*100+c2]*x[(j+1)*100+c2];
}
x2avt[j+1]=sum6/100;//Mittel der Positionsquadrate
defft[j+1]=(x2avt[j+1]-xavt[j+1]*xavt[j+1])/(2*(j+1)*dt);//Diffusionskoeffizient
}
double min=defft[N-P];
int d;
//Finden des Minimums der letzten Werte
for(d=0;d<P;d++){
if(defft[N-P+d+1]<min){
min=defft[N-P+d+1];
}
}
//Finden des Maximums der letzten Werte
double max=defft[N-P];
int e;
for(e=0;e<P;e++){
if(defft[N-P+e+1]>max){
max=defft[N-P+e+1];
}
}
deff2[s]=(min+max)/2;//mittl Diffusionskoeffizient
double sum=0;
for(a=0;a<100;a++){
sum=sum+v[N*100+a];
}
vav[s]=sum/100;
double sum2=0;
for(b=0;b<100;b++){
sum2=sum2+x[N*100+b];
}
xav[s]=sum2/100;
double sum3=0;
for(c=0;c<100;c++){
sum3=sum3+x[N*100+c]*x[N*100+c];
}
x2av[s]=sum3/100;
deff[s]=(x2av[s]-xav[s]*xav[s])/(2*N*dt);//Diffusionskoeffizient aus den letzten Werten
}
//Ausgabe
std::cout <<"wasss kommt raus %f %f %f",vav[5],vav[O-5],deff[O-5];
//int k;
//for(k=0;k<O;k++){
//fprintf(ft,"%f %f\n",F0+k*df,vav[k]);
//}
//int z;
//for(z=0;z<O;z++){
//fprintf(fp,"%f %f\n",F0+z*df,deff[z]);
//}
//
//int y;
//for(y=0;y<O;y++){
//fprintf(fu,"%f %f\n",F0+y*df,deff2[y]);
//}
//Speicher freigeben und Dokumente schließen
//fclose(ft);
//fclose(fu);
gsl_rng_free (r);
//fclose(fp);
free(v);
free(x);
return 0;
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
from scipy.optimize import curve_fit
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def snr(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,av,v0):
return (qr(r0m,am,bm,cm,t,D)*(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))/(v0**2*qr(r0p,ap,bp,cp,t,D)))*((((2*ap*t+bp)-(2*am*t+bm))*qr(r0p,ap,bp,cp,t,D)*v0)/(D*(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D)))+av)**2
def qbarrier(x,a,b,c):
return a*x**2+b*x+c
def qr(r0,a,b,c,t,D):
return r0*np.exp(-qbarrier(t,a,b,c)/D)
def deff(x,rp,rm,v0,av):
return ((v0+av*x)**2*rp*rm)/((rp+rm)**3)
def fano(x,rp,rm,v0,av):
return (2*(v0+av*x)*rp)/((rp+rm)**2)
def func(x, a, b):
return a * np.exp(-b * x)
def deffana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return ((barrier(av,v0,t))**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
def deffqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,av,v0):
return ((barrier(av,v0,t))**2*qr(r0p,ap,bp,cp,t,D)*qr(r0m,am,bm,cm,t,D))/((qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))**3)
def fanoana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return (2*barrier(av,v0,t)*r(r0p,ap,bp,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**2)
def vana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return barrier(av,v0,t)*r(r0m,am,bm,t,D)/(r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))
def vqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,av,v0):
return barrier(av,v0,t)*qr(r0m,am,bm,cm,t,D)/(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))
date3='realfast11jjem2sh'
date2='realfast19jjem2st'
ivalues=20
l=5
D1=[35]
D3=[40,50]
D2=[45]
Dvar=[30]
D=D1+D2+D3+Dvar
Da=np.array(D)
btoeq=np.zeros((l,ivalues))
eqtob=np.zeros((l,ivalues))
params=np.zeros((4,ivalues))
paramsav=np.zeros((4,ivalues))
params2=np.zeros(4)
paramsq=np.zeros(6)
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/rate%s%d.txt' %('new'+date3+'new'+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,l):
btoeq[k][k2]=1/ax[k]
eqtob[k][k2]=1/ax[k+l]
av=0.013
v0=0.0637
xs=np.zeros(l)
for b in range(0,l):
xs[b]=100/Da[b]
for k2 in range(0,ivalues):
popt,pcov = curve_fit(func, xs, btoeq[:,k2])
params[0][k2]=popt[0]
params[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2])
params[2][k2]=popt[0]
params[3][k2]=popt[1]
rbte=np.mean(params[0,:])
retb=np.mean(params[2,:])
istart=1
xnew=np.arange(-5+istart,-5+istart+ivalues)*0.02
popt,pcov = curve_fit(qbarrier, xnew, params[1,:])
paramsq[0]=popt[0]
paramsq[1]=popt[1]
paramsq[2]=popt[2]
popt,pcov = curve_fit(qbarrier, xnew, params[3,:])
paramsq[3]=popt[0]
paramsq[4]=popt[1]
paramsq[5]=popt[2]
bp = 1.74
ap = 5.64
r0p = 0.0075
bm = 3.15
am = -10.76
r0m = 0.012
date='realfast13aem2n4'
date1='realfast9aem2sh'
D=[25,30]
D1=[35,45]
Dtot=D+D1
l=len(D)+len(D1)
points=1000000
length=500000
ivalues=20
SNR=np.zeros((l,ivalues))
scale=np.zeros((l,ivalues))
ii=0
for c in D:
for z in range(1,21):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date,c,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date,c,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-1]=epsilon**2*T
omegaind=round(omega*T)
SNR[ii][z-1]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
for c1 in D1:
for z in range(1,21):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date1,c1,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date1,c1,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-1]=epsilon**2*T
omegaind=round(omega*T)
SNR[ii][z-1]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Signal-to-noise ratio SNR')
t=np.arange(-0.1,0.3,0.01)
xs=np.arange(-0.08,0.32,0.02)
plt.yscale('log')
#plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
#plt.xlim(4*10**(-4),100)
colorv=['g','y','b','r','c']
for n in range(0,l):
plt.plot(xs,(SNR[n,:]-1)/scale[n,:],colorv[n],label='D=%.2f' %(Dtot[n]*0.01))
#for n in range(0,l):
# plt.plot(t,snr(rbte,retb,paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[n]*0.01,av,v0)/8,colorv[n])
plt.plot([0.163, 0.163], [10**(-7), 10], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot([-0.02, -0.02], [10**(-7), 10], color='black', linestyle='-')
#plt.plot(xs,SNR[2,:],label='D=3')
#plt.plot(xs,SNR[1,:],label='D=2.5')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [0,2,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
#plt.plot(sax2,say2/T2,label='e6')
plt.legend()
plt.savefig('snrealonlycrit2.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
vec=np.zeros((3,2))
ii=0
for x in [0.1,0.2,0.3]:
file=open('/home/richard/paratest/test%.1f.txt' % (x),"r")
col=[]
for k in file:
col.append(k)
for y in range(0,2):
cola=np.array(col)
vec[ii][y]=cola[y]
ii=ii+1
print(vec[0][0],vec[1][1],vec[2][0])
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
omega=0.01
runs=500
points=1000000
length=500000
N=100000000
repetitions=2
dt=0.00001
T=N*repetitions*dt
T2=T*10
S=np.zeros(length)
omegaind=round(omega*T)
SNR=np.zeros((4,20))
ii=0
for c in [30,40,50]:
for z in range(1,21):
file=open('/home/richard/outhome/ft11je1%d%d.txt' %(c,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
SNR[ii][z-1]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
repetitions=2
T=N*repetitions*dt
for c in [25]:
for z in range(1,21):
file=open('/home/richard/outhome/ft8je1%d%d.txt' %(c,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
SNR[ii][z-1]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind+1],ay[omegaind+2]])
ii=ii+1
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('bias current')
plt.ylabel('SNR')
xs=np.arange(-0.75,4.25,0.25)
plt.yscale('log')
#plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
#plt.xlim(4*10**(-4),100)
plt.plot(xs,SNR[0,:],label='D=3')
plt.plot(xs,SNR[1,:],label='D=4')
plt.plot(xs,SNR[2,:],label='D=5')
#plt.plot(xs,SNR[1,:],label='D=2.5')
plt.legend()
#plt.plot(sax2,say2/T2,label='e6')
plt.savefig('snr345log.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def barrier(a,b,x):
return a * x + b
def qbarrier(x,a,b,c):
return a*x**2+b*x+c
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def deff(x,rp,rm,v0,av):
return ((v0+av*x)**2*rp*rm)/((rp+rm)**3)
def v(x,rp,rm,v0,av):
return ((v0+av*x)*rm)/(rp+rm)
def func(x, a, b):
return a * np.exp(-b * x)
def deffana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return ((barrier(av,v0,t))**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
def fanoana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return (2*barrier(av,v0,t)*r(r0p,ap,bp,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**2)
def vana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return barrier(av,v0,t)*r(r0m,am,bm,t,D)/(r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))
def fanofun(x,rp,rm,v0,av):
return 2*deff(x,rp,rm,v0,av)/v(x,rp,rm,v0,av)
D1=[35]
D3=[40,50]
D2=[45]
Dvar=[30]
D=D1+D2+D3+Dvar
Da=np.array(D)
l1=len(D1)
l2=len(D2)
l3=len(D3)
lvar=len(Dvar)
l=l1+l2+l3+lvar
date1='realfast11jjem2sh'
date3='realfast11jjem2st'
date2='realfast19jjem2st'
datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
yvar=[4,13,3]
yvalues=len(yvar)
istart=1
ivalues=20
epsilon = 0.00001
btoeq=np.zeros((l,ivalues))
eqtob=np.zeros((l,ivalues))
params=np.zeros((4,ivalues))
paramsav=np.zeros((4,ivalues))
params2=np.zeros(4)
paramsq=np.zeros(6)
for k2 in range(0,ivalues):
x=[]
ratefile = open('rate%s%d.txt' %('new'+date1+'new'+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,l):
btoeq[k][k2]=1/ax[k]
eqtob[k][k2]=1/ax[k+l]
av=0.013
v0=0.0637
xs=np.zeros(l)
for b in range(0,l):
xs[b]=100/Da[b]
for k2 in range(0,ivalues):
popt,pcov = curve_fit(func, xs, btoeq[:,k2])
params[0][k2]=popt[0]
params[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2])
params[2][k2]=popt[0]
params[3][k2]=popt[1]
rbte=np.mean(params[0,:])
retb=np.mean(params[2,:])
for k2 in range(0,ivalues):
popt,pcov = curve_fit(func, xs, btoeq[:,k2],bounds=((rbte-epsilon,-np.inf), (rbte+epsilon,np.inf)))
paramsav[0][k2]=popt[0]
paramsav[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2],bounds=((retb-epsilon,-np.inf), (retb+epsilon,np.inf)))
paramsav[2][k2]=popt[0]
paramsav[3][k2]=popt[1]
xnew=np.arange(-5+istart,-5+istart+ivalues)*0.02
popt,pcov = curve_fit(qbarrier, xnew, params[1,:])
paramsq[0]=popt[0]
paramsq[1]=popt[1]
paramsq[2]=popt[2]
popt,pcov = curve_fit(qbarrier, xnew, params[3,:])
paramsq[3]=popt[0]
paramsq[4]=popt[1]
paramsq[5]=popt[2]
popt,pcov = curve_fit(barrier, xnew, paramsav[1,:])
params2[0]=popt[0]
params2[1]=popt[1]
popt,pcov = curve_fit(barrier, xnew, paramsav[3,:])
params2[2]=popt[0]
params2[3]=popt[1]
eqfile2 = open('paramsdfnew%s.txt'%(date1+date2),'w')
for k4 in range(0,2):
eqfile2.write('%.6f\n'%params2[k4])
eqfile2.write('%.6f\n'%rbte)
for k4 in range(2,4):
eqfile2.write('%.6f\n'%params2[k4])
eqfile2.write('%.6f\n'%retb)
eqfile2.close()
paramfile = open('parambarrier%s.txt' %('new'+date1+'new'+date2),'r')
xx=[]
for k4 in paramfile:
row=k4.split()
xx.append(float(row[0]))
axx=np.array(xx)
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countI9a.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
N=50000000
dt=0.0005
T=N*dt
vvec=np.zeros(ivalues)
for ll in range(0,ivalues):
vvec[ll]=cola[2*ll+12]/T
ii=0
istart1=1
ivalues1=20
vec=np.zeros((l,ivalues1))
for x in D1:
col1,colx1=[],[]
for y in range(istart1,istart1+ivalues1):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,ivalues1):
vec[ii][z]=cola1[z]
ii=ii+1
istart2=1
ivalues2=20
for x in D2:
col2,colx2=[],[]
for y in range(istart2,istart2+ivalues2):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx2.append(float(row[0]))
col2.append(float(row[1]))
colxa2=np.array(colx2)
cola2=np.array(col2)
for z in range(0,ivalues2):
vec[ii][z]=cola2[z]
ii=ii+1
istart3=1
ivalues3=20
for x in D3:
col3,colx3=[],[]
for y in range(istart3,istart3+ivalues3):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx3.append(float(row[0]))
col3.append(float(row[1]))
colxa3=np.array(colx3)
cola3=np.array(col3)
for z in range(0,ivalues3):
vec[ii][z]=cola3[z]
ii=ii+1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/d%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
vec[ii][z]=colavar[z]
ii=ii+1
xs=np.arange(-5+istart1,-5+istart1+ivalues1)*0.02
pv=np.arange(0,ivalues)
plt.xlabel('bias current I')
plt.ylabel('$D_{eff}$')
#plt.xlim(0,3.5)
#plt.ylim(5*10**(-2),2*10**3)
plt.yscale('log')
ap=ax[0]
am=ax[3]
bp=ax[1]
bm=ax[4]
r0p=rbte
r0m=retb
colorv=['y','g','b','r','c']
t=np.arange(-0.1,0.3,0.01)
#for n in range(0,l):
# plt.plot(t,deffana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#for n in range(0,l):
# plt.plot(t,deffana(axx[2],axx[5],axx[0],axx[3],axx[1],axx[4],t,Da[n]/100,av,v0),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,l):
plt.plot(xs,vec[n,:],colorv[n]+'o',label='D=%.2f' %(Da[n]/100))
for n in range(0,l):
plt.plot((pv-4)*0.02,deff((pv-4)*0.02,btoeq[n][pv],eqtob[n][pv],vvec[pv],0),colorv[n])
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
handles, labels = plt.gca().get_legend_handles_labels()
order = [4,0,2,1,3]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('dcompdfpwnew%s.pdf' %(date1+date2))
g=np.zeros((l,ivalues1))
ii=0
for x in D1:
col1,colx1=[],[]
for y in range(istart1,istart1+ivalues1):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,ivalues1):
g[ii][z]=cola1[z]
ii=ii+1
for x in D2:
col2,colx2=[],[]
for y in range(istart2,istart2+ivalues2):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx2.append(float(row[0]))
col2.append(float(row[1]))
colxa2=np.array(colx2)
cola2=np.array(col2)
for z in range(0,ivalues2):
g[ii][z]=cola2[z]
ii=ii+1
for x in D3:
col3,colx3=[],[]
for y in range(istart3,istart3+ivalues3):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx3.append(float(row[0]))
col3.append(float(row[1]))
colxa3=np.array(colx3)
cola3=np.array(col3)
for z in range(0,ivalues3):
g[ii][z]=cola3[z]
ii=ii+1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/g%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
g[ii][z]=colavar[z]
ii=ii+1
plt.figure()
plt.xlabel('bias current I')
plt.ylabel('firing rate')
#plt.yscale('log')
colorv=['y','g','b','r','c']
t=np.arange(-0.1,0.3,0.01)
#for n in range(0,l):
# plt.plot(t,vana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,l):
plt.plot((pv-4)*0.02,v((pv-4)*0.02,btoeq[n][pv],eqtob[n][pv],vvec[pv],0),colorv[n])
for n in range(0,l):
plt.plot(xs,g[n,:],colorv[n]+'o',label='D=%.2f' %(Da[n]/100))
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
handles, labels = plt.gca().get_legend_handles_labels()
order = [4,0,2,1,3]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('gcompdfpwnew%s.pdf' %(date1+date2))
fano=np.zeros((l,ivalues1))
ii=0
for x in D1:
col1,colx1=[],[]
for y in range(istart1,istart1+ivalues1):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,ivalues1):
fano[ii][z]=cola1[z]
ii=ii+1
for x in D2:
col2,colx2=[],[]
for y in range(istart2,istart2+ivalues2):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx2.append(float(row[0]))
col2.append(float(row[1]))
colxa2=np.array(colx2)
cola2=np.array(col2)
for z in range(0,ivalues2):
fano[ii][z]=cola2[z]
ii=ii+1
for x in D3:
col3,colx3=[],[]
for y in range(istart3,istart3+ivalues3):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx3.append(float(row[0]))
col3.append(float(row[1]))
colxa3=np.array(colx3)
cola3=np.array(col3)
for z in range(0,ivalues3):
fano[ii][z]=cola3[z]
ii=ii+1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/f%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
fano[ii][z]=colavar[z]
ii=ii+1
plt.figure()
plt.xlabel('bias current I')
plt.ylabel('Fano factor')
plt.yscale('log')
colorv=['y','g','b','r','c']
t=np.arange(-0.1,0.3,0.01)
#for n in range(0,l):
# plt.plot(t,fanoana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
for n in range(0,l):
plt.plot((pv-4)*0.02,fanofun((pv-4)*0.02,btoeq[n][pv],eqtob[n][pv],vvec[pv],0),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,l):
plt.plot(xs,fano[n,:],colorv[n]+'o',label='D=%.2f' %(Da[n]/100))
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
handles, labels = plt.gca().get_legend_handles_labels()
order = [4,0,2,1,3]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('fcompdfpwnew%s.pdf' %(date1+date2))
t=np.arange(-0.1,0.3,0.001)
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('potential barrier')
#plt.plot(t,barrier(t,params2[0],params2[1]),'y')
#plt.plot(t,barrier(t,params2[2],params2[3]),'y')
#plt.plot(t,2*barrier(t,params2[0],params2[1]),'y')
#plt.plot(t,2*barrier(t,params2[2],params2[3]),'y')
plt.plot(t,qbarrier(t,paramsq[0],paramsq[1],paramsq[2]),colorv[0])
plt.plot(t,qbarrier(t,paramsq[3],paramsq[4],paramsq[5]),colorv[1])
plt.plot(t,2*qbarrier(t,paramsq[0],paramsq[1],paramsq[2]),colorv[2])
plt.plot(t,2*qbarrier(t,paramsq[3],paramsq[4],paramsq[5]),colorv[3])
plt.plot(xs,params[1,:],colorv[0]+'o',label='burst to eq')
plt.plot(xs,params[3,:],colorv[1]+'o',label='eq to burst')
plt.plot(xs,2*params[1,:],colorv[2]+'o',label='2x burst to eq')
plt.plot(xs,2*params[3,:],colorv[3]+'o',label='2x eq to burst')
plt.legend()
plt.savefig('barriercompdfnew%s.pdf' %(date1+date2))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
matplotlib.rcParams.update({'font.size': 20})
def comp(x,a,b):
return a*x+b
file=open('/home/richard/mastergit/NetBeansProjects/detmodelreal/countanhopfa16.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
cola=np.array(col)
colxa=np.array(colx)
a=174/9.8
a2=82/4
t=np.arange(0,10,0.1)
xs=np.arange(0,10,0.2)
fig, ax=plt.subplots()
plt.xlabel('timestep [ms]')
plt.ylabel('spike count')
#plt.xlim(0,4)
#plt.ylim(1.2,1.4)
#plt.yscale('log')
plt.xscale('log')
plt.plot(colxa,cola)
#plt.plot(t,comp(t,a2,602)/500,label='linear appr')
#plt.legend()
ax.yaxis.set_major_locator(plt.MaxNLocator(3))
plt.tight_layout()
plt.savefig('detmotimeanhopfbig2.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
axs=np.zeros(10000)
ays=np.zeros(10000)
azs=np.zeros(10000)
file=open('/home/richard/mainp2new/train29a202.txt',"r")
x,y,z=[],[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
z.append(float(row[2]))
ax=np.array(x)
ay=np.array(y)
az=np.array(z)
for z in range(0,10000):
axs[z]=ax[z]
ays[z]=ay[z]
azs[z]=az[z]
plt.figure()
plt.ylabel('gating variable n')
plt.xlabel('membrane voltage V')
plt.xlim(-26.1,-26)
plt.ylim(0.447,0.45)
plt.plot(ays,azs)
plt.savefig('mainp2foc.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
vec=np.zeros((5,20))
gdiff=np.zeros((5,19))
deffmitt=np.zeros((5,19))
ii=0
istep=0.25
for x in [20]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/g16m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
for n in range(0,19):
gdiff[ii][n]=(cola[n+1]-cola[n])/istep
ii=ii+1
for x in [25]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/g29m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
for n in range(0,19):
gdiff[ii][n]=(cola[n+1]-cola[n])/istep
ii=ii+1
for x in [30,40,50]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/g7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
for n in range(0,19):
gdiff[ii][n]=(cola[n+1]-cola[n])/istep
ii=ii+1
#for x in [40]:
# col=[]
# for y in range(5,21):
# file=open('/home/richard/outhome/g17a%d%d.txt' % (x,y),"r")
# for k in file:
# row=k.split()
# col.append(row[1])
# cola=np.array(col)
# for z in range(0,16):
# vec[ii][z]=cola[z]
# ii=ii+1
xs=np.arange(-0.75,4.25,0.25)
plt.xlabel('bias current I')
plt.ylabel('firing rate')
#plt.yscale('log')
plt.plot(xs,vec[0,:],label='D=2')
plt.plot(xs,vec[1,:],label='D=2.5')
plt.plot(xs,vec[2,:],label='D=3')
plt.plot(xs,vec[3,:],label='D=4')
plt.plot(xs,vec[4,:],label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('gneurp29m5.pdf')
plt.figure()
xsmitt=np.arange(-0.625,4.125,0.25)
plt.ylabel('dr/dI')
#plt.yscale('log')
plt.plot(xsmitt,gdiff[0,:],label='D=2')
plt.plot(xsmitt,gdiff[1,:],label='D=2.5')
plt.plot(xsmitt,gdiff[2,:],label='D=3')
plt.plot(xsmitt,gdiff[3,:],label='D=4')
plt.plot(xsmitt,gdiff[4,:],label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('drdi29m5.pdf')
ii=0
for x in [20]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/d16m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
for n in range(0,19):
deffmitt[ii][n]=(cola[n+1]+cola[n])/2
ii=ii+1
for x in [25]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/d29m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
for n in range(0,19):
deffmitt[ii][n]=(cola[n+1]+cola[n])/2
ii=ii+1
for x in [30,40,50]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/d7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
for n in range(0,19):
deffmitt[ii][n]=(cola[n+1]+cola[n])/2
ii=ii+1
plt.figure()
plt.ylabel('$D_{eff}$')
plt.yscale('log')
plt.plot(xs,vec[0,:],label='D=2')
plt.plot(xs,vec[1,:],label='D=2.5')
plt.plot(xs,vec[2,:],label='D=3')
plt.plot(xs,vec[3,:],label='D=4')
plt.plot(xs,vec[4,:],label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('dneurp29m5.pdf')
plt.figure()
plt.ylabel('(dr/dI)^2/$D_{eff}$')
plt.yscale('log')
plt.plot(xsmitt,gdiff[0,:]**2/deffmitt[0,:],label='D=2')
plt.plot(xsmitt,gdiff[1,:]**2/deffmitt[1,:],label='D=2.5')
plt.plot(xsmitt,gdiff[2,:]**2/deffmitt[2,:],label='D=3')
plt.plot(xsmitt,gdiff[3,:]**2/deffmitt[3,:],label='D=4')
plt.plot(xsmitt,gdiff[4,:]**2/deffmitt[4,:],label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('snrapp29m5.pdf')
ii=0
for x in [20]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/f16m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
for x in [25]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/f29m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
for x in [30,40,50]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/f7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
plt.figure()
plt.ylabel('Fano factor')
plt.yscale('log')
plt.plot(xs,vec[0,:],label='D=2')
plt.plot(xs,vec[1,:],label='D=2.5')
plt.plot(xs,vec[2,:],label='D=3')
plt.plot(xs,vec[3,:],label='D=4')
plt.plot(xs,vec[4,:],label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('fneurp29m5.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
date='anhopfa2sh'
I=46
v=open('/home/richard/cppworkshop/phasev%s%d.txt' %(date,I),"r")
vv=[]
for k in v:
num = float(k.rstrip())
vv.append(num)
av=np.array(vv)
vl=len(av)
n=open('/home/richard/cppworkshop/phasen%s%d.txt' %(date,I),"r")
vn=[]
for k2 in n:
num = float(k2.rstrip())
vn.append(num)
an=np.array(vn)
nl=len(an)
z=open('/home/richard/cppworkshop/phasez%s%d.txt' %(date,I),"r")
vz=np.zeros((nl,vl))
v=0
for k3 in z:
rowz=k3.split()
rowza=np.array(rowz)
for f in range(0,vl):
vz[v][f]=rowza[f]
v=v+1
def finf(x,v12,k):
return 1/(1+np.exp((v12-x)/k))
def vnc(x,I,v12,k,gL,EL,gNa,ENa,gK,EK):
return (I-gL*(x-EL)-gNa*finf(x,v12,k)*(x-ENa))/(gK*(x-EK))
gL=1
EL=-78
gNa=4
ENa=60
gK=4
EK=-90
km=7
vm=-30
kn=5
vn=-45
tau=1
#b=1.65+0.0261*t
#s=0.76*np.sin((t+56)*np.pi/80)
t=np.arange(av[0],av[-1]+0.01,0.01)
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
plt.contourf(av,an,abs(vz))
plt.colorbar()
plt.plot(t,vnc(t,I,vm,km,gL,EL,gNa,ENa,gK,EK),label='v-nullcline')
plt.plot(t,finf(t,vn,kn),label='n-nullcline')
#plt.plot(t,b,label='barrier')
#plt.plot(t,s,label='barrier2')
#plt.plot(-62.5701,0.00054509, 'bo')
plt.ylim(-0.1,an[-1])
#plt.suptitle('equil. time [ms]')
plt.suptitle('spikes/starting point')
plt.xlabel('initial $V_0$')
plt.ylabel('initial $n_0$')
plt.legend(loc='upper right')
plt.tight_layout()
plt.savefig('contour%s.pdf' %date)
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on July 2, 2019, 5:19 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
using namespace std;
double average(long long int x[],int n);
double square(long long int x[],int n);
double ninf(double V, double k, double Vh);
double init(long long int x[],int n);
double initd(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
ofstream myfile2;
//ofstream myfile3;
myfile.open ("realstatevar145.txt");
myfile2.open ("paramsvar145.txt");
//myfile3.open (argv[4]
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
double I0=0.1; // 0
double dI=0.5;
double gL=0.3; // 8
double EL=-80; // -80
double gNa=1; // 20
double ENa=60; // 60
double gK=0.4; // 9
double EK=-90; // -90
//double gM=5; // 5
/*//slow K+ current
double kinf=5; // 5
double vinf=-20; // -20
double tauM=30; // 20*/
//Na current
double km=14; // 15
double vm=-18; // -20
//fast K+ current
double kn=5; // 5
double vn=-25; // -20
double tau=3; // 0.152
//int N=500000;
int Neq=100000000;
int points=200000;
int sampling=Neq/points;
int j,f;
double dt=0.0005;
double D=1;
//int spikes=100;
//double* spike=new double[spikes];
// simulate equilibrium point
int Nsim=5000000;
double vsim,nfsim,nfsims,vsims,neq,veq;
nfsims=0.4;
vsims=-70;
for(int jsim=0;jsim<Nsim;jsim++){
vsim=I0*dt+vsims-gL*(vsims-EL)*dt-gNa*ninf(vsims,km,vm)*(vsims-ENa)*dt-gK*nfsims*(vsims-EK)*dt;
nfsim=nfsims+(ninf(vsims,kn,vn)-nfsims)*dt/tau;
vsims=vsim;
nfsims=nfsim;
}
veq=vsims;
neq=nfsims;
//simulate instable focus
int Nfoc=20000000;
double dtfoc,vfoc,nffoc,nffocs,vfocs,th,thn;
dtfoc=-dt;
nffocs=0.5;
vfocs=-25;
for(int jfoc=0;jfoc<Nfoc;jfoc++){
vfoc=I0*dtfoc+vfocs-gL*(vfocs-EL)*dtfoc-gNa*ninf(vfocs,km,vm)*(vfocs-ENa)*dtfoc-gK*nffocs*(vfocs-EK)*dtfoc;
nffoc=nffocs+(ninf(vfocs,kn,vn)-nffocs)*dtfoc/tau;
vfocs=vfoc;
nffocs=nffoc;
}
if(vfocs<=0 && vfocs >=-100 && nffocs <= 1 && nffocs >=0){
th=vfocs;
thn=nffocs;
}
else{
th=-25;
thn=0.7;
}
int runs=1;
int Ivalues=1;
long long int count;
double Nav,N2av,T;
double mx,nx,nx2,v,nf,nfs,vs,uGe[Ivalues],uFano[Ivalues],uDeff[Ivalues],Deff,Deff2,deff[Ivalues],vav[Ivalues],Fano[Ivalues],vout[points],nout[points],bvout[points];
int cout[points];
int p=0;
int bv2,sv,svlocked;
sv=0;
//for(s=0;s<Ivalues;s++){
//initd(nfs,runs);
nfs=0.2;
vs=-28;
sv=0;svlocked=0;
count=0;
for(j=0;j<Neq;j++){
v=I0*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt+sqrt(2*D*dt)*n(gen);
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
if(v > th && vs < th){
sv=1;
}
if(sv==1 && nf > thn && nfs < thn){
count=count+1;
sv=0;
bv2=1;
svlocked=0;
}
if(bv2==1 && v<veq+5 && nf<neq+0.1){
if(svlocked==0){
if(v < veq && vs > veq){
svlocked=1;
}}
if(svlocked==0){
if(nf < neq && nfs > neq){
svlocked=-1;
}
}
if(svlocked==1){
if(nf < neq && nfs > neq){
bv2=0;
svlocked=2;
}
}
if(svlocked==-1){
if(v < veq && vs > veq){
bv2=0;
svlocked=2;
}
}
}
if(j==p*sampling){vout[p]=v;
nout[p]=nf;
bvout[p]=bv2;
cout[p]=count;
p=p+1;
}
vs=v;
nfs=nf;
}
for(f=0;f<points;f++){
myfile << f*sampling*dt << " " << vout[f] << " "<< nout[f] << " "<< bvout[f]<<" " << cout[f] << "\n";
}
myfile2 << th<<" "<<thn<<" "<<veq<<" "<<neq;
myfile.close();
myfile2.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(long long int x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
double square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
double init(long long int x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
matplotlib.rcParams.update({'font.size': 14})
#datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
#Dvar=np.array([30])
#lvar=len(Dvar)
#yvar=[4,13,3]
#yvalues=len(yvar)
timefac=1000
date='realanhopf26flog'
date1='realanhopf19flog'
date2='realrinzel15ninv0'
date3='realrinzel15ninv1'
D=[15]
D1=[20,25,30]
D2=[]
D3=[]
Dtot=D+D1+D2+D3
l=len(Dtot)
istart=4
ivalues=12
vecx=np.zeros((l,ivalues))
vec=np.zeros((l,ivalues))
ii=0
#for x in Dvar:
# colvar,colxvar=[],[]
# for kk in range(0,yvalues):
# ystart=1
# jj=0
# while jj < kk:
# ystart=ystart+yvar[jj]
# jj=jj+1
# for y in range(ystart,ystart+yvar[kk]):
# file=open('/home/richard/outhome/d%s%d%d.txt' % (datevar[kk],x,y),"r")
# for k in file:
# row=k.split()
# colxvar.append(float(row[0]))
# colvar.append(float(row[1]))
# colxavar=np.array(colxvar)
# colavar=np.array(colvar)
# for z in range(0,20):
# vec[ii][z]=colavar[z]
# ii=ii+1
offset=np.zeros(l,dtype=int)
for x in D:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D2:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D3:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
#xs=np.arange(-0.08,0.32,0.02)
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ $[s^{-1}]$')
plt.yscale('log')
#plt.xlim(44,47)
#plt.ylim(10**(-3),5*10**5)
#plt.xscale('log')
for n in range(0,l):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='D=%.2f' %(Dtot[n]/100))
plt.plot([46.1, 46.1], [10**(-2), 10**5], color='black', linestyle='-',label='$I_{crit}$')
plt.plot([45.3, 45.3], [10**(-2),10**(5)], color='black', linestyle='--',label='$I_{max}$')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend()
plt.tight_layout()
plt.savefig('dneur31crit%s.pdf' %(date+date1))
vec=np.zeros((l,ivalues))
vecx=np.zeros((l,ivalues))
ii=0
#for x in Dvar:
# colvar,colxvar=[],[]
# for kk in range(0,yvalues):
# ystart=1
# jj=0
# while jj < kk:
# ystart=ystart+yvar[jj]
# jj=jj+1
# for y in range(ystart,ystart+yvar[kk]):
# file=open('/home/richard/outhome/f%s%d%d.txt' % (datevar[kk],x,y),"r")
# for k in file:
# row=k.split()
# colxvar.append(float(row[0]))
# colvar.append(float(row[1]))
# colxavar=np.array(colxvar)
# colavar=np.array(colvar)
# for z in range(0,20):
# vec[ii][z]=colavar[z]
# ii=ii+1
offset2=np.zeros(l,dtype=int)
for x in D:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset2[ii]<y-istart+1:
offset2[ii]=offset2[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset2[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset2[ii]<y-istart+1:
offset2[ii]=offset2[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset2[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D2:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset2[ii]<y-istart+1:
offset2[ii]=offset2[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset2[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D3:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset2[ii]<y-istart+1:
offset2[ii]=offset2[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset2[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
fig, bx=plt.subplots()
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Fano factor F')
#plt.yscale('log')
#plt.xlim(44,47)
#plt.xscale('log')
for n in range(0,l):
nl=round(ivalues-offset2[n])
bx.plot(vecx[n,0:nl],vec[n,0:nl],label='D=%.2f' %(Dtot[n]/100))
bx.plot([46.1, 46.1], [10**(-3), 8*10**3], color='black', linestyle='-',label='$I_{crit}$')
plt.plot([45.3, 45.3], [10**(-3),8*10**(3)], color='black', linestyle='--',label='$I_{max}$')
#plt.plot([46.1, 46.1], [10**(-4), 10**5], color='black', linestyle='-')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend()
bx.set_yscale("log")
locmaj = matplotlib.ticker.LogLocator(base=10.0, subs=(1.0, ), numticks=100)
bx.yaxis.set_major_locator(locmaj)
locmin = matplotlib.ticker.LogLocator(base=10.0, subs=np.arange(2, 10) * .1, numticks=100)
bx.yaxis.set_minor_locator(locmin)
bx.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
plt.tight_layout()
plt.savefig('fneur31crit%s.pdf' %(date+date1))
vec=np.zeros((l,ivalues))
vecx=np.zeros((l,ivalues))
ii=0
offset3=np.zeros(l,dtype=int)
for x in D:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset3[ii]<y-istart+1:
offset3[ii]=offset3[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset3[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset3[ii]<y-istart+1:
offset3[ii]=offset3[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset3[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D2:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset3[ii]<y-istart+1:
offset3[ii]=offset3[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset3[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D3:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset3[ii]<y-istart+1:
offset3[ii]=offset3[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset3[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
N=50000000
dt=0.005
T=N*dt
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countanhopf.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
plt.figure()
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('average firing rate <v> [$s^{-1}$]')
#plt.xlim(44,47)
#plt.yscale('log')
#plt.xscale('log')
plt.plot(colxa[10:38],cola[10:38]/T*timefac,label='spiking firing rate $v_0$',color='black')
for n in range(0,l):
nl=round(ivalues-offset3[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='D=%.2f' %(Dtot[n]/100))
#plt.plot(colxa,vec[0,:],label='D=%.2f' %(D[0]/100))
#plt.plot(xs,vec[3,:],label='D=1.5')
#plt.plot(xs,vec[0,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(colxa,cola,label='D=3e-3')
plt.legend()
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [3,1,2,0]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.tight_layout()
plt.savefig('gneur31critsp%s.pdf' %(date+date1))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def barrier(a,b,x):
return a * x + b
def qbarrier(x,a,b,c):
return a*x**2+b*x+c
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def deff(x,rp,rm,v0,av):
return ((v0+av*x)**2*rp*rm)/((rp+rm)**3)
def v(x,rp,rm,v0,av):
return ((v0+av*x)*rm)/(rp+rm)
def func(x, a, b):
return a * np.exp(-b * x)
def deffana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return ((barrier(av,v0,t))**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
def fanoana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return (2*barrier(av,v0,t)*r(r0p,ap,bp,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**2)
def vana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return barrier(av,v0,t)*r(r0m,am,bm,t,D)/(r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))
def fanofun(x,rp,rm,v0,av):
return 2*deff(x,rp,rm,v0,av)/v(x,rp,rm,v0,av)
def comp(x,b,c,d,e):
return b*x**3+c*x**2+d*x+e
def fit(x,a,b):
return a/x+b
matplotlib.rcParams.update({'font.size': 18})
timefac=1000
D2=[250,300]
D1=[200]
D3=[400,500]
Dvar=[]
D=D1+D2+D3+Dvar
Da=np.array(D)
l1=len(D1)
l2=len(D2)
l3=len(D3)
lvar=len(Dvar)
l=l1+l2+l3+lvar
date1='realrinzelrange26d1'
date3=''
date2='realrinzelrange26d1'
datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
yvar=[4,13,3]
yvalues=len(yvar)
istart=1
ivalues=10
epsilon = 0.00001
#params=4
#dvalues=6
#b=np.zeros(dvalues)
#c=np.zeros(dvalues)
#d=np.zeros(dvalues)
#e=np.zeros(dvalues)
#ii=0
#eqfile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/detmocountparam5.txt','r')
#for k in eqfile:
# col=[]
# row=k.split()
# for lll in range(0,params):
# col.append(float(row[lll]))
# cola=np.array(col)
# b[ii]=cola[0]
# c[ii]=cola[1]
# d[ii]=cola[2]
# e[ii]=cola[3]
# ii=ii+1
#eqfile.close()
file=open('/home/richard/mastergit/pythonplots/arrhenius_analytics/detmocountparamparam.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
cola=np.array(col)
colxa=np.array(colx)
rbtoeq=np.zeros(ivalues)
ubtoeq=np.zeros(ivalues)
reqtob=np.zeros(ivalues)
ueqtob=np.zeros(ivalues)
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/param%s%d.txt' %(date1+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
rbtoeq[k2]=x[0]
ubtoeq[k2]=x[1]
reqtob[k2]=x[2]
ueqtob[k2]=x[3]
def rred(r0,U,D):
return r0*np.exp(-U/D)
def deffred(rp,up,rm,um,v,D):
return (v**2*rred(rp,up,D)*rred(rm,um,D))/((rred(rp,up,D)+rred(rm,um,D))**3)
def vred(rp,up,rm,um,v,D):
return v*rred(rm,um,D)/(rred(rp,up,D)+rred(rm,um,D))
def fanored(rp,up,rm,um,v,D):
return 2*deffred(rp,up,rm,um,v,D)/vred(rp,up,rm,um,v,D)
date2='realrinzelrange26d1'
date3='realrinzelrangeshort26d1'
date1='realrinzelrangelong26d1'
ii=0
istart1=1
ivalues1=10
vec=np.zeros((l,ivalues1))
for x in D1:
col1,colx1=[],[]
for y in range(istart1,istart1+ivalues1):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,ivalues1):
vec[ii][z]=cola1[z]
ii=ii+1
istart2=1
ivalues2=10
for x in D2:
col2,colx2=[],[]
for y in range(istart2,istart2+ivalues2):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx2.append(float(row[0]))
col2.append(float(row[1]))
colxa2=np.array(colx2)
cola2=np.array(col2)
for z in range(0,ivalues2):
vec[ii][z]=cola2[z]
ii=ii+1
istart3=1
ivalues3=10
for x in D3:
col3,colx3=[],[]
for y in range(istart3,istart3+ivalues3):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx3.append(float(row[0]))
col3.append(float(row[1]))
colxa3=np.array(colx3)
cola3=np.array(col3)
for z in range(0,ivalues3):
vec[ii][z]=cola3[z]
ii=ii+1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/d%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
vec[ii][z]=colavar[z]
ii=ii+1
xs=np.arange(-21.25+istart1,-21.25+istart1+ivalues1)*0.8
pv=np.arange(0,ivalues)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ [$10^3s^{-1}$]')
#plt.xlim(0,3.5)
#plt.ylim(5*10**(-2),2*10**3)
plt.yscale('log')
colorv=[ '#1f77b4', '#ff7f0e', '#2ca02c','#d62728','#9467bd']
#for n in range(0,l):
# plt.plot(t,deffana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#for n in range(0,l):
# plt.plot(t,deffana(axx[2],axx[5],axx[0],axx[3],axx[1],axx[4],t,Da[n]/100,av,v0),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,1):
plt.plot(xs,vec[n,:]*timefac,'o',color=colorv[n],label='D=%.0f*' %(Da[n]/10))
for n in range(1,l):
plt.plot(xs,vec[n,:]*timefac,'o',color=colorv[n],label='D=%.0f' %(Da[n]/10))
for n in range(0,l):
#bv=b[n+1]
#cv=c[n+1]
#dv=d[n+1]
#ev=e[n+1]
plt.plot((pv-20.25)*0.8,deffred(rbtoeq[pv],ubtoeq[pv],reqtob[pv],ueqtob[pv],comp((pv-20.25)*0.8,fit(Da[n]/10,colxa[0],cola[0]),fit(Da[n]/10,colxa[1],cola[1]),fit(Da[n]/10,colxa[2],cola[2]),fit(Da[n]/10,colxa[3],cola[3])),Da[n]/10)*timefac,colorv[n])
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,3,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend(bbox_to_anchor=(0.4, 0.6))
plt.tight_layout()
plt.savefig('dcompdfpwnew2big%s.pdf' %(date1+date2))
g=np.zeros((l,ivalues1))
ii=0
for x in D1:
col1,colx1=[],[]
for y in range(istart1,istart1+ivalues1):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,ivalues1):
g[ii][z]=cola1[z]
ii=ii+1
for x in D2:
col2,colx2=[],[]
for y in range(istart2,istart2+ivalues2):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx2.append(float(row[0]))
col2.append(float(row[1]))
colxa2=np.array(colx2)
cola2=np.array(col2)
for z in range(0,ivalues2):
g[ii][z]=cola2[z]
ii=ii+1
for x in D3:
col3,colx3=[],[]
for y in range(istart3,istart3+ivalues3):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx3.append(float(row[0]))
col3.append(float(row[1]))
colxa3=np.array(colx3)
cola3=np.array(col3)
for z in range(0,ivalues3):
g[ii][z]=cola3[z]
ii=ii+1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/g%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
g[ii][z]=colavar[z]
ii=ii+1
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('firing rate r [$10^3s^{-1}$]')
#plt.yscale('log')
colorv=[ '#1f77b4', '#ff7f0e', '#2ca02c','#d62728','#9467bd']
#for n in range(0,l):
# plt.plot(t,vana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,1):
plt.plot(xs,g[n,:]*timefac,'o',color=colorv[n],label='D=%.0f*' %(Da[n]/10))
for n in range(1,l):
plt.plot(xs,g[n,:]*timefac,'o',color=colorv[n],label='D=%.0f' %(Da[n]/10))
for n in range(0,l):
#bv=b[n+1]
#cv=c[n+1]
#dv=d[n+1]
#ev=e[n+1]
plt.plot((pv-20.25)*0.8,vred(rbtoeq[pv],ubtoeq[pv],reqtob[pv],ueqtob[pv],comp((pv-20.25)*0.8,fit(Da[n]/10,colxa[0],cola[0]),fit(Da[n]/10,colxa[1],cola[1]),fit(Da[n]/10,colxa[2],cola[2]),fit(Da[n]/10,colxa[3],cola[3])),Da[n]/10)*timefac,colorv[n])
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,3,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend()
plt.tight_layout()
plt.savefig('gcompdfpwnew2big%s.pdf' %(date1+date2))
fano=np.zeros((l,ivalues1))
ii=0
for x in D1:
col1,colx1=[],[]
for y in range(istart1,istart1+ivalues1):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,ivalues1):
fano[ii][z]=cola1[z]
ii=ii+1
for x in D2:
col2,colx2=[],[]
for y in range(istart2,istart2+ivalues2):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx2.append(float(row[0]))
col2.append(float(row[1]))
colxa2=np.array(colx2)
cola2=np.array(col2)
for z in range(0,ivalues2):
fano[ii][z]=cola2[z]
ii=ii+1
for x in D3:
col3,colx3=[],[]
for y in range(istart3,istart3+ivalues3):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx3.append(float(row[0]))
col3.append(float(row[1]))
colxa3=np.array(colx3)
cola3=np.array(col3)
for z in range(0,ivalues3):
fano[ii][z]=cola3[z]
ii=ii+1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/f%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
fano[ii][z]=colavar[z]
ii=ii+1
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Fano factor')
plt.yscale('log')
colorv=[ '#1f77b4', '#ff7f0e', '#2ca02c','#d62728','#9467bd']
t=np.arange(-0.1,0.3,0.01)
#for n in range(0,l):
# plt.plot(t,fanoana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,1):
plt.plot(xs,fano[n,:],'o',color=colorv[n],label='D=%.0f*' %(Da[n]/10))
for n in range(1,l):
plt.plot(xs,fano[n,:],'o',color=colorv[n],label='D=%.0f' %(Da[n]/10))
for n in range(0,l):
#bv=b[n+1]
#cv=c[n+1]
#dv=d[n+1]
#ev=e[n+1]
plt.plot((pv-20.25)*0.8,fanored(rbtoeq[pv],ubtoeq[pv],reqtob[pv],ueqtob[pv],comp((pv-20.25)*0.8,fit(Da[n]/10,colxa[0],cola[0]),fit(Da[n]/10,colxa[1],cola[1]),fit(Da[n]/10,colxa[2],cola[2]),fit(Da[n]/10,colxa[3],cola[3])),Da[n]/10),colorv[n])
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,3,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend()
plt.tight_layout()
plt.savefig('fcompdfpwnew2big%s.pdf' %(date1+date2))
#t=np.arange(-12,-9,0.01)
#plt.figure()
#plt.xlabel('bias current I $[\mu A/cm^2]$')
#plt.ylabel('potential barrier')
#plt.plot(t,barrier(t,params2[0],params2[1]),'y')
#plt.plot(t,barrier(t,params2[2],params2[3]),'y')
#plt.plot(t,2*barrier(t,params2[0],params2[1]),'y')
#plt.plot(t,2*barrier(t,params2[2],params2[3]),'y')
#plt.plot(t,qbarrier(t,paramsq[0],paramsq[1],paramsq[2]),colorv[0])
#plt.plot(t,qbarrier(t,paramsq[3],paramsq[4],paramsq[5]),colorv[1])
#plt.plot(t,2*qbarrier(t,paramsq[0],paramsq[1],paramsq[2]),colorv[2])
#plt.plot(t,2*qbarrier(t,paramsq[3],paramsq[4],paramsq[5]),colorv[3])
#plt.plot(xs,params[1,:],colorv[0]+'o',label='burst to eq')
#plt.plot(xs,params[3,:],colorv[1]+'o',label='eq to burst')
#plt.plot(xs,2*params[1,:],colorv[2]+'o',label='2x burst to eq')
#plt.plot(xs,2*params[3,:],colorv[3]+'o',label='2x eq to burst')
#plt.legend()
#plt.savefig('barriercompdfnew%s.pdf' %(date1+date2))
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on January 8, 2019, 12:48 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
using namespace std;
double average(long long int x[],int n);
double square(long long int x[],int n);
double ninf(double V, double k, double Vh);
double init(long long int x[],int n);
double initd(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
ofstream myfile2;
ofstream myfile3;
myfile.open ("deffD5.txt");
myfile2.open ("vavD5.txt");
myfile3.open ("fanoD5.txt");
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
double I0=0; // 0
double dI=0.2;
double gL=8; // 8
double EL=-80; // -80
double gNa=20; // 20
double ENa=60; // 60
double gK=9; // 9
double EK=-90; // -90
double gM=5; // 5
//slow K+ current
double kinf=5; // 5
double vinf=-20; // -20
double tauM=30; // 20
//Na current
double km=15; // 15
double vm=-20; // -20
//fast K+ current
double kn=5; // 5
double vn=-25; // -20
double tau=0.152; // 0.152
long int N=5000000;
int points=1000;
int sample=N/points;
int j,f;
double dt=0.00001;
double D=5;
//int spikes=100;
//double* spike=new double[spikes];
double th=-25;
int runs=50;
long long int count[runs],sqcount[runs];
double Nav[points],N2av[points],vav[points],Fano[points];
double v[runs],nf[runs],nfs[runs],vs[runs],Deff[points];
int p=1;
Deff[0]=0;
initd(nfs,runs);
initd(vs,runs);
init(count,runs);
for(j=0;j<N;j++){
for(int a=0;a<runs;a++){
v[a]=I0*dt+vs[a]-gL*(vs[a]-EL)*dt-gNa*ninf(vs[a],km,vm)*(vs[a]-ENa)*dt-gK*nfs[a]*(vs[a]-EK)*dt+sqrt(2*D*dt)*n(gen);
nf[a]=nfs[a]+(ninf(vs[a],kn,vn)-nfs[a])*dt/tau;
if(v[a] > th && vs[a] < th){
count[a]=count[a]+1;
}
vs[a]=v[a];
nfs[a]=nf[a];
}
if(j==p*sample){
Nav[p]=average(count,runs);
for(int j2=0;j2<runs;j2++){
sqcount[j2]=count[j2]*count[j2];
}
N2av[p]=average(sqcount,runs);
Deff[p]=(N2av[p]-Nav[p]*Nav[p])/(2*j*dt);
vav[p]=Nav[p]/(j*dt);
Fano[p]=2*Deff[p]/vav[p];
p++;
}
}
for(f=0;f<points;f++){
myfile << f*sample*dt << " " << Deff[f] << "\n";
}
myfile.close();
for(f=0;f<points;f++){
myfile2 << f*sample*dt << " " << vav[f] << "\n";
}
myfile2.close();
for(f=0;f<points;f++){
myfile3 << f*sample*dt << " " << Fano[f] << "\n";
}
myfile3.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(long long int x[],int n){
int i;
double sum=0;
for(i=0;i<n;i++){
sum=sum+x[i];
}
double av=sum/n;
return av;
}
double square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
double init(long long int x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b):
return a * np.exp(-b * x)
def func2(x, a, b):
return a * x + b
def func3(x, a):
return a
def funcrate(x,ap,am,bp,bm):
return 2*am * np.exp(-bm * x)*ap * np.exp(-bp * x)/(am * np.exp(-bm * x)+ap * np.exp(-bp * x))
params2=np.zeros(6)
params=np.zeros((4,20))
eqtottime=np.zeros((3,20))
eqreltime=np.zeros((3,20))
btottime=np.zeros((3,20))
breltime=np.zeros((3,20))
ii=0
dt=0.00001
N2=100000000
Neq2=10000000
Ndiff2=N2-Neq2
runs=100
repetitions=100
for x in [30,40,50]:
for y in range(1,21):
times,avalues,jrvalues,j2values,state=[],[],[],[],[]
file=open('/home/richard/outhome/time7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
avalues.append(float(row[1]))
jrvalues.append(float(row[2]))
j2values.append(float(row[3]))
state.append(float(row[4]))
j2valuesa=np.array(j2values)
jrvaluesa=np.array(jrvalues)
avaluesa=np.array(avalues)
statea=np.array(state)
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff2>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff2:
inteq[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff2+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff2>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff2:
intb[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff2+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff2>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff2:
intb[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff2+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff2>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff2:
inteq[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff2+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
counts=counteq+countb
countsrel=counts/Ndiff2
eqtot=np.sum(inteqt)
btot=np.sum(intbt)
eqrel=eqtot/(eqtot+btot)
brel=btot/(eqtot+btot)
eqtottime[ii][y-1]=eqtot/counteq
btottime[ii][y-1]=btot/countb
eqreltime[ii][y-1]=eqrel
breltime[ii][y-1]=brel
ii=ii+1
inteqt[c]=inteq[c]
for k2 in range(0,20):
plt.figure()
xs=[1/3,1/4,1/5]
xv=np.arange(0.1,0.5,0.01)
popt,pcov = curve_fit(func, xs, 1/btottime[:,k2])
params[0][k2]=popt[0]
params[1][k2]=popt[1]
ap=params[0][k2]
bp=params[1][k2]
popt,pcov = curve_fit(func, xs, 1/eqtottime[:,k2])
params[2][k2]=popt[0]
params[3][k2]=popt[1]
am=params[2][k2]
bm=params[3][k2]
eqfile = open('paramsh16m%d.txt' % (k2),'w')
for k3 in range(0,4):
eqfile.write('%.6f\n'%params[k3][k2])
eqfile.close()
plt.figure()
plt.xlabel('inverse noise intensity 1/D')
plt.ylabel('total transition rate')
plt.yscale('log')
plt.plot(xs,(2*(1/btottime[:,k2])*(1/eqtottime[:,k2]))/(1/eqtottime[:,k2]+1/btottime[:,k2]),'bo',label='simulation')
plt.plot(xv,funcrate(xv,ap,am,bp,bm),label='theory')
plt.savefig('cortimeshort16m%d.pdf' %(k2))
plt.figure()
xold=np.arange(-0.75,4.25,0.25)
plt.xlabel('bias current I')
plt.ylabel('correlation time')
plt.yscale('log')
plt.plot(xold,1/(1/btottime[0,:]+1/eqtottime[0,:]),label='D=3')
plt.plot(xold,1/(1/btottime[1,:]+1/eqtottime[1,:]),label='D=4')
plt.plot(xold,1/(1/btottime[2,:]+1/eqtottime[2,:]),label='D=5')
plt.savefig('altcortimeshort16m.pdf')
plt.figure()
xnew=np.arange(-0.75,4.25,0.25)
plt.xlabel('bias current')
plt.ylabel('prefactor')
plt.plot(xnew,params[0,:],label='burst to eq')
plt.plot(xnew,params[2,:],label='eq to burst')
plt.legend()
plt.savefig('prefacshort16m.pdf')
plt.figure()
plt.xlabel('bias current')
plt.ylabel('potential barrier')
plt.plot(xnew,params[1,:],label='burst to eq')
plt.plot(xnew,params[3,:],label='eq to burst')
plt.plot(xnew,2*params[1,:],label='2x burst to eq')
plt.plot(xnew,2*params[3,:],label='2x eq to burst')
plt.legend()
plt.savefig('barriershort216m.pdf')
eqfile3 = open('barrierex16m.txt','w')
for k3 in range(0,11):
eqfile3.write('%.6f %6.f %6.f %6.f %6.f\n'%(xnew[k3],params[0][k3],params[1][k3],params[2][k3],params[3][k3]))
eqfile3.close()
popt,pcov = curve_fit(func2, xnew, params[1,:])
params2[0]=popt[0]
params2[1]=popt[1]
popt,pcov = curve_fit(func2, xnew, params[3,:])
params2[3]=popt[0]
params2[4]=popt[1]
popt,pcov = curve_fit(func3, xnew, params[0,:])
params2[2]=popt[0]
popt,pcov = curve_fit(func3, xnew, params[2,:])
params2[5]=popt[0]
eqfile2 = open('parambarriershort16m.txt','w')
for k4 in range(0,6):
eqfile2.write('%.6f\n'%params2[k4])
eqfile2.close()
t=np.arange(0.5,3,0.01)
plt.figure()
plt.xlabel('bias current')
plt.ylabel('potential barrier')
plt.plot(t,func2(t,params2[0],params2[1]),'y')
plt.plot(t,func2(t,params2[3],params2[4]),'y')
plt.plot(t,2*func2(t,params2[0],params2[1]),'y')
plt.plot(t,2*func2(t,params2[3],params2[4]),'y')
plt.plot(xnew,params[1,:],label='burst to eq')
plt.plot(xnew,params[3,:],label='eq to burst')
plt.plot(xnew,2*params[1,:],label='2x burst to eq')
plt.plot(xnew,2*params[3,:],label='2x eq to burst')
plt.legend()
plt.savefig('barriercompshort16m.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on December 28, 2018, 12:03 AM
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cmath>
#include <random>
#include <map>
#include <string>
#include <iomanip>
using namespace std;
int main(int argc, char** argv) {
ofstream myfile;
ofstream myfile2;
myfile.open ("diff.txt");
myfile2.open ("gesch.txt");
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
int N=10000000;//Anzahl Zeitschritte
double v[100];
double x[100];
double deff;
double deff2;
double dt=0.01;
double F=0.7;//kleinste Kraft
double kT=0.056;
double gam=0.4;
int h,i,j,l,a,b,c,a2,b2,c2,d2,f,g;
double vavt[1000],xavt[1000],x2avt[1000],defft[1000];
//Initialisierung von x
for(h=0;h<100;h++){
x[h]=0;
}
//Initialisierung von v
for(i=0;i<100;i++){
v[i]=0;
}
d2=0;
//Schleife über alle Zeitschritte
for(j=0;j<N;j++){
if(j==(d2+1)*10000-1){
d2=d2+1;
for(l=0;l<100;l++){
v[l]=v[l]-gam*v[l]*dt+F*dt-sin(x[l])*dt+sqrt(2*kT*gam*dt)*n(gen);
x[l]=x[l]+v[l]*dt;
}
double sum4=0;
for(a2=0;a2<100;a2++){
sum4=sum4+v[a2];
}
vavt[d2]=sum4/100;//mittl Geschwindigkeit
double sum5=0;
for(b2=0;b2<100;b2++){
sum5=sum5+x[b2];
}
xavt[d2]=sum5/100;//mittl Position
double sum6=0;
for(c2=0;c2<100;c2++){
sum6=sum6+x[c2]*x[c2];
}
x2avt[d2]=sum6/100;//Mittel der Positionsquadrate
defft[d2]=(x2avt[d2]-xavt[d2]*xavt[d2])/(2*(j+1)*dt);//Diffusionskoeffizient
}
else{
for(l=0;l<100;l++){
v[l]=v[l]-gam*v[l]*dt+F*dt-sin(x[l])*dt+sqrt(2*kT*gam*dt)*n(gen);
x[l]=x[l]+v[l]*dt;
}
}
}
vavt[0]=0;xavt[0]=0;x2avt[0]=0;defft[0]=0;
for(f=0;f<1000;f++){
myfile << f*100 << ' ' << defft[f] <<"\n";
}
for(g=0;g<1000;g++){
myfile2 << g*100 << ' ' << vavt[g] << "\n";
}
myfile.close();
myfile2.close();
return 0;
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def finf(t,v12,k12):
return 1/(1+np.exp((v12-t)/k12))
matplotlib.rcParams.update({'font.size': 22})
t=np.arange(-70,30,0.01)
plt.figure()
plt.xlabel('membrane voltage V')
plt.ylabel('gating variable n')
plt.plot(t,finf(t,-30,7),label='$m_\infty(V)$')
plt.plot(t,finf(t,-45,5),label='$n_\infty(V)$')
plt.legend()
plt.tight_layout()
plt.savefig('gatinganhopf.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
from scipy.optimize import curve_fit
def func(x, a, b):
return a * np.exp(-b * x)
def r(r0,U,D):
return r0*np.exp(-U/D)
def snr(r0p,r0m,up,um,ups,ums,D,av,v0):
return (r(r0m,um,D)*(r(r0p,up,D)+r(r0m,um,D))/(v0**2*r(r0p,up,D)))*(((ups-ums)*r(r0p,up,D)*v0)/(D*(r(r0p,up,D)+r(r0m,um,D)))+av)**2
def rprime(r0,r0s,Us,D):
return (r0s/r0-Us/D)
def snrcor(r0p,r0m,up,um,ups,ums,D,av,v0,r0ps,r0ms):
return ((av*r(r0m,um,D)*(r(r0m,um,D)+r(r0p,up,D))+v0*(rprime(r0m,r0ms,ums,D)-rprime(r0p,r0ps,ups,D))*r(r0p,up,D)*r(r0m,um,D))**2)/((r(r0p,up,D)+r(r0m,um,D))*v0**2*r(r0p,up,D)*r(r0m,um,D))
matplotlib.rcParams.update({'font.size': 18}) #18
#date3='newrealfast11jjem2sh'
#date2='newrealfast19jjem2st'
date3='realfast9acoarsetf'
date2='realfast23mtf'
ivalues=20
l=5
#D1=[35]
#D2=[45]
#D3=[40,50]
#Dvar=[30]
#D=D1+D2+D3+Dvar
D=[30,35,40,45,50]
Da=np.array(D)
btoeq=np.zeros((l,ivalues))
eqtob=np.zeros((l,ivalues))
params=np.zeros((4,ivalues))
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/rate%s%d.txt' %(date3+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,l):
btoeq[k][k2]=1/ax[k]
eqtob[k][k2]=1/ax[k+l]
xs=np.zeros(l)
for b in range(0,l):
xs[b]=100/Da[b]
for k2 in range(0,ivalues):
popt,pcov = curve_fit(func, xs, btoeq[:,k2])
params[0][k2]=popt[0]
params[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2])
params[2][k2]=popt[0]
params[3][k2]=popt[1]
rbte=np.mean(params[0,:])
retb=np.mean(params[2,:])
ups=np.zeros(ivalues-2)
ums=np.zeros(ivalues-2)
r0ms=np.zeros(ivalues-2)
r0ps=np.zeros(ivalues-2)
istart=1
istep=0.02
xnew=np.arange(-5+istart,-5+istart+ivalues)*istep
for k3 in range(0,ivalues-2):
ups[k3]=(params[1][k3+2]-params[1][k3])/(2*istep)
ums[k3]=(params[3][k3+2]-params[3][k3])/(2*istep)
r0ps[k3]=(params[0][k3+2]-params[0][k3])/(2*istep)
r0ms[k3]=(params[2][k3+2]-params[2][k3])/(2*istep)
N0=50000000
dt0=0.0005
T0=N0*dt0
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countI9a.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
cola=np.array(col)/T0
colxa=np.array(colx)
lenx=len(colxa)
ratenew=np.zeros(ivalues)
dratenew=np.zeros(ivalues)
for ls in range(0,ivalues):
x=xnew[ls]
for m in range(0,lenx-1):
b=colxa[m+1]
a=colxa[m]
if x<=b and x>a:
ratenew[ls]=cola[m]+((x-a)/(b-a))*(cola[m+1]-cola[m])
dratenew[ls]=(cola[m+1]-cola[m])/(b-a)
break
ll=0
SNR=np.zeros((l,ivalues))
snrfile=open('snrealfile2.txt','r')
for s in snrfile:
row=s.split()
for t in range(0,ivalues):
SNR[ll][t]=float(row[t])
ll=ll+1
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('signal-to-noise ratio SNR')
Dtot=np.array([25,30,35,45])
#Dtot=np.array([2,3,4,5])
l2=len(Dtot)
t=np.arange(-18,-8,0.1)
#xs=np.arange(-21.25+istart,-21.25+istart+ivalues)*0.8
#xs=np.arange(-20+istart,-20+istart+ivalues)*0.6
plt.yscale('log')
#plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
plt.ylim(10**(-5),7*10**(-2))
#colorv=['r','y','c','g','k','b'] # 6 colors
colorv=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
#colorv=['y','g','b'] # 3 colors
#colorv=['y','c','g','k','b'] # 5 colors
#plt.plot(xnew[1:ivalues-1],snrcor(params[0,1:ivalues-1],params[2,1:ivalues-1],params[1,1:ivalues-1],params[3,1:ivalues-1],ups,ums,15*0.01,dratenew[1:ivalues-1],ratenew[1:ivalues-1],r0ps,r0ms)/8,'purple',label='D=%.2f' %(15*0.01))
for n in range(0,1):
plt.plot(xnew,SNR[n,:],color=colorv[n],label='D=%.2f*' %(Dtot[n]*0.01))
#plt.plot(xnew[1:ivalues-1],snrcor(params[0,1:ivalues-1],params[2,1:ivalues-1],params[1,1:ivalues-1],params[3,1:ivalues-1],ups,ums,Dtot[n]*0.01,dratenew[1:ivalues-1],ratenew[1:ivalues-1],r0ps,r0ms)/8,colorv[n],label='D=%.2f' %(Dtot[n]*0.01))
for n in range(1,l2):
plt.plot(xnew,abs(SNR[n,:]),color=colorv[n],label='D=%.2f' %(Dtot[n]*0.01))
#plt.plot(xnew[1:ivalues-1],snrcor(params[0,1:ivalues-1],params[2,1:ivalues-1],params[1,1:ivalues-1],params[3,1:ivalues-1],ups,ums,Dtot[n]*0.01,dratenew[1:ivalues-1],ratenew[1:ivalues-1],r0ps,r0ms)/8,colorv[n],label='D=%.2f' %(Dtot[n]*0.01))
#plt.plot([0.163, 0.163], [10**(-74), 10**(45)], color='black', linestyle='-',label='$I_{crit}$')
plt.plot([0.163, 0.163], [5*10**(-7), 5], color='black', linestyle='-')#,label='$I_{crit}$')
plt.plot([0.06, 0.06], [5*10**(-7), 5], color='black', linestyle='--')#,label='$I_{max}$')
#plt.text(0.07,10*10**(-6),'$I_{max}$',fontsize='20')
#plt.text(0.173,10*10**(-6),'$I_{crit}$',fontsize='20')
plt.xlim(-0.07,0.29)
#plt.plot(xnew,ratenew,colorv[n])
plt.legend(loc='upper left')
plt.tight_layout()
#plt.savefig('snrtwostateneurcorsh5big.pdf')
#plt.savefig('snrpredneur2big.pdf')
plt.savefig('snrsaddlenodedef.pdf')
#plt.savefig('snrinzelonly.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def finf(x,v12,k):
return 1/(1+np.exp((v12-x)/k))
def vnc(x,I,v12,k,gL,EL,gNa,ENa,gK,EK):
return (I-gL*(x-EL)-gNa*finf(x,v12,k)*(x-ENa))/(gK*(x-EK))
plt.axes().set_aspect(1)
style="Simple,tail_width=0.5,head_width=4,head_length=8"
kw = dict(arrowstyle=style, color="k")
a1 = patches.FancyArrowPatch((-17,0.85), (-40,0.3),connectionstyle="arc3,rad=.2",**kw )
a2 = patches.FancyArrowPatch((-40,0.23), (-36,0.1),connectionstyle="arc3,rad=.5",**kw)
a3 = patches.FancyArrowPatch((-34,0.1), (-11,0.72),connectionstyle="arc3,rad=.5", **kw)
a4 = patches.FancyArrowPatch((-11,0.75), (-15,0.85),connectionstyle="arc3,rad=.4", **kw)
I=0
gL=0.3
EL=-80
gNa=1
ENa=60
gK=0.4
EK=-90
km=14
vm=-18
kn=5
vn=-25
tau=3
t=np.arange(-75,-10,0.1)
plt.figure()
for a in [a1,a2,a3,a4]:
plt.gca().add_patch(a)
plt.xlabel('membrane voltage V [mV]')
plt.ylabel('gating variable n')
plt.plot(t,vnc(t,I,vm,km,gL,EL,gNa,ENa,gK,EK),label='v-nullcline')
plt.plot(t,finf(t,vn,kn),label='n-nullcline')
plt.plot(-69.108,finf(-69.108,vn,kn),'bo')
plt.plot(-55.8294,finf(-55.8294,vn,kn),'o',color='purple')
plt.plot(-21.7225,finf(-21.7225,vn,kn),'ro')
plt.text(-69.108,finf(-69.108,vn,kn)+0.02,'$P_1$')
plt.text(-55.8294-2,finf(-55.8294,vn,kn)+0.02,'$P_2$')
plt.text(-21.7225-3,finf(-21.7225,vn,kn),'$P_3$')
plt.xlim((-75,-10))
plt.ylim((-0.1,0.9))
plt.legend()
plt.savefig('inapikrealncwnp.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
style="Simple,tail_width=0.5,head_width=4,head_length=8"
kw = dict(arrowstyle=style, color="k")
a1 = patches.FancyArrowPatch((5,1), (8,1),connectionstyle="arc3,rad=-.7",**kw )
a2 = patches.FancyArrowPatch((9.48,0.1), (3.2,0.1),connectionstyle="arc3,rad=0",**kw)
a3 = patches.FancyArrowPatch((3.2,0.2), (5,1),connectionstyle="arc3,rad=.3", **kw)
a4 = patches.FancyArrowPatch((8,1), (9.48,0.2),connectionstyle="arc3,rad=.3", **kw)
t=np.arange(2,10.5,0.001)
vnc=-5/2*np.sin(t)
xnc=0*t
plt.figure()
for a in [a1,a2,a3,a4]:
plt.gca().add_patch(a)
plt.xlabel('position x')
plt.ylabel('velocity V')
plt.plot(t,xnc,label='x-Nullcline')
plt.plot(t,vnc,label='v-Nullcline')
plt.legend()
plt.savefig('nullclinemm2.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def finf(x,v12,k):
return 1/(1+np.exp((v12-x)/k))
def vnc(x,I,v12,k,gL,EL,gNa,ENa,gK,EK):
return (I-gL*(x-EL)-gNa*finf(x,v12,k)*(x-ENa))/(gK*(x-EK))
I=46
gL=1
EL=-78
gNa=4
ENa=60
gK=4
EK=-90
km=7
vm=-30
kn=5
vn=-45
tau=1
file=open('/home/richard/mastergit/NetBeansProjects/inapik/inaprealanhopfnb.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
#ayi=ay[::-1]
t=np.arange(-55,-45,0.1)
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
plt.xlabel('time [s]')
plt.ylabel('membrane voltage V [mV]')
#plt.ylabel('gating variable n')
#plt.plot(t,vnc(t,I,vm,km,gL,EL,gNa,ENa,gK,EK),label='v-nullcline')
#plt.plot(t,finf(t,vn,kn),label='n-nullcline')
#plt.gcf().subplots_adjust(left=0.15)
#plt.plot(abs(ax[0:1000])/1000,ayi[0:1000],'black')
plt.plot(ax[0:1000]/1000,ay[0:1000],'black')
#plt.xlim(0,0.1)
#plt.xlim(0,0.05)
#plt.ylim(0.1,0.4)
#plt.legend()
plt.tight_layout()
plt.savefig('inaprealanhopfnbvtblack.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on July 2, 2019, 5:19 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
using namespace std;
double average(long long int x[],int n);
double square(long long int x[],int n);
double ninf(double V, double k, double Vh);
double an(double V);
double bn(double V);
double am(double V);
double bm(double V);
double ah(double V);
double bh(double V);
double init(long long int x[],int n);
double initd(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
//ofstream myfile2;
//ofstream myfile3;
myfile.open ("realstatehh.txt");
//myfile2.open ("statechange.txt");
//myfile3.open (argv[4]
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
double mu=6.5; // 0
double dI=0.5;
double gL=0.3; // 8
double EL=10; // -80
double gNa=120; // 20
double ENa=115; // 60
double gK=36; // 9
double EK=-12; // -90
//double gM=5; // 5
/*//slow K+ current
double kinf=5; // 5
double vinf=-20; // -20
double tauM=30; // 20*/
//Na current
//int N=500000;
int Neq=30000000;
int points=100000;
int sampling=Neq/points;
int j,f;
double dt=0.0005;
double D=0.5;
//int spikes=100;
//double* spike=new double[spikes];
int runs=1;
int Ivalues=1;
long long int sqcount[runs];
double Nav,N2av,T;
double v[runs],nf[runs],nfs[runs],vs[runs],mf[runs],mfs[runs],hf[runs],hfs[runs],uGe[Ivalues],uFano[Ivalues],uDeff[Ivalues],Deff,Deff2,deff[Ivalues],vav[Ivalues],Fano[Ivalues],vout[points],nout[points],mout[points],hout[points],lastcount,prelastchange,lastchange;
int p=0;
int bv,bvp,sv;
lastcount=0;
prelastchange=0;lastchange=0;
sv=0;
//for(s=0;s<Ivalues;s++){
//initd(nfs,runs);
mfs[0]=0.06;
hfs[0]=0.6;
nfs[0]=0.35;
vs[0]=0;
for(j=0;j<Neq;j++){
for(int a=0;a<runs;a++){
v[a]=mu*dt+vs[a]+gL*(EL-vs[a])*dt+gNa*pow(mfs[a],3)*hfs[a]*(ENa-vs[a])*dt+gK*pow(nfs[a],4)*(EK-vs[a])*dt+sqrt(2*D*dt)*n(gen);
nf[a]=nfs[a]+an(vs[a])*(1-nfs[a])*dt-bn(vs[a])*nfs[a]*dt;
mf[a]=mfs[a]+am(vs[a])*(1-mfs[a])*dt-bm(vs[a])*mfs[a]*dt;
hf[a]=hfs[a]+ah(vs[a])*(1-hfs[a])*dt-bh(vs[a])*hfs[a]*dt;
if(j==p*sampling){vout[p]=v[a];
nout[p]=nf[a];
mout[p]=mf[a];
hout[p]=hf[a];
p=p+1;
}
vs[a]=v[a];
nfs[a]=nf[a];
hfs[a]=hf[a];
mfs[a]=mf[a];
}
}
for(f=0;f<points;f++){
myfile << f*sampling*dt << " " << vout[f] << " "<< nout[f] <<" " << mout[f] << " "<< hout[f] << "\n";
}
myfile.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(long long int x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
double square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
double init(long long int x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
double an(double V){
double f=(10-V)/(100*(exp((10-V)/10)-1));
return f;
}
double am(double V){
double f=(25-V)/(10*(exp((25-V)/10)-1));
return f;
}
double ah(double V){
double f=7*exp(-V/20)/100;
return f;
}
double bn(double V){
double f=exp(-V/80)/8;
return f;
}
double bm(double V){
double f=4*exp(-V/18);
return f;
}
double bh(double V){
double f=1/(exp((30-V)/10)+1);
return f;
}<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on December 28, 2018, 12:03 AM
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cmath>
#include <random>
#include <map>
#include <string>
#include <iomanip>
using namespace std;
int main(int argc, char** argv) {
ofstream myfile;
ofstream myfile2;
myfile.open ("difff.txt");
myfile2.open ("geschf.txt");
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
int N=50000000;//Anzahl Zeitschritte
double v[100],vs[100];
double x[100],xs[100];
double deff;
double deff2;
double dt=0.01;
double F=0.7;//kleinste Kraft
double kT=0.056;
double gam=0.4;
int h,i,j,l,a,b,c,a2,b2,c2,d2,f,g;
double vavt[1000],xavt[1000],x2avt[1000],defft[1000];
//Initialisierung von x
for(h=0;h<100;h++){
x[h]=0;
}
//Initialisierung von v
for(i=0;i<100;i++){
v[i]=0;
}
d2=0;
//Schleife über alle Zeitschritte
for(j=0;j<N;j++){
if(j==(d2+1)*50000-1){
d2=d2+1;
for(l=0;l<100;l++){
x[l]=xs[l]+vs[l]*dt;
v[l]=vs[l]-gam*vs[l]*dt+F*dt-sin(xs[l])*dt+sqrt(2*kT*gam*dt)*n(gen);
vs[l]=v[l];
xs[l]=x[l];
}
double sum4=0;
for(a2=0;a2<100;a2++){
sum4=sum4+v[a2];
}
vavt[d2]=sum4/100;//mittl Geschwindigkeit
double sum5=0;
for(b2=0;b2<100;b2++){
sum5=sum5+x[b2];
}
xavt[d2]=sum5/100;//mittl Position
double sum6=0;
for(c2=0;c2<100;c2++){
sum6=sum6+x[c2]*x[c2];
}
x2avt[d2]=sum6/100;//Mittel der Positionsquadrate
defft[d2]=(x2avt[d2]-xavt[d2]*xavt[d2])/(2*(j+1)*dt);//Diffusionskoeffizient
}
else{
for(l=0;l<100;l++){
x[l]=xs[l]+vs[l]*dt;
v[l]=vs[l]-gam*vs[l]*dt+F*dt-sin(xs[l])*dt+sqrt(2*kT*gam*dt)*n(gen);
xs[l]=x[l];
vs[l]=v[l];
}
}
}
vavt[0]=0;xavt[0]=0;x2avt[0]=0;defft[0]=0;
for(f=0;f<1000;f++){
myfile << f*500 << ' ' << defft[f] <<"\n";
}
for(g=0;g<1000;g++){
myfile2 << g*500 << ' ' << vavt[g] << "\n";
}
myfile.close();
myfile2.close();
return 0;
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on December 27, 2018, 1:54 PM
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cmath>
#include <random>
#include <map>
#include <string>
#include <iomanip>
using namespace std;
double average(double x[],int n);
double square(double x[],int n);
double init(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
ofstream myfile2;
ofstream myfile3;
myfile.open (argv[2]);
myfile2.open (argv[3]);
myfile3.open (argv[4]);
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
int T=1200;//Simulationszeit
int O=1;//Anzahl der Kraftschritte
int P=200;//Zeit, ab der gemittelt wird
double df=0.02;
double v[100],vs[100];
double x[100],xs[100];
double deff[O];
deff[0]=0;
double deff2[O];
deff2[0]=0;
double vav[O];
double dt=0.01;
int N=T/dt;
double F0=atof(argv[1]);//kleinste Kraft 0.55
double kT=0.033;
double gam=0.4;
int Neq=P/dt;
int j,l,a2,f,g,g2,s;
double F;
double xav[O];
xav[0]=0;
double Fano[O];
Fano[0]=0;
double vavt,xavt,x2avt,defft;
//Schleife über versch Kräfte
for(s=0;s<O;s++){
F=F0+s*df;
//Initialisierung von x
init(x,100);
init(xs,100);
//Initialisierung von v
init(v,100);
init(vs,100);
//Schleife über die ersten Zeitschritte
for(j=0;j<Neq;j++){
//Schleife über alle Teilchen
for(l=0;l<100;l++){
v[l]=vs[l]-gam*vs[l]*dt+F*dt-sin(xs[l])*dt+sqrt(2*kT*gam*dt)*n(gen);
x[l]=xs[l]+vs[l]*dt;
xs[l]=x[l];
vs[l]=v[l];
}
}
int e=0;
double av=0;
double avv=0;
//Schleife über die letzten Zeitschritte
for(a2=Neq;a2<N;a2++){
//Schleife über alle Teilchen
for(l=0;l<100;l++){
v[l]=vs[l]-gam*vs[l]*dt+F*dt-sin(xs[l])*dt+sqrt(2*kT*gam*dt)*n(gen);
x[l]=xs[l]+vs[l]*dt;
vs[l]=v[l];
xs[l]=x[l];
}
vavt=average(v,100);//mittl Geschwindigkeit
xavt=average(x,100);//mittl Position
square(x,100);
x2avt=average(x,100);//Mittel der Positionsquadrate
defft=(x2avt-xavt*xavt)/(2*(a2+1)*dt);//Diffusionskoeffizient
//Finden des Mittels der letzten Werte
av=(e*av+defft)/(e+1);
avv=(e*avv+vavt)/(e+1);
e=e+1;
deff2[s]=av;//mittl Diffusionskoeffizient
}
vav[s]=avv;
Fano[s]=deff2[s]/vav[s];
}
for(f=0;f<O;f++){
myfile << F0+f*df << " " << deff2[f] <<"\n";
}
for(g=0;g<O;g++){
myfile2 << F0+g*df << " " << vav[g] << "\n";
}
for(g2=0;g2<O;g2++){
myfile3 << F0+g2*df << " " <<Fano[g2] << "\n";
}
myfile.close();
myfile2.close();
myfile3.close();
return 0;
}
double average(double x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
double square(double x[],int n){
int j;
for(j=0;j<n;j++){
x[j]*=x[j];
}
}
double init(double x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
def spectrum(f,tau,sigma):
return (2*tau*sigma**2)/(1+(2*np.pi*f*tau)**2)
date='xtraje18ftfteneq2'
nr=9
epsilon=0.01
omega=0.01
tau=3
file=open('/home/richard/mastergit/NetBeansProjects/oup/%s.txt' %(date),"r")
#file=open('/home/richard/outhome/spikerealrinzel25o%d%d.txt' %(z,nr),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
file2=open('/home/richard/mastergit/NetBeansProjects/oup/%sshort.txt' %(date),"r")
#file=open('/home/richard/outhome/spikerealrinzel25o%d%d.txt' %(z,nr),"r")
x,y=[],[]
for k in file2:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax2=np.array(x)
ay2=np.array(y)
amp=epsilon**2/ax[0]/(4*(1+((omega/2)*tau)**2))
#SNR=ay2[omegaind]/background
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('Frequency $[s^{-1}]$')
plt.ylabel('Spectral power')
plt.yscale('log')
plt.xscale('log')
plt.xlim(10**(-4),950)
plt.ylim(10**(-10),10**3)
# plt.xlim(ax[0]*timefac,10000000/(2*T)*timefac)
#plt.xlim(4*10**(-4),100)
plt.plot(ax,ay*ax[0],label='Simulationlong')
plt.plot(ax2,ay2*ax2[0],label='Simulationshort')
plt.plot(ax,spectrum(ax,3,5),label='theorylong')
plt.plot(ax2,spectrum(ax2,3,5),label='theoryshort')
plt.plot(omega/2,amp+spectrum(omega/(4*np.pi),3,5),'x',label="delta")
plt.legend()
#plt.plot(ax2,spectrum(ax2,1/(4.748*10**(-3)),13),label='theory')
#plt.plot(omega,background/T,'kx')
#plt.legend()
#plt.plot(sax2,say2/T2,label='e6')
#plt.savefig('inapikrealfrange9aspD=%.2fI=%.2f.pdf' %(D*0.01,-0.1+z*0.02))
plt.savefig('oup%sfourier.pdf' %(date))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
#vec=np.zeros((1,20))
#ii=0
#vec=np.zeros((1,7))
#for x in [8,10,12,15,20,30,40]:
for x in [3]:
col,colx=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/drealtest30j22%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
# for z in range(0,20):
# vec[ii][z]=cola[z]
# ii=ii+1
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I')
plt.ylabel('$D_{eff}$')
plt.yscale('log')
#plt.xscale('log')
#plt.plot(xs,vec[0,:],label='D=0.8')
#plt.plot(xs,vec[1,:],label='D=1')
#plt.plot(xs,vec[2,:],label='D=1.2')
#plt.plot(xs,vec[3,:],label='D=1.5')
#plt.plot(xs,vec[0,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
plt.plot(colxa,cola,label='D=3e-3')
plt.legend()
plt.savefig('dneur30j223.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on July 2, 2019, 5:19 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
using namespace std;
double average(long long int x[],int n);
double square(long long int x[],int n);
double ninf(double V, double k, double Vh);
double minf(double V);
double ninf(double V);
double hinf(double V);
double init(long long int x[],int n);
double initd(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
//ofstream myfile2;
//ofstream myfile3;
myfile.open ("realstaterinzel12100.txt");
//myfile2.open ("statechange.txt");
//myfile3.open (argv[4]
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
double I=-12; // 0
double S=1.27;
double phi=3.82;
double dI=0.5;
double gL=0.3; // 8
double EL=10; // -80
double gNa=120; // 20
double ENa=115; // 60
double gK=36; // 9
double EK=12; // -90
//double gM=5; // 5
/*//slow K+ current
double kinf=5; // 5
double vinf=-20; // -20
double tauM=30; // 20*/
//Na current
//int N=500000;
int Neq=3000000;
int points=100000;
int sampling=Neq/points;
int j,f;
double dt=0.001;
double D=100;
//int spikes=100;
//double* spike=new double[spikes];
int runs=1;
int Ivalues=1;
long long int sqcount[runs];
double Nav,N2av,T;
double v[runs],wf[runs],wfs[runs],vs[runs],uGe[Ivalues],uFano[Ivalues],uDeff[Ivalues],Deff,Deff2,deff[Ivalues],vav[Ivalues],Fano[Ivalues],vout[points],wout[points],lastcount,prelastchange,lastchange;
int p=0;
int bv,bvp,sv;
lastcount=0;
prelastchange=0;lastchange=0;
sv=0;
//for(s=0;s<Ivalues;s++){
//initd(nfs,runs);
wfs[0]=0.2;
vs[0]=10.1;
for(j=0;j<Neq;j++){
for(int a=0;a<runs;a++){
v[a]=I*dt+vs[a]-gL*(vs[a]-EL)*dt-gNa*pow(minf(v[a]),3)*(1-wfs[a])*(vs[a]-ENa)*dt-gK*pow(wfs[a]/S,4)*(vs[a]-EK)*dt+sqrt(2*D*dt)*n(gen);
wf[a]=wfs[a]+phi*((S*(ninf(vs[a])+S*(1-hinf(vs[a])))/(1+(S*S)))-wfs[a])*dt/(5*exp(-pow((vs[a]+10)/55,2))+1);
if(wf[a]>1){
wf[a]=1;
}
if(j==p*sampling){vout[p]=v[a];
wout[p]=wf[a];
p=p+1;
}
vs[a]=v[a];
wfs[a]=wf[a];
}
}
for(f=0;f<points;f++){
myfile << f*sampling*dt << " " << vout[f] << " "<< wout[f] <<" " << "\n";
}
myfile.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(long long int x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
double square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
double init(long long int x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
double ninf(double V){
double f=((10-V)/(100*(exp((10-V)/10)-1)))/((10-V)/(100*(exp((10-V)/10)-1))+exp(-V/80)/8);
return f;
}
double minf(double V){
double f=((25-V)/(10*(exp((25-V)/10)-1)))/((25-V)/(10*(exp((25-V)/10)-1))+4*exp(-V/18));
return f;
}
double hinf(double V){
double f=(7*exp(-V/20)/100)/(7*exp(-V/20)/100+1/(exp((30-V)/10)+1));
return f;
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
points=100000
file=open('/home/richard/mastergit/NetBeansProjects/inapik/inaprealanhopf.txt',"r")
x,y,z,a=[],[],[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
#az=40*np.array(z)-65
#aa=-np.array(a)
area=(np.sum(ay)-min(ay)*points)*0.003/360
plt.figure()
plt.xlabel('time [s]')
plt.ylabel('membrane voltage [mV]')
plt.xlim(0,0.1)
#plt.plot(ax,ay,label='%.6f' %area)
plt.plot(ax/1000,ay,'black')
#plt.plot(ax,aa)
#plt.legend()
plt.savefig('inaprealanhopfvtblack.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <ios>
#include <iomanip>
#include <fftw3.h>
using namespace std;
int main(int argc, char** argv) {
ofstream myfile;
myfile.open("xtraj.txt");
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
const int d=1;
const int * zeiger;
zeiger=&d;
int runs=10;
int N=1000000;
int points=1000000;
int sampling=N*runs/points;
int j22;
double dt=0.001;
double tau=1;
double sigma=1;
double xv[points];
double xvout[points][2];
int p=0;
double x=0;
for(int a=0;a<runs;a++){
for(int j2=0;j2<N;j2++){
j22=j2+a*N;
x=x*(1-dt/tau)+sqrt((2*sigma*sigma*dt)/tau)*n(gen);
if(j22==p*sampling){
xv[p]=x;
p=p+1;
}
}
}
fftw_plan q;
q=fftw_plan_dft_r2c(N,zeiger,xv,xvout,FFTW_ESTIMATE);
fftw_execute(q);
fftw_destroy_plan(q);
for(int rv=0;rv<points;rv++){
myfile << rv*sampling*dt << " " << xvout[rv] <<"\n";
}
myfile.close();
return 0;
}<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
jj=0
vecx=np.zeros((2,5,10000))
vecy=np.zeros((2,5,10000))
for x in ['ais','aism']:
ii=0
for y in range(1,6):
colx,coly=[],[]
file=open('/home/richard/outhome/deff%s%d.txt' % (x,y),"r")
for k in file:
row=k.split()
colx.append(row[0])
coly.append(row[1])
colxa=np.array(colx)
colya=np.array(coly)
for z in range(0,10000):
vecx[jj][ii][z]=colxa[z]
vecy[jj][ii][z]=colya[z]
ii=ii+1
jj=jj+1
plt.xlabel('time')
plt.ylabel('$D_eff$')
plt.yscale('log')
plt.plot(vecx[0][0][:],vecy[0][0][:],'y',label='kT=0.033')
plt.plot(vecx[1][0][:],vecy[1][0][:],'y',label='kT=0.033, average')
plt.plot(vecx[0][1][:],vecy[0][1][:],'r',label='kT=0.043')
plt.plot(vecx[1][1][:],vecy[1][1][:],'r',label='kT=0.043, average')
plt.plot(vecx[0][2][:],vecy[0][2][:],'b',label='kT=0.056')
plt.plot(vecx[1][2][:],vecy[1][2][:],'b',label='kT=0.056, average')
plt.plot(vecx[0][3][:],vecy[0][3][:],'orange',label='kT=0.072')
plt.plot(vecx[1][3][:],vecy[1][3][:],'orange',label='kT=0.072, average')
plt.plot(vecx[0][4][:],vecy[0][4][:],'g',label='kT=0.094')
plt.plot(vecx[1][4][:],vecy[1][4][:],'g',label='kT=0.094, average')
#plt.legend()
plt.savefig('dmechav.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
#datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
#Dvar=np.array([30])
#lvar=len(Dvar)
#yvar=[4,13,3]
#yvalues=len(yvar)
timefac=1000
date='realanhopf3mlogcorner2'
date1='realanhopf3mlogcorner'
date2='realanhopf21flogcorner'
date3='realanhopf3mlogcorner'
datevar=['realanhopf17mlogcorner2','realanhopf11mlogcorner2']
D=[]
D1=[10]
D2=[10]
D3=[]
Dvar=[10]
Dtot=D+D1+D2+D3+Dvar
l=len(Dtot)
istart=1
ivalues=10
vecx=np.zeros((l,ivalues))
vec=np.zeros((l,ivalues))
ii=0
offset=np.zeros(l,dtype=int)
yvar=[4,6]
yvalues=len(yvar)
ystart=1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/d%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
if len(colvar)+offset[ii]<y+kk*yvar[kk]-istart+1:
offset[ii]=offset[ii]+1
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=colavar[z]
vecx[ii][z]=colxavar[z]
ii=ii+1
istart0=1
ivalues0=3
for x in D:
col,colx=[],[]
for y in range(istart0,istart0+ivalues0):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart0+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues0-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D2:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D3:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
#xs=np.arange(-0.08,0.32,0.02)
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ $[s^{-1}]$')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,1):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='D=%.2f,kurz' %(Dtot[n]/100))#kurz
#for n in range(0,1):
# plt.plot(vecx[n,0:3],vec[n,0:3]*timefac,label='D=%.2f' %(Dtot[n]/100))#kurz
#plt.xlim(46,47)
for n in range(1,2):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='D=%.2f,mittel' %(Dtot[n]/100))
for n in range(2,3):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='D=%.2f,lang' %(Dtot[n]/100))
#plt.plot([46.1, 46.1], [10**(-2), 10**2], color='black', linestyle='-',label='$I_{crit}$')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend()
plt.savefig('dneur%s.pdf' %(date+date1))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
eqreltime=np.zeros((4,20))
breltime=np.zeros((4,20))
ii=0
for x in [50]:
times,avalues,j2values,state=[],[],[],[]
for y in range(15,16):
file=open('/home/richard/mainp2test/time15atest%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
times.append(float(row[0]))
avalues.append(float(row[1]))
j2values.append(float(row[2]))
state.append(float(row[3]))
timesa=np.array(times)
statea=np.array(state)
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if timesa[2*z+1]>timesa[2*z]:
inteq[z]=timesa[2*z+1]-timesa[2*z]
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if timesa[2*z+2]>timesa[2*z+1]:
intb[z]=timesa[2*z+2]-timesa[2*z+1]
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if timesa[2*z+1]>timesa[2*z]:
intb[z]=timesa[2*z+1]-timesa[2*z]
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if timesa[2*z+2]>timesa[2*z+1]:
inteq[z]=timesa[2*z+2]-timesa[2*z+1]
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
plt.hist(intbt, bins=50)
plt.title("distribution of bursting time intervals")
plt.savefig('bdist%d%d.pdf' %(x,y))
plt.figure()
plt.hist(inteqt, bins=50)
plt.title("distribution of equilibrium time intervals")
plt.savefig('eqdist%d%d.pdf' %(x,y))
#eqtot=np.sum(inteq)
#btot=np.sum(intb)
#eqrel=eqtot/(eqtot+btot)
#brel=btot/(eqtot+btot)
#eqreltime[ii][y]=eqrel
#breltime[ii][y]=brel
ii=ii+1
#xs=np.arange(-0.75,4.25,0.25)
#plt.xlabel('bias current I')
#plt.ylabel('proportion of simulation time')
#plt.plot(xs,eqreltime[0,:],label='D=1,burst')
#plt.plot(xs,eqreltime[1,:],label='D=2,burst')
#plt.plot(xs,eqreltime[2,:],label='D=3,burst')
#plt.plot(xs,eqreltime[3,:],label='D=4,burst')
#plt.plot(xs,breltime[0,:],label='D=1,equilibrium')
#plt.plot(xs,breltime[1,:],label='D=2,equilibrium')
#plt.plot(xs,breltime[2,:],label='D=3,equilibrium')
#plt.plot(xs,breltime[3,:],label='D=4,equilibrium')
#plt.legend()
#plt.savefig('inapiktimes.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def barrier(a,b,x):
return a * x + b
def r(t,av,v0,a,b):
return (av*t+v0)/(1+np.exp(-barrier(a,b,t)))
def ralt(t,v0,a,b):
return r(t,0,v0,a,b)
N=50000000
dt=0.0005
T=N*dt
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countI9a.txt',"r")
col=[]
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
D1=[35]
D3=[25,30]
D2=[45]
Dvar=[]
D=D1+D2+D3+Dvar
Da=np.array(D)
l1=len(D1)
l2=len(D2)
l3=len(D3)
lvar=len(Dvar)
l=l1+l2+l3+lvar
date1='realfast11jjem2sh'
date3='realfast13aem2n4'
date2='realfast19jjem2st'
datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
yvar=[4,13,3]
yvalues=len(yvar)
istart=1
ivalues=20
epsilon = 0.00001
g=np.zeros((l,ivalues))
xg=np.zeros((l,ivalues))
ii=0
istart1=1
ivalues1=20
for x in D1:
col1,colx1=[],[]
for y in range(istart1,istart1+ivalues1):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,ivalues1):
g[ii][z]=cola1[z]
xg[ii][z]=colxa1[z]
ii=ii+1
istart2=1
ivalues2=20
for x in D2:
col2,colx2=[],[]
for y in range(istart2,istart2+ivalues2):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx2.append(float(row[0]))
col2.append(float(row[1]))
colxa2=np.array(colx2)
cola2=np.array(col2)
for z in range(0,ivalues2):
g[ii][z]=cola2[z]
xg[ii][z]=colxa2[z]
ii=ii+1
istart3=1
ivalues3=20
for x in D3:
col3,colx3=[],[]
for y in range(istart3,istart3+ivalues3):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx3.append(float(row[0]))
col3.append(float(row[1]))
colxa3=np.array(colx3)
cola3=np.array(col3)
for z in range(0,ivalues3):
g[ii][z]=cola3[z]
xg[ii][z]=colxa3[z]
ii=ii+1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/g%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
g[ii][z]=colavar[z]
xg[ii][z]=colxavar[z]
ii=ii+1
avn=np.zeros(l)
v0n=np.zeros(l)
av=np.zeros(l)
bv=np.zeros(l)
for kk in range(0,l):
popt,pcov = curve_fit(r, xg[kk,:], g[kk,:],bounds=((0.01,0.06,-np.inf,-np.inf),(0.02,0.07,np.inf,np.inf)))
avn[kk]=popt[0]
v0n[kk]=popt[1]
av[kk]=popt[2]
bv[kk]=popt[3]
eqfile2 = open('rateparamsv11s.txt','w')
for k4 in range(0,l):
eqfile2.write('%.6f %.6f %.6f %.6f \n'%(avn[k4],v0n[k4],av[k4],bv[k4]))
eqfile2.close()
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('average firing rate <v> $[10^3s^{-1}]$')
#plt.yscale('log')
colorv=['b','r','g','y','c']
t=np.arange(-0.1,0.31,0.01)
xburst=np.arange(-0.20,0.31,0.01)
#for n in range(0,l):
# plt.plot(t,r(t,avn[n],v0n[n],av[n],bv[n]),colorv[n])
for n in range(0,l):
plt.plot(xg[n,:],g[n,:],colorv[n],label='D=%.2f' %(Da[n]/100))
plt.plot(xburst,cola/T,label='running firing rate $v_0$',color='black')
plt.xlim(-0.1,0.3)
handles, labels = plt.gca().get_legend_handles_labels()
order = [2,3,0,1,4]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('ganaburst23j2%s.pdf' %(date1+date2))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
#matplotlib.rcParams.update({'font.size': 22})
datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
Dvar=np.array([])
lvar=len(Dvar)
yvar=[4,13,3]
yvalues=len(yvar)
timefac=1000 #convert ms to s
date0='realfast11jjem2sh'
date='realfast19jjem2st'
date1='realfast13aem2n4'
D=np.array([45])
D1=np.array([30,25])
datefull=date+date1+date0
l1=len(D1)
D0=np.array([35])
l0=len(D0)
l=len(D)
ltot=l0+l+lvar+l1
vec=np.zeros((ltot,20))
ii=0
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/d%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
vec[ii][z]=colavar[z]*timefac
ii=ii+1
for x in D1:
col1,colx1=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,20):
vec[ii][z]=cola1[z]*timefac
ii=ii+1
for x in D0:
col0,colx0=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date0,x,y),"r")
for k in file:
row=k.split()
colx0.append(float(row[0]))
col0.append(float(row[1]))
colxa0=np.array(colx0)
cola0=np.array(col0)
for z in range(0,20):
vec[ii][z]=cola0[z]*timefac
ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]*timefac
ii=ii+1
colorv=['y','g','b','r','c']
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ $[s^{-1}]$')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,lvar):
plt.plot(colxavar,vec[n,:],colorv[n],label='D=%.2f' %(Dvar[n]/100))
for n in range(lvar,l1+lvar):
plt.plot(colxa1,vec[n,:],colorv[n],label='D=%.2f' %(D1[n-lvar]/100))
for n in range(l1+lvar,l1+lvar+l0):
plt.plot(colxa0,vec[n,:],colorv[n],label='D=%.2f' %(D0[n-lvar-l1]/100))
for n in range(l1+lvar+l0,ltot):
plt.plot(colxa,vec[n,:],colorv[n],label='D=%.2f' %(D[n-lvar-l1-l0]/100))
#plt.plot([0.165, 0.165], [5*10**(-1), 50000], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot([-0.022, -0.022], [5*10**(-1), 50000], color='black', linestyle='-')
#plt.legend()
handles, labels = plt.gca().get_legend_handles_labels()
order = [1,0,2,3]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('dneur3sh%s.pdf' %datefull)
vec=np.zeros((ltot,20))
ii=0
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/f%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
vec[ii][z]=colavar[z]
ii=ii+1
for x in D1:
col1,colx1=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,20):
vec[ii][z]=cola1[z]
ii=ii+1
for x in D0:
col0,colx0=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date0,x,y),"r")
for k in file:
row=k.split()
colx0.append(float(row[0]))
col0.append(float(row[1]))
colxa0=np.array(colx0)
cola0=np.array(col0)
for z in range(0,20):
vec[ii][z]=cola0[z]
ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
plt.figure()
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Fano factor F')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,lvar):
plt.plot(colxavar,vec[n,:],colorv[n],label='D=%.2f' %(Dvar[n]/100))
for n in range(lvar,l1+lvar):
plt.plot(colxa1,vec[n,:],colorv[n],label='D=%.2f' %(D1[n-lvar]/100))
for n in range(l1+lvar,l1+lvar+l0):
plt.plot(colxa0,vec[n,:],colorv[n],label='D=%.2f' %(D0[n-lvar-l1]/100))
for n in range(l1+lvar+l0,ltot):
plt.plot(colxa,vec[n,:],colorv[n],label='D=%.2f' %(D[n-lvar-l1-l0]/100))
#plt.plot([0.165, 0.165], [10**(-2), 10**4], color='black', linestyle='-', label='$I_{crit}$')
#plt.plot([-0.022, -0.022], [10**(-2), 10**4], color='black', linestyle='-')
#plt.plot(xs,vec[3,:],label='D=1.5')
#plt.plot(xs,vec[0,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(colxa,cola,label='D=3e-3')
#plt.legend()
handles, labels = plt.gca().get_legend_handles_labels()
order = [1,0,2,3]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('fneur3sh%s.pdf' %datefull)
vec=np.zeros((ltot,20))
ii=0
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/g%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
vec[ii][z]=colavar[z]*timefac
ii=ii+1
for x in D1:
col1,colx1=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,20):
vec[ii][z]=cola1[z]*timefac
ii=ii+1
for x in D0:
col0,colx0=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date0,x,y),"r")
for k in file:
row=k.split()
colx0.append(float(row[0]))
col0.append(float(row[1]))
colxa0=np.array(colx0)
cola0=np.array(col0)
for z in range(0,20):
vec[ii][z]=cola0[z]*timefac
ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]*timefac
ii=ii+1
N=50000000
dt=0.0005
T=N*dt
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countI9a.txt',"r")
col=[]
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)*timefac
xburst=np.arange(-0.20,0.31,0.01)
plt.figure()
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('average firing rate <v> [$s^{-1}$]')
#plt.yscale('log')
#plt.xscale('log')
plt.plot(xburst,cola/T,label='running firing rate $v_0$',color='black')
for n in range(0,lvar):
plt.plot(colxavar,vec[n,:],colorv[n],label='D=%.2f' %(Dvar[n]/100))
for n in range(lvar,l1+lvar):
plt.plot(colxa1,vec[n,:],colorv[n],label='D=%.2f' %(D1[n-lvar]/100))
for n in range(l1+lvar,l1+lvar+l0):
plt.plot(colxa0,vec[n,:],colorv[n],label='D=%.2f' %(D0[n-lvar-l1]/100))
for n in range(l1+lvar+l0,ltot):
plt.plot(colxa,vec[n,:],colorv[n],label='D=%.2f' %(D[n-lvar-l1-l0]/100))
plt.xlim(-0.08,0.3)
#plt.plot(xs,vec[3,:],label='D=1.5')
#plt.plot(xs,vec[0,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(colxa,cola,label='D=3e-3')
#plt.legend()
handles, labels = plt.gca().get_legend_handles_labels()
order = [2,1,3,4,0]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('gneursh3%s.pdf' %datefull)
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
date='firingratestimesh'
D=[30,35,40,45,50]
dvalues=len(D)
istart=-0.05
irange=0.5
ivalues=50
istep=irange/ivalues
vec=np.zeros((dvalues,ivalues))
ii=0
file=open('/home/richard/outhome/%s.txt' %date,"r")
for k in file:
col=[]
row=k.split()
for j in range(0,dvalues):
col.append(float(row[j]))
cola=np.array(col)
for z in range(0,dvalues):
vec[z][ii]=cola[z]
ii=ii+1
ivar=np.arange(istart,istart+irange,istep)
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I')
plt.ylabel('firing rate')
#plt.yscale('log')
#plt.xscale('log')
for n in range(0,dvalues):
plt.plot(ivar,vec[n,:],label='D=%s' %D[n])
plt.savefig('firingratesh.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
vec=np.zeros(20)
col,colx=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/dkno%d.txt' % (y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
minv=np.amin(cola)
maxv=np.amax(cola)
x=np.arange(0.5,10.5,0.5)
#fig=plt.figure()
plt.yscale('log')
plt.plot(x,cola)
plt.yticks(np.arange(2450,2800,300))
plt.xlabel('time constant kn')
plt.ylabel('$D_{eff}$')
plt.savefig('dneurknovar.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on June 27, 2019, 10:13 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <iostream>
using namespace std;
double ninf(double V, double k, double Vh);
double init(double x[],int n);
int main(int argc, char** argv) {
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
ofstream myfile;
myfile.open ("countI2.txt");
double I0=0; // 0
double gL=0.0029; // 8
double EL=-80; // -80
double gNa=0.01; // 20
double ENa=60; // 60
double gK=0.004; // 9
double EK=-90; // -90
//Na current
double km=14; // 15
double vm=-18; // -20
//fast K+ current
double kn=5; // 5
double vn=-25; // -20
double tau=400; // 0.152
int N0;
N0=5000000;
int points=10000;
int runs=5;
int sampling=(N0*runs)/points;
double count[runs],vout[points],hout[points];
double v,vs,nf,nfs,D;
D=0.01;
double th=-25;
vs=-30;
nfs=0.2;
int j,f,p;
p=0;
double dt;
dt=0.01;
init(count,runs);
for(int a=0;a<runs;a++){
for(j=0;j<N0;j++){
v=I0*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt+sqrt(2*D*dt)*n(gen);
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
if(v > th && vs < th){
count[a]=count[a]+1;
}
if(j+a*N0==p*sampling){vout[p]=v;
hout[p]=nf;
p=p+1;
}
vs=v;
nfs=nf;
}
}
for(f=0;f<points;f++){
myfile << dt*sampling*f << " " << vout[f] << " "<< hout[f] << "\n";
}
myfile.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double init(double x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
<file_sep>#
# Generated - do not edit!
#
# NOCDDL
#
CND_BASEDIR=`pwd`
CND_BUILDDIR=build
CND_DISTDIR=dist
# Debug configuration
CND_PLATFORM_Debug=GNU-Linux
CND_ARTIFACT_DIR_Debug=dist/Debug/GNU-Linux
CND_ARTIFACT_NAME_Debug=irange2
CND_ARTIFACT_PATH_Debug=dist/Debug/GNU-Linux/irange2
CND_PACKAGE_DIR_Debug=dist/Debug/GNU-Linux/package
CND_PACKAGE_NAME_Debug=irange2.tar
CND_PACKAGE_PATH_Debug=dist/Debug/GNU-Linux/package/irange2.tar
# Release configuration
CND_PLATFORM_Release=GNU-Linux
CND_ARTIFACT_DIR_Release=dist/Release/GNU-Linux
CND_ARTIFACT_NAME_Release=irange2
CND_ARTIFACT_PATH_Release=dist/Release/GNU-Linux/irange2
CND_PACKAGE_DIR_Release=dist/Release/GNU-Linux/package
CND_PACKAGE_NAME_Release=irange2.tar
CND_PACKAGE_PATH_Release=dist/Release/GNU-Linux/package/irange2.tar
#
# include compiler specific variables
#
# dmake command
ROOT:sh = test -f nbproject/private/Makefile-variables.mk || \
(mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk)
#
# gmake command
.PHONY: $(shell test -f nbproject/private/Makefile-variables.mk || (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk))
#
include nbproject/private/Makefile-variables.mk
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def velpot(v,F):
return v**4/4-v**2/2-F*v
def lokex(arr,xmin,imin,imax,dx,p):
minind=round((imin-xmin)/dx)
maxind=round((imax-xmin)/dx)
parta=arr[minind:maxind]
if(p<=0):
ind=np.where(parta==parta.min())
else:
ind=np.where(parta==parta.max())
return xmin+(minind+ind[0][0])*dx
xmin=-1.8
xmax=1.8
dx=0.01
F=0.05
ymin=-0.4
ymax=0.2
t=np.arange(xmin,xmax,dx)
asy=velpot(t,F)
maxv=lokex(asy,xmin,-0.5,0.5,dx,1)
maxt=np.arange(maxv-0.5,maxv+0.5,dx)
minlv=lokex(asy,xmin,-1.5,-0.5,dx,-1)
minlt=np.arange(minlv,minlv+0.45,dx)
minrv=lokex(asy,xmin,0.5,1.5,dx,-1)
minrt=np.arange(minrv-0.6,minrv,dx)
plt.figure()
plt.ylabel('velocity potential U(v)',fontsize=12)
#plt.xlabel('velocity v')
plt.ylim(ymin,ymax)
plt.plot(t,velpot(t,F))
plt.plot(maxt,np.ones(100)*velpot(maxv,F),'black')
plt.plot(minlt,np.ones(45)*velpot(minlv,F),'black')
plt.plot(minrt,np.ones(60)*velpot(minrv,F),'black')
#plt.legend()
plt.arrow(maxv,velpot(maxv,F),0,ymin-velpot(maxv,F),head_length = 0.010, head_width = 0.025,color='black', length_includes_head = True,ls=':')
plt.arrow(minlv,velpot(minlv,F),0,ymin-velpot(minlv,F),head_length = 0.010, head_width = 0.025,color='black', length_includes_head = True,ls=':')
plt.arrow(minrv,velpot(minrv,F),0,ymin-velpot(minrv,F),head_length = 0.010, head_width = 0.025,color='black', length_includes_head = True,ls=':')
plt.arrow(maxv+0.48,velpot(maxv,F),0,velpot(minrv,F)-velpot(maxv,F),head_length = 0.010, head_width = 0.025,color='black', length_includes_head = True)
plt.arrow(maxv+0.48,velpot(minrv,F),0,velpot(maxv,F)-velpot(minrv,F),head_length = 0.010, head_width = 0.025,color='black', length_includes_head = True)
plt.arrow(maxv-0.5,velpot(maxv,F),0,velpot(minlv,F)-velpot(maxv,F),head_length = 0.010, head_width = 0.025,color='black', length_includes_head = True)
plt.arrow(maxv-0.5,velpot(minlv,F),0,velpot(maxv,F)-velpot(minlv,F),head_length = 0.010, head_width = 0.025,color='black', length_includes_head = True)
plt.text(maxv+0.55,(velpot(maxv,F)+velpot(minrv,F))/2, '$\Delta U_+$', fontdict=None,fontsize=15)
plt.text(maxv-1,(velpot(maxv,F)+velpot(minlv,F))/2, '$\Delta U_-$', fontdict=None,fontsize=15)
plt.text(maxv,ymin-0.03, '$v_0$', fontdict=None,fontsize=12)
plt.text(minrv,ymin-0.03, '$v_+$', fontdict=None,fontsize=12)
plt.text(minlv,ymin-0.03, '$v_-$', fontdict=None,fontsize=12)
plt.text(minrv+0.3,ymin-0.03, 'velocity $v$', fontdict=None,fontsize=12)
plt.xticks([])
plt.yticks([])
plt.savefig('velpot.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import cmath
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
ave=10
dt=0.00001
omega=0.001
runs=10
repetitions=50
fpoints=50000
datapoints=1000000
N=100000000
T=N*repetitions*dt
S=np.zeros(fpoints)
last_entry=0
def exp(f,t):
return cmath.exp(2*np.pi*1j*f*t)
file=open('/home/richard/outhome/spike8je1long3010.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
ax=np.array(x)
for z in range(0,datapoints):
current=ax[z]
if current>last_entry:
last_entry=current
else:
points_act=z
break
length=int(points_act/ave)
x_act=np.zeros(length)
for hh in range(0,ave):
for z2 in range(0,length):
x_act[z2]=ax[z2+hh*length]
for ii in range(0,fpoints):
f=3*ii/fpoints
arr=np.zeros(length,dtype=np.complex_)
for jj in range(0,length):
arr[jj]=exp(f,ax[jj])
S[ii]=(hh*S[ii]+(np.abs(np.sum(arr))**2)/T)/(hh+1)
f=np.arange(0,3,3/fpoints)
plt.figure()
plt.xlabel('frequency')
plt.ylabel('power spectrum')
plt.yscale('log')
plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
#plt.xlim(4*10**(-4),100)
plt.plot(f,S)
#plt.plot(sax2,say2/T2,label='e6')
plt.savefig('deltaspectrum2.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
file=open('/home/richard/NetBeansProjects/simplemodel/simplemodel5d2.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[1]))
y.append(float(row[2]))
ax=np.array(x)
ay=np.array(y)
plt.figure()
plt.ylabel('gating variable')
plt.xlabel('membrane voltage V')
plt.plot(ax,ay)
plt.savefig('simplemodel5d2p.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
vec=np.zeros((4,20))
ii=0
for x in [15,20,30,40]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/inatoptd%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
xs=np.arange(-0.9,1.1,0.1)
plt.xlabel('bias current I')
plt.ylabel('$D_eff$')
#plt.yscale('log')
plt.plot(xs,vec[0,:],label='D=1.5')
plt.plot(xs,vec[1,:],label='D=2')
plt.plot(xs,vec[2,:],label='D=3')
plt.plot(xs,vec[3,:],label='D=4')
#plt.plot(xs,vec[4,:],label='D=4')
#plt.plot(xs,vec[5,:],label='D=5')
#plt.plot(xs,vec[6,:],label='D=6')
plt.legend()
plt.savefig('dneurinat.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
def spectrum(f,tau,sigma):
return (2*tau*sigma**2)/(1+(2*np.pi*f*tau)**2)
omega=0.000005
runs=50
timefac=1000
date='realanhopf4flog'
D=20
istart=1
ivalues=20
nr=9
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date,D,z),"r")
#file=open('/home/richard/outhome/spikerealrinzel25o%d%d.txt' %(z,nr),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
l=len(ax)
if l==0:
continue
param=open('/home/richard/outhome/param%s%d%d.txt' %(date,D,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
T=N*repetitions*dt
rate=open('/home/richard/outhome/g%s%d%d.txt' %(date,D,z),"r")
for k in rate:
row=k.split()
r=float(row[1])
#background=np.mean([ay2[omegaind-1],ay2[omegaind-2],ay2[omegaind+1],ay2[omegaind+2],ay2[omegaind-3]])
#SNR=ay2[omegaind]/background
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
#plt.suptitle('I=%.2f, D=%.2f' %(-0.1+z*0.02,D*0.01))
plt.suptitle('I=%.2f, D=%.2f' %(43+z*0.25,D/100))
plt.xlabel('Frequency $[s^{-1}]$')
plt.ylabel('Spectral power')
plt.yscale('log')
plt.xscale('log')
plt.xlim(ax[0]*timefac,10000000/(2*T)*timefac)
#plt.xlim(4*10**(-4),100)
plt.plot(ax[0:l-11]*timefac,ay[0:l-11]/T*timefac,label='Simulation')
plt.plot(ax[0:l-11]*timefac,r*np.ones(l-11)*timefac,label='running firing rate')
#plt.plot(ax2,spectrum(ax2,1/(4.748*10**(-3)),13),label='theory')
#plt.plot(omega,background/T,'kx')
#plt.legend()
#plt.plot(sax2,say2/T2,label='e6')
#plt.savefig('inapikrealfrange9aspD=%.2fI=%.2f.pdf' %(D*0.01,-0.1+z*0.02))
plt.savefig('inapikanhopf%sfourierD=%.2fI=%.2f.pdf' %(date,D/100,43+z*0.25))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
D=[150,200,250,300,400,500]
dvalues=len(D)
T=10000000
istart=-21
irange=15
ivalues=51
istep=irange/ivalues
vec=np.zeros((dvalues,ivalues))
ii=0
file=open('/home/richard/outhome/countrinzelrate.txt',"r")
for k in file:
col=[]
row=k.split()
for j in range(0,dvalues+1):
col.append(float(row[j]))
cola=np.array(col)
for z in range(0,dvalues):
vec[z][ii]=cola[z+1]
ii=ii+1
ivar=np.arange(istart,istart+irange,istep)
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I')
plt.ylabel('firing rate')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,dvalues):
plt.plot(ivar,vec[n,:]/T,label='D=%s' %(D[n]/10))
plt.legend()
plt.savefig('firingraterinzelnoiselonglog.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
file=open('/home/richard/NetBeansProjects/cpphellodet/mechdet2.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[1]))
y.append(float(row[2]))
ax=np.array(x)
ay=np.array(y)
plt.figure()
plt.ylabel('velocity v')
plt.xlabel('position x')
plt.plot(ay,ax)
plt.savefig('mechdet2.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on May 23, 2019, 9:24 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <ios>
#include <iomanip>
#include <fftw3.h>
#include <math.h>
#include <complex>
#define REAL 0
#define IMAG 1
void fft(fftw_complex *in, fftw_complex *out, int N)
{
// create a DFT plan
fftw_plan plan = fftw_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
// execute the plan
fftw_execute(plan);
// do some cleaning
fftw_destroy_plan(plan);
fftw_cleanup();
}
void initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
int main(int argc, char** argv) {
std::ofstream myfile;
std::ofstream myfile2;
std::ofstream myfile3;
myfile.open("xtraje18ftfteneq2long.txt");
myfile2.open("xtraje18ftfteneq2longshort.txt");
myfile3.open("param18ftften2.txt");
const double pi = 3.14159265358979323846;
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
std::uniform_real_distribution<> dis(0, 2*pi);
int points=100000;
int runs=200;
int N=10000000;
int sampling=N/points;
double dt=0.001;
double dtint=sampling*dt;
double T=N*dt;
//int fpointscheck=2*sampling*10;
int fpointsshort,shortsamp;
double deltapeakshort,dtshort,Tfshort;
/*if(fpointscheck<points){
fpointsshort=fpointscheck;
shortsamp=1;
dtshort=dt;
}
else{
fpointsshort=points;
shortsamp=floor(fpointscheck/points);
dtshort=shortsamp*dt;
}
deltapeakshort=1/dtshort;
Tfshort=dtshort*fpointsshort;
*/
fpointsshort=100000;
shortsamp=1;
dtshort=dt;
deltapeakshort=1/dtshort;
Tfshort=dtshort*fpointsshort;
int foutpoints=1000;
int foutvalues[foutpoints];
foutvalues[0]=1;
double logstep=exp(log(points/2)/foutpoints);
int wints=round(1/(logstep-1));
int wnew,wold,wlength;
for(int w=1;w<wints;w++){
foutvalues[w]=w+1;
}
for(int w=wints;w<foutpoints;w++){
wold=foutvalues[w-1];
wnew=round(wold*logstep);
if(wnew>points/2){
wlength=w;
break;
}
else{
foutvalues[w]=wnew;
}
}
int foutfinal[wlength];
for (int w2=0;w2<wlength;w2++){
foutfinal[w2]=foutvalues[w2];
}
int foutvaluesshort[foutpoints];
foutvaluesshort[0]=1;
double logstepshort=exp(log(fpointsshort/2)/foutpoints);
int wintshort=round(1/(logstepshort-1));
int wnewshort,woldshort,wlengthshort;
for(int w=1;w<wintshort;w++){
foutvaluesshort[w]=w+1;
}
for(int w=wintshort;w<foutpoints;w++){
woldshort=foutvaluesshort[w-1];
wnewshort=round(woldshort*logstepshort);
if(wnewshort>fpointsshort/2){
wlengthshort=w;
break;
}
else{
foutvaluesshort[w]=wnewshort;
}
}
int foutfinalshort[wlengthshort];
for (int w2=0;w2<wlengthshort;w2++){
foutfinalshort[w2]=foutvaluesshort[w2];
}
double tau=3;
double sigma=5;
double epsilon=0.01;
double omega=0.01;
double t,phi;
//double xv[points];
//double xvout[500][2];
double sqout[points];
initd(sqout,points);
double sqoutshort[fpointsshort];
initd(sqoutshort,fpointsshort);
double x;
int p,qshort,qvarshort;
//fftw_complex in[points], out[points];
fftw_complex* in = new fftw_complex[points];
fftw_complex* out = new fftw_complex[points];
fftw_complex* inshort = new fftw_complex[fpointsshort];
fftw_complex* outshort = new fftw_complex[fpointsshort];
for(int a=0;a<runs;a++){
p=0;
x=0;
qshort=0;
qvarshort=0;
phi=dis(gen);
for(int j2=0;j2<N;j2++){
qvarshort=qvarshort+1;
t=j2*dt;
x=x*(1-dt/tau)+epsilon*cos(omega*t*pi+phi)*dt+sqrt((2*sigma*sigma*dt)/tau)*n(gen);
if(j2==p*sampling){
in[p][REAL]=x;
in[p][IMAG]=0;
p=p+1;
}
if(qshort<fpointsshort){
if(qvarshort==shortsamp){
qvarshort=0;
inshort[qshort][REAL]=x;
inshort[qshort][IMAG]=0;
qshort=qshort+1;
}
}
}
fft(in, out,points);
for(int ind=0;ind<points;ind++){
sqout[ind]=(a*sqout[ind]+(out[ind][REAL]*out[ind][REAL]+out[ind][IMAG]*out[ind][IMAG])*dtint*dtint)/(a+1);
}
fft(inshort, outshort,fpointsshort);
for(int ind=0;ind<fpointsshort;ind++){
sqoutshort[ind]=(a*sqoutshort[ind]+(outshort[ind][REAL]*outshort[ind][REAL]+outshort[ind][IMAG]*outshort[ind][IMAG])*dtshort*dtshort)/(a+1);
}
}
for(int rv=0;rv<wlength;rv++){
myfile << foutvalues[rv]/T << " " << sqout[foutvalues[rv]] <<"\n";
}
myfile.close();
for(int rv=0;rv<wlengthshort;rv++){
myfile2 << foutvaluesshort[rv]/Tfshort << " " << sqoutshort[foutvaluesshort[rv]] <<"\n";
}
myfile2.close();
myfile3<<T<<" "<<Tfshort<<" "<<points<<" "<<fpointsshort<<"\n";
myfile3.close();
return 0;
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on May 23, 2019, 9:24 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <ios>
#include <iomanip>
#include <fftw3.h>
#include <math.h>
#include <complex>
#define REAL 0
#define IMAG 1
void fft(fftw_complex *in, fftw_complex *out, int N)
{
// create a DFT plan
fftw_plan plan = fftw_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
// execute the plan
fftw_execute(plan);
// do some cleaning
fftw_destroy_plan(plan);
fftw_cleanup();
}
void initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
int main(int argc, char** argv) {
std::ofstream myfile;
myfile.open("xtraje18f.txt");
const double pi = 3.14159265358979323846;
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
std::uniform_real_distribution<> dis(0, 2*pi);
int points=1000000;
int runs=200;
int N=10000000;
int sampling=N/points;
double dt=0.001;
double dtint=sampling*dt;
double T=N*dt;
double tau=3;
double sigma=5;
double epsilon=0.01;
double omega=0.01;
double t,phi;
//double xv[points];
//double xvout[500][2];
double sqout[points];
initd(sqout,points);
double x;
int p;
//fftw_complex in[points], out[points];
fftw_complex* in = new fftw_complex[points];
fftw_complex* out = new fftw_complex[points];
for(int a=0;a<runs;a++){
p=0;
x=0;
phi=dis(gen);
for(int j2=0;j2<N;j2++){
t=j2*dt;
x=x*(1-dt/tau)+epsilon*cos(omega*t*pi+phi)*dt+sqrt((2*sigma*sigma*dt)/tau)*n(gen);
if(j2==p*sampling){
in[p][REAL]=x;
in[p][IMAG]=0;
p=p+1;
}
}
fft(in, out,points);
for(int ind=0;ind<points;ind++){
sqout[ind]=(a*sqout[ind]+(out[ind][REAL]*out[ind][REAL]+out[ind][IMAG]*out[ind][IMAG])*dtint*dtint)/(a+1);
}
}
for(int rv=0;rv<points;rv++){
myfile << rv/T << " " << sqout[rv] <<"\n";
}
myfile.close();
return 0;
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
file=open('/home/richard/NetBeansProjects/inapik/inapi0d0.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[1]))
y.append(float(row[2]))
ax=np.array(x)
ay=np.array(y)
t=np.arange(-70,-10,0.1)
vnc=(0-8*(t+80)-20*(t-60)/(1+np.exp((-20-t)/15)))/(9*(t+90))
nnc=1/(1+np.exp((-25-t)/5))
nvalues=21
vvalues=21
points=51
file2=open('/home/richard/outhome/phaseliness0.txt',"r")
x,y=[],[]
for k in file2:
row=k.split()
x.append(row[2])
y.append(row[3])
ax=np.array(x)
ay=np.array(y)
xv=np.zeros((vvalues,nvalues,points))
yv=np.zeros((vvalues,nvalues,points))
for vi in range(0,vvalues):
for ni in range(0,nvalues):
for pi in range(0,points):
xv[vi][ni][pi]=ax[(ni*vvalues+vi)*points+pi]
yv[vi][ni][pi]=ay[(ni*vvalues+vi)*points+pi]
for vi in range(0,vvalues):
for ni in range(0,nvalues):
plt.plot(yv[vi][ni][:],xv[vi][ni][:])
plt.figure()
plt.xlabel('membrane voltage V')
plt.ylabel('gating variable n')
plt.plot(t,vnc,label='v-nullcline')
plt.plot(t,nnc,label='n-nullcline')
for vi in range(0,vvalues):
for ni in range(0,nvalues):
plt.plot(yv[vi][ni][:],xv[vi][ni][:])
#plt.gcf().subplots_adjust(left=0.15)
plt.plot(ax,ay)
plt.legend()
plt.savefig('inapburstwnpp.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
date='realdrange6aem2'
nr=[9]
l=len(nr)
points=1000000
length=500000
dvalues=20
SNR=np.zeros((l,dvalues))
D=np.zeros((l,dvalues))
scale=np.zeros((l,dvalues))
ii=0
'''
for c in nr:
for z in range(1,5):
file=open('/home/richard/outhome/ft%s%d%d.txt' %(date,z,c),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
SNR[ii][z-1]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
for c in nr:
for z in range(6,21):
file=open('/home/richard/outhome/ft%s%d%d.txt' %(date,z,c),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
SNR[ii][z-2]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
'''
for c in nr:
for z in range(1,21):
file=open('/home/richard/outhome/ft%s%d%d.txt' %(date,z,c),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date,z,c),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
D[ii][z-1]=value[name.index('D')]
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-1]=epsilon**2*T
omegaind=round(omega*T)
SNR[ii][z-1]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('noise intensity D')
plt.ylabel('SNR')
#xs=np.array([0.11,0.12,0.13,0.14,0.16,0.17,0.18,0.19,0.2,0.21,0.22,0.23,0.24,0.25,0.26,0.27,0.28,0.29,0.30])
#xs=np.arange(0.31,0.51,0.01)
plt.yscale('log')
#plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
#plt.xlim(4*10**(-4),100)
for n in range(0,l):
plt.plot(D[n,:],(SNR[n,:]-1)/scale[n,:],label='I=%f' %(nr[n]*0.02-0.1))
#plt.plot(xs,SNR[2,:],label='D=3')
#plt.plot(xs,SNR[1,:],label='D=2.5')
plt.legend()
plt.tight_layout()
#plt.plot(sax2,say2/T2,label='e6')
plt.savefig('snrauto%s.pdf' %date)
<file_sep>#
# Generated - do not edit!
#
# NOCDDL
#
CND_BASEDIR=`pwd`
CND_BUILDDIR=build
CND_DISTDIR=dist
# Debug configuration
CND_PLATFORM_Debug=GNU-Linux
CND_ARTIFACT_DIR_Debug=dist/Debug/GNU-Linux
CND_ARTIFACT_NAME_Debug=irange
CND_ARTIFACT_PATH_Debug=dist/Debug/GNU-Linux/irange
CND_PACKAGE_DIR_Debug=dist/Debug/GNU-Linux/package
CND_PACKAGE_NAME_Debug=irange.tar
CND_PACKAGE_PATH_Debug=dist/Debug/GNU-Linux/package/irange.tar
# Release configuration
CND_PLATFORM_Release=GNU-Linux
CND_ARTIFACT_DIR_Release=dist/Release/GNU-Linux
CND_ARTIFACT_NAME_Release=irange
CND_ARTIFACT_PATH_Release=dist/Release/GNU-Linux/irange
CND_PACKAGE_DIR_Release=dist/Release/GNU-Linux/package
CND_PACKAGE_NAME_Release=irange.tar
CND_PACKAGE_PATH_Release=dist/Release/GNU-Linux/package/irange.tar
#
# include compiler specific variables
#
# dmake command
ROOT:sh = test -f nbproject/private/Makefile-variables.mk || \
(mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk)
#
# gmake command
.PHONY: $(shell test -f nbproject/private/Makefile-variables.mk || (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk))
#
include nbproject/private/Makefile-variables.mk
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on January 9, 2019, 2:23 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
using namespace std;
double average(long long int x[],int n);
double square(long long int x[],int n);
double ninf(double V, double k, double Vh);
double init(long long int x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
ofstream myfile2;
ofstream myfile3;
myfile.open (argv[2]);
myfile2.open (argv[3]);
myfile3.open (argv[4]);
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
double I0=-1; // 0
double dI=0.2;
double gL=8; // 8
double EL=-80; // -80
double gNa=20; // 20
double ENa=60; // 60
double gK=9; // 9
double EK=-90; // -90
double gM=5; // 5
//slow K+ current
double kinf=5; // 5
double vinf=-20; // -20
double tauM=30; // 20
//Na current
double km=15; // 15
double vm=-20; // -20
//fast K+ current
double kn=5; // 5
double vn=-25; // -20
double tau=0.152; // 0.152
int N=100000;
double v,nf;
double vs=0,nfs=0;
int j,f;
double dt=0.0004;
double D=atof(argv[1]);
double th=-25;
int runs=50;
long long int count[runs];
int Ivalues=20;
double Fano[Ivalues],Deff[Ivalues],avN2[Ivalues];
double Nav,N2av;
for(int b=0;b<Ivalues;b++){
init(count,runs);
for(int a=0;a<runs;a++){
for(j=0;j<N;j++){
v=(I0+b*dI)*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt+sqrt(2*D*dt)*n(gen);
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
if(v > th && vs < th){
count[a]=count[a]+1;
}
vs=v;
nfs=nf;
}
}
Nav=average(count,runs);
square(count,runs);
N2av=average(count,runs);
Fano[b]=(N2av-Nav*Nav)/Nav;
Deff[b]=(N2av-Nav*Nav)/;
avN2[b]=N2av;
}
for(f=0;f<Ivalues;f++){
myfile << I0+f*dI << " " << Fano[f] << "\n";
}
myfile.close();
for(int x=0;x<Ivalues;x++){
myfile2 << I0+x*dI << " " << avN[x] << "\n";
}
myfile2.close();
for(int y=0;y<Ivalues;y++){
myfile3 << I0+y*dI << " " << avN2[y] << "\n";
}
myfile3.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(long long int x[],int n){
int i;
double sum=0;
for(i=0;i<n;i++){
sum=sum+x[i];
}
double av=sum/n;
return av;
}
double square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
double init(long long int x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
def spectrum(f,tau,sigma):
return (2*tau*sigma**2)/(1+(2*np.pi*f*tau)**2)
omega=0.000005
runs=50
timefac=1000
date='realanhopf25fsamp'
mode='spike'
D=35
I=10
istart=0
ivalues=10
nr=9
#zv=[20,30,40,50,60,70,80,90,100,200]
zv=np.arange(1,11)
for z in range(istart,istart+ivalues):
freq=200*zv[z]
#freq=200*z
file=open('/home/richard/outhome/%s%s%d%d%d.txt' %(mode,date,D,I,zv[z]),"r")
#file=open('/home/richard/outhome/%s%s%d%d%d.txt' %(mode,date,D,I,z),"r")
#file=open('/home/richard/outhome/spikerealrinzel25o%d%d.txt' %(z,nr),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
l=len(ax)
if l==0:
continue
#file2=open('/home/richard/outhome/%sshort%s%d%d%d.txt' %(mode,date,D,I,z),"r")
file2=open('/home/richard/outhome/%sshort%s%d%d%d.txt' %(mode,date,D,I,zv[z]),"r")
#file=open('/home/richard/outhome/spikerealrinzel25o%d%d.txt' %(z,nr),"r")
x,y=[],[]
for k in file2:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax2=np.array(x)
ay2=np.array(y)
l2=len(ax2)
if l2==0:
continue
#param=open('/home/richard/outhome/param%s%d%d%d.txt' %(date,D,I,z),"r")
param=open('/home/richard/outhome/param%s%d%d%d.txt' %(date,D,I,zv[z]),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
T=N*repetitions*dt
#rate=open('/home/richard/outhome/g%s%d%d%d.txt' %(date,D,I,z),"r")
rate=open('/home/richard/outhome/g%s%d%d%d.txt' %(date,D,I,zv[z]),"r")
for k in rate:
row=k.split()
r=float(row[1])
rate0=open('/home/richard/outhome/grealanhopf22j3020.txt',"r")
for k in rate0:
row=k.split()
r0=float(row[1])
#background=np.mean([ay2[omegaind-1],ay2[omegaind-2],ay2[omegaind+1],ay2[omegaind+2],ay2[omegaind-3]])
#SNR=ay2[omegaind]/background
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
ind11=np.argmin(abs(ax-r0))
ind21=np.argmin(abs(ax2-r0))
ind1=np.argmax(ay[ind11-5:ind11+5])+ind11-5
ind2=np.argmax(ay2[ind21-5:ind21+5])+ind21-5
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
#plt.suptitle('I=%.2f, D=%.2f' %(-0.1+z*0.02,D*0.01))
plt.suptitle('I=%.2f, D=%.2f' %(45.5,D/100))
plt.xlabel('Frequency $[s^{-1}]$')
plt.ylabel('Spectral power')
plt.yscale('log')
plt.xscale('log')
# plt.xlim(ax[0]*timefac,10000000/(2*T)*timefac)
#plt.xlim(4*10**(-4),100)
plt.plot(ax[0:l-11]*timefac,ay[0:l-11]*ax[0]*timefac,'blue')#,label='Simulation')
plt.plot(ax[l-11:l]*timefac,ay[l-11:l]*ax[0]*timefac,'blue')
plt.plot(ax2*timefac,ay2*ax2[0]*timefac,'orange')#,label='Simulation')
plt.plot(ax[ind1]*timefac,ay[ind1]*timefac*ax[0],'x',color='blue')
plt.plot(ax2[ind2]*timefac,ay2[ind2]*timefac*ax2[0],'x',color='orange')
plt.plot(ax[0:l-11]*timefac,r*np.ones(l-11)*timefac,'g',label='running firing rate')
plt.plot(ax2[0:l2]*timefac,r*np.ones(l2)*timefac,'g')
#plt.plot(ax2,spectrum(ax2,1/(4.748*10**(-3)),13),label='theory')
#plt.plot(omega,background/T,'kx')
#plt.legend()
#plt.plot(sax2,say2/T2,label='e6')
#plt.savefig('inapikrealfrange9aspD=%.2fI=%.2f.pdf' %(D*0.01,-0.1+z*0.02))
plt.savefig('inapikanhopf%s2%sfourierD=%.2fI=%.2f.pdf' %(mode,date,D/100,freq))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def barrier(a,b,x):
return a * x + b
def qbarrier(x,a,b,c):
return a*x**2+b*x+c
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def deff(x,rp,rm,v0,av):
return ((v0+av*x)**2*rp*rm)/((rp+rm)**3)
def v(x,rp,rm,v0,av):
return ((v0+av*x)*rm)/(rp+rm)
def func(x, a, b):
return a * np.exp(-b * x)
def deffana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return ((barrier(av,v0,t))**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
def fanoana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return (2*barrier(av,v0,t)*r(r0p,ap,bp,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**2)
def vana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return barrier(av,v0,t)*r(r0m,am,bm,t,D)/(r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))
def fanofun(x,rp,rm,v0,av):
return 2*deff(x,rp,rm,v0,av)/v(x,rp,rm,v0,av)
matplotlib.rcParams.update({'font.size': 18})
timefac=1000
D1=[35]
D3=[25,30]
D2=[45]
Dvar=[]
D=D1+D2+D3+Dvar
Da=np.array(D)
l1=len(D1)
l2=len(D2)
l3=len(D3)
lvar=len(Dvar)
l=l1+l2+l3+lvar
date1='realfast11jjem2sh'
date3='realfast13aem2n4'
date2='realfast19jjem2st'
datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
yvar=[4,13,3]
yvalues=len(yvar)
istart=1
ivalues=20
epsilon = 0.00001
btoeq=np.zeros((l,ivalues))
eqtob=np.zeros((l,ivalues))
params=np.zeros((4,ivalues))
paramsav=np.zeros((4,ivalues))
params2=np.zeros(4)
paramsq=np.zeros(6)
for k2 in range(0,ivalues):
x=[]
ratefile = open('rate%s%d.txt' %('new'+date1+'new'+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,l):
btoeq[k][k2]=1/ax[k]
eqtob[k][k2]=1/ax[k+l]
av=0.013
v0=0.0637
xs=np.zeros(l)
for b in range(0,l):
xs[b]=100/Da[b]
for k2 in range(0,ivalues):
popt,pcov = curve_fit(func, xs, btoeq[:,k2])
params[0][k2]=popt[0]
params[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2])
params[2][k2]=popt[0]
params[3][k2]=popt[1]
rbte=np.mean(params[0,:])
retb=np.mean(params[2,:])
for k2 in range(0,ivalues):
popt,pcov = curve_fit(func, xs, btoeq[:,k2],bounds=((rbte-epsilon,-np.inf), (rbte+epsilon,np.inf)))
paramsav[0][k2]=popt[0]
paramsav[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2],bounds=((retb-epsilon,-np.inf), (retb+epsilon,np.inf)))
paramsav[2][k2]=popt[0]
paramsav[3][k2]=popt[1]
xnew=np.arange(-5+istart,-5+istart+ivalues)*0.02
popt,pcov = curve_fit(qbarrier, xnew, params[1,:])
paramsq[0]=popt[0]
paramsq[1]=popt[1]
paramsq[2]=popt[2]
popt,pcov = curve_fit(qbarrier, xnew, params[3,:])
paramsq[3]=popt[0]
paramsq[4]=popt[1]
paramsq[5]=popt[2]
popt,pcov = curve_fit(barrier, xnew, paramsav[1,:])
params2[0]=popt[0]
params2[1]=popt[1]
popt,pcov = curve_fit(barrier, xnew, paramsav[3,:])
params2[2]=popt[0]
params2[3]=popt[1]
eqfile2 = open('paramsdfnewpred%s.txt'%(date1+date2),'w')
for k4 in range(0,2):
eqfile2.write('%.6f\n'%params2[k4])
eqfile2.write('%.6f\n'%rbte)
for k4 in range(2,4):
eqfile2.write('%.6f\n'%params2[k4])
eqfile2.write('%.6f\n'%retb)
eqfile2.close()
paramfile = open('parambarrier%s.txt' %('new'+date1+'new'+date2),'r')
xx=[]
for k4 in paramfile:
row=k4.split()
xx.append(float(row[0]))
axx=np.array(xx)
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countI9a.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
N=50000000
dt=0.0005
T=N*dt
vvec=np.zeros(ivalues)
for ll in range(0,ivalues):
vvec[ll]=cola[2*ll+12]/T
#date10='realfast11jjem2sh'
#date20='realfast19jjem2st'
date10='realfast9acoarsetf'
date20='realfast23mtf'
ivalues=20
rbtoeq=np.zeros(ivalues)
ubtoeq=np.zeros(ivalues)
reqtob=np.zeros(ivalues)
ueqtob=np.zeros(ivalues)
for k2 in range(0,ivalues):
x=[]
#ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/param%s%d.txt' %('new'+date10+'new'+date20,k2),'r')
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/param%s%d.txt' %(date10+date20,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
rbtoeq[k2]=x[0]
ubtoeq[k2]=x[1]
reqtob[k2]=x[2]
ueqtob[k2]=x[3]
def rred(r0,U,D):
return r0*np.exp(-U/D)
def deffred(rp,up,rm,um,v,D):
return (v**2*rred(rp,up,D)*rred(rm,um,D))/((rred(rp,up,D)+rred(rm,um,D))**3)
def vred(rp,up,rm,um,v,D):
return v*rred(rm,um,D)/(rred(rp,up,D)+rred(rm,um,D))
def fanored(rp,up,rm,um,v,D):
return 2*deffred(rp,up,rm,um,v,D)/vred(rp,up,rm,um,v,D)
xs=np.arange(-5+istart,-5+istart+ivalues)*0.02
pv=np.arange(0,ivalues)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ [$s^{-1}$]')
#plt.xlim(0,3.5)
#plt.ylim(5*10**(-2),2*10**3)
plt.yscale('log')
plt.xlim(-0.08,0.2)
Dvec=[2,3,4,5]
#colorv=['g','y','b','r','c']
colorv=[ '#1f77b4', '#ff7f0e', '#2ca02c','#d62728','#9467bd']
t=np.arange(-0.1,0.3,0.01)
#for n in range(0,l):
# plt.plot(t,deffana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#for n in range(0,l):
# plt.plot(t,deffana(axx[2],axx[5],axx[0],axx[3],axx[1],axx[4],t,Da[n]/100,av,v0),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,l):
plt.plot((pv-4)*0.02,deffred(rbtoeq[pv],ubtoeq[pv],reqtob[pv],ueqtob[pv],vvec[pv],Dvec[n]/100)*timefac,colorv[n],label='D=%.2f'%(Dvec[n]/100))
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.plot([0.165, 0.165], [10**(-35), 10**39], color='black', linestyle='-', label='$I_{crit}$')
plt.plot([-0.022, -0.022], [10**(-35), 10**39], color='black', linestyle='-')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,3,0,1,4]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order],loc='upper right', bbox_to_anchor=(0.65, 0.55))
plt.legend(loc='upper right', bbox_to_anchor=(0.8, 0.67))
plt.tight_layout()
plt.savefig('dcompdfpwnewpred3%s.pdf' %(date1+date2))
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('firing rate r [$s^{-1}$]')
#plt.yscale('log')
#colorv=['b','r','g','y','c']
t=np.arange(-0.1,0.3,0.01)
#for n in range(0,l):
# plt.plot(t,vana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,l):
plt.plot((pv-4)*0.02,vred(rbtoeq[pv],ubtoeq[pv],reqtob[pv],ueqtob[pv],vvec[pv],Dvec[n]/100)*timefac,colorv[n],label='D=%.2f'%(Dvec[n]/100))
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,3,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order],loc='lower right')
plt.legend()
plt.tight_layout()
plt.savefig('gcompdfpwnewpred3%s.pdf' %(date1+date2))
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Fano factor F')
plt.yscale('log')
plt.xlim(-0.08,0.2)
#colorv=['b','r','g','y','c']
t=np.arange(-0.1,0.3,0.01)
#for n in range(0,l):
# plt.plot(t,fanoana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,l):
plt.plot((pv-4)*0.02,fanored(rbtoeq[pv],ubtoeq[pv],reqtob[pv],ueqtob[pv],vvec[pv],Dvec[n]/100),colorv[n],label='D=%.2f'%(Dvec[n]/100))
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.plot([0.165, 0.165], [10**(-20), 10**40], color='black', linestyle='-', label='$I_{crit}$')
plt.plot([-0.022, -0.022], [10**(-20), 10**40], color='black', linestyle='-')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,3,0,1,4]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order],loc='lower left')
plt.legend()
plt.tight_layout()
plt.savefig('fcompdfpwnewpred3%s.pdf' %(date1+date2))
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on June 27, 2019, 9:20 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <iostream>
using namespace std;
double ninf(double V, double k, double Vh);
void init(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
myfile.open ("countInew3.txt");
double I0=0; // 0
double gL=0.3; // 8
double EL=-80; // -80
double gNa=1; // 20
double ENa=60; // 60
double gK=0.4; // 9
double EK=-90; // -90
//Na current
double km=14; // 15
double vm=-18; // -20
//fast K+ current
double kn=5; // 5
double vn=-25; // -20
double tau=3; // 0.152
int N0;
N0=50000000;
int runs=50;
double count[runs];
double v,vs,nf,nfs;
double th=-25;
vs=-30;
nfs=0.2;
int j,f;
double dt,dt0;
dt0=0.0001;
init(count,runs);
for(int a=0;a<runs;a++){
dt=dt0*(a+1);
int N=round(N0/(a+1));
for(j=0;j<N;j++){
v=I0*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt;
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
if(v > th && vs < th){
count[a]=count[a]+1;
}
vs=v;
nfs=nf;
}
}
for(f=0;f<runs;f++){
myfile << dt0*(f+1) << " " << count[f] << "\n";
}
myfile.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
void init(double x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def deff(r0p,r0m,ap,am,bp,bm,t,D,v):
return (v**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
file=open('/home/richard/NetBeansProjects/parambarrier16m.txt',"r")
x=[]
for k in file:
row=k.split()
x.append(float(row[0]))
ax=np.array(x)
t=np.arange(0,4,0.01)
ap=ax[0]
am=ax[3]
bp=ax[1]
bm=ax[4]
r0p=ax[2]
r0m=ax[5]
v=1.33
veco=np.zeros((2,16))
vec=np.zeros((3,20))
ii=0
for x in [12]:
col=[]
for y in range(5,6):
file=open('/home/richard/outhome/d26a%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
col.append(float(row[1]))
for y in range(7,21):
file=open('/home/richard/outhome/d26a%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,16):
veco[0][z]=cola[z]
for x in [20]:
col=[]
for y in range(5,21):
file=open('/home/richard/outhome/d16m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,16):
veco[1][z]=cola[z]
for x in [30,40,50]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/d7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
#for x in [40]:
# col=[]
# for y in range(5,21):
# file=open('/home/richard/outhome/g17a%d%d.txt' % (x,y),"r")
# for k in file:
# row=k.split()
# col.append(row[1])
# cola=np.array(col)
# for z in range(0,16):
# vec[ii][z]=cola[z]
# ii=ii+1
xso=np.arange(0.25,4.25,0.25)
xs=np.arange(-0.75,4.25,0.25)
xsh=np.arange(1,4.2,0.2)
plt.xlabel('bias current I')
plt.ylabel('$D_{eff}$')
plt.xlim(0.5,3)
plt.ylim(5*10**(-2),2*10**3)
plt.yscale('log')
plt.plot(t,deff(r0p,r0m,ap,am,bp,bm,t,2,v),'y')
plt.plot(t,deff(r0p,r0m,ap,am,bp,bm,t,3,v),'g')
plt.plot(t,deff(r0p,r0m,ap,am,bp,bm,t,4,v),'b')
plt.plot(t,deff(r0p,r0m,ap,am,bp,bm,t,5,v),'r')#,label='D=%d,theory' %k)
#plt.plot(xsh,veco[0,:],label='D=1.2')
plt.plot(xso,veco[1,:],'yo',label='D=2')
plt.plot(xs,vec[0,:],'go',label='D=3')
plt.plot(xs,vec[1,:],'bo',label='D=4')
plt.plot(xs,vec[2,:],'ro',label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('dcomp16mp.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
date='realfrange8aem2'
nr=[30]
l=len(nr)
points=1000000
length=500000
fvalues=20
SNR=np.zeros((l,fvalues))
omegavec=np.zeros((l,fvalues))
scale=np.zeros((l,fvalues))
ii=0
for c in nr:
for z in range(1,21):
file=open('/home/richard/outhome/ft%s%d%d.txt' %(date,c,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date,c,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
omegavec[ii][z-1]=omega
T=N*repetitions*dt
scale[ii][z-1]=epsilon**2*T
omegaind=round(omega*T)
SNR[ii][z-1]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('signal frequency')
plt.ylabel('SNR')
#xs=omega0*np.square(np.arange(1,21))
plt.yscale('log')
plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
#plt.ylim(1,100)
for n in range(0,l):
plt.plot(omegavec[n,:],(SNR[n,:]-1)/scale[n,:],label='I=0.08,D=%f' %(nr[n]*0.01+0.1))
#plt.plot(xs,SNR[2,:],label='D=3')
#plt.plot(xs,SNR[1,:],label='D=2.5')
plt.legend()
#plt.plot(sax2,say2/T2,label='e6')
plt.savefig('snrautofrange8a.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on May 26, 2019, 6:06 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <ios>
#include <iomanip>
#include <complex>
#include <iostream>
#include <valarray>
const double PI = 3.141592653589793238460;
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
void fft(CArray &x)
{
// DFT
unsigned int N = x.size(), k = N, n;
double thetaT = 3.14159265358979323846264338328L / N;
Complex phiT = Complex(cos(thetaT), -sin(thetaT)), T;
while (k > 1)
{
n = k;
k >>= 1;
phiT = phiT * phiT;
T = 1.0L;
for (unsigned int l = 0; l < k; l++)
{
for (unsigned int a = l; a < N; a += n)
{
unsigned int b = a + k;
Complex t = x[a] - x[b];
x[a] += x[b];
x[b] = t * T;
}
T *= phiT;
}
}
// Decimate
unsigned int m = (unsigned int)log2(N);
for (unsigned int a = 0; a < N; a++)
{
unsigned int b = a;
// Reverse bits
b = (((b & 0xaaaaaaaa) >> 1) | ((b & 0x55555555) << 1));
b = (((b & 0xcccccccc) >> 2) | ((b & 0x33333333) << 2));
b = (((b & 0xf0f0f0f0) >> 4) | ((b & 0x0f0f0f0f) << 4));
b = (((b & 0xff00ff00) >> 8) | ((b & 0x00ff00ff) << 8));
b = ((b >> 16) | (b << 16)) >> (32 - m);
if (b > a)
{
Complex t = x[a];
x[a] = x[b];
x[b] = t;
}
}
//// Normalize (This section make it not working correctly)
//Complex f = 1.0 / sqrt(N);
//for (unsigned int i = 0; i < N; i++)
// x[i] *= f;
}
// inverse fft (in-place)
void ifft(CArray& x)
{
// conjugate the complex numbers
x = x.apply(std::conj);
// forward fft
fft( x );
// conjugate the complex numbers again
x = x.apply(std::conj);
// scale the numbers
x /= x.size();
}
int main(int argc, char** argv) {
std::ofstream myfile;
myfile.open("xtraj.txt");
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
int runs=10;
int N=100000;
int points=100000;
int sampling=N*runs/points;
int j22;
double dt=0.001;
double T0=N*runs*dt;
double tau=1;
double sigma=1;
Complex xv[points];
double xvout[points];
int p=0;
double x=0;
for(int a=0;a<runs;a++){
for(int j2=0;j2<N;j2++){
j22=j2+a*N;
x=x*(1-dt/tau)+sqrt((2*sigma*sigma*dt)/tau)*n(gen);
if(j22==p*sampling){
xv[p]=x;
p=p+1;
}
}
}
CArray data(xv, points);
// forward fft
fft(data);
for(int b=0;b<points;b++){
xvout[b]=std::abs(data[b])*std::abs(data[b]);
}
for(int rv=0;rv<points;rv++){
myfile << rv/T0 << " " << xvout[rv] <<"\n";
}
myfile.close();
return 0;
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def barrier(a,b,x):
return a * x + b
def r(r0,U,D):
return r0*np.exp(-U/D)
def deff(rp,up,rm,um,v,D):
return (v**2*r(rp,up,D)*r(rm,um,D))/((r(rp,up,D)+r(rm,um,D))**3)
first=5
total=11
deffs=4
rp=np.zeros(total)
up=np.zeros(total)
rm=np.zeros(total)
um=np.zeros(total)
for k2 in range(first,first+total):
x=[]
paramfile = open('param16m%d.txt' %k2,'r')
for k4 in paramfile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
rp[k2-first]=ax[0]
up[k2-first]=ax[1]
rm[k2-first]=ax[2]
um[k2-first]=ax[3]
v=1.33
veco=np.zeros((1,16))
vec=np.zeros((3,20))
ii=0
for x in [20]:
col=[]
for y in range(5,21):
file=open('/home/richard/outhome/d16m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,16):
veco[0][z]=cola[z]
for x in [30,40,50]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/d7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
#for x in [40]:
# col=[]
# for y in range(5,21):
# file=open('/home/richard/outhome/g17a%d%d.txt' % (x,y),"r")
# for k in file:
# row=k.split()
# col.append(row[1])
# cola=np.array(col)
# for z in range(0,16):
# vec[ii][z]=cola[z]
# ii=ii+1
xfit=np.arange(0.5,3.25,0.25)
xso=np.arange(0.25,4.25,0.25)
xs=np.arange(-0.75,4.25,0.25)
xsh=np.arange(1,4.2,0.2)
plt.xlabel('bias current I')
plt.ylabel('$D_{eff}$')
plt.xlim(0.5,3)
plt.ylim(5*10**(-2),2*10**3)
plt.yscale('log')
plt.plot(xfit,deff(rp,up,rm,um,v,2),'y')#,label='D=2,theory' )
plt.plot(xfit,deff(rp,up,rm,um,v,3),'g')#,label='D=3,theory' )
plt.plot(xfit,deff(rp,up,rm,um,v,4),'b')#,label='D=4,theory' )
plt.plot(xfit,deff(rp,up,rm,um,v,5),'r')#,label='D=5,theory' )
#plt.plot(xsh,veco[0,:],label='D=1.2')
plt.plot(xso,veco[0,:],'yo',label='D=2')
plt.plot(xs,vec[0,:],'go',label='D=3')
plt.plot(xs,vec[1,:],'bo',label='D=4')
plt.plot(xs,vec[2,:],'ro',label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('dcompdw16m.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
v=open('/home/richard/cppworkshop/phasev11stime0.1.txt',"r")
vv=[]
for k in v:
num = float(k.rstrip())
vv.append(num)
av=np.array(vv)
vl=len(av)
n=open('/home/richard/cppworkshop/phasen11stime0.1.txt',"r")
vn=[]
for k2 in n:
num = float(k2.rstrip())
vn.append(num)
an=np.array(vn)
nl=len(an)
z=open('/home/richard/cppworkshop/phasez11stime0.1.txt',"r")
vz=np.zeros((nl,vl))
v=0
for k3 in z:
rowz=k3.split()
rowza=np.array(rowz)
for f in range(0,vl):
vz[v][f]=rowza[f]
v=v+1
def finf(x,v12,k):
return 1/(1+np.exp((v12-x)/k))
def vnc(x,I,v12,k,gL,EL,gNa,ENa,gK,EK):
return (I-gL*(x-EL)-gNa*finf(x,v12,k)*(x-ENa))/(gK*(x-EK))
I=0.1
gL=0.3
EL=-80
gNa=1
ENa=60
gK=0.4
EK=-90
km=14
vm=-18
kn=5
vn=-25
tau=3
#b=1.65+0.0261*t
#s=0.76*np.sin((t+56)*np.pi/80)
t=np.arange(av[0],av[-1]+0.01,0.01)
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
plt.contourf(av,an,abs(vz))
plt.colorbar()
plt.plot(t,vnc(t,I,vm,km,gL,EL,gNa,ENa,gK,EK),label='v-nullcline')
plt.plot(t,finf(t,vn,kn),label='n-nullcline')
#plt.plot(t,b,label='barrier')
#plt.plot(t,s,label='barrier2')
#plt.plot(-62.5701,0.00054509, 'bo')
#plt.ylim(-0.1,an[-1])
plt.suptitle('equil. time [ms]')
plt.xlabel('initial $V_0$')
plt.ylabel('initial $n_0$')
#plt.legend()
plt.tight_layout()
plt.savefig('contoureqtime01wn3.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on January 8, 2019, 12:48 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <iostream>
#include <math.h>
using namespace std;
double init(double x[],int n);
double Ninf(double V);
double minf(double V);
double hinf(double V);
int main(int argc, char** argv) {
ofstream myfile;
myfile.open ("countrinzel.txt");
double I0=-21; // 0
double S=1.27;
double phi=3.82;
double dI=0.3;
double gL=0.3; // 8
double EL=10; // -80
double gNa=120; // 20
double ENa=115; // 60
double gK=36; // 9
double EK=12; // -90
int N0;
N0=50000000;
int runs=51;
double count[runs];
double v,vs,wf,wfs;
double th=40;
vs=30;
wfs=0.2;
int j,f;
double dt;
dt=0.0005;
init(count,runs);
for(int a=0;a<runs;a++){
for(j=0;j<N0;j++){
v =(I0+a*dI)*dt+vs-gL*(vs-EL)*dt-gNa*pow(minf(vs),3)*(1-wfs)*(vs-ENa)*dt-gK*pow(wfs/S,4)*(vs-EK)*dt;
wf=wfs+phi*((S*(Ninf(vs)+S*(1-hinf(vs)))/(1+(S*S)))-wfs)*dt/(5*exp(-pow((vs+10)/55,2))+1);
if(wf >1){
wf=1;
}
if(v > th && vs < th){
count[a]=count[a]+1;
}
vs=v;
wfs=wf;
}
}
for(f=0;f<runs;f++){
myfile << I0+dI*f << " " << count[f] << "\n";
}
myfile.close();
return 0;
}
double init(double x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double Ninf(double V){
double f=((10-V)/(100*(exp((10-V)/10)-1)))/((10-V)/(100*(exp((10-V)/10)-1))+exp(-V/80)/8);
return f;
}
double minf(double V){
double f=((25-V)/(10*(exp((25-V)/10)-1)))/((25-V)/(10*(exp((25-V)/10)-1))+4*exp(-V/18));
return f;
}
double hinf(double V){
double f=(7*exp(-V/20)/100)/(7*exp(-V/20)/100+1/(exp((30-V)/10)+1));
return f;
}<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def finf(x,v12,k):
return 1/(1+np.exp((v12-x)/k))
def vnc(x,I,v12,k,gL,EL,gNa,ENa,gK,EK):
return (I-gL*(x-EL)-gNa*finf(x,v12,k)*(x-ENa))/(gK*(x-EK))
I=45
gL=1
EL=-78
gNa=4
ENa=60
gK=4
EK=-90
km=7
vm=-30
kn=5
vn=-45
tau=1
file=open('/home/richard/mastergit/NetBeansProjects/realstatevar/realstateanhopf5.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[1]))
y.append(float(row[2]))
ax=np.array(x)
ay=np.array(y)
#ayi=ay[::-1]
t=np.arange(-70,0,0.1)
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
axs = plt.subplot(111)
plt.suptitle('$I$=45$\mu A/cm^2$')
#plt.xlabel('time [s]')
plt.xlabel('membrane voltage V [mV]')
plt.ylabel('gating variable n')
plt.plot(t,vnc(t,I,vm,km,gL,EL,gNa,ENa,gK,EK),label='v-nullcline')
plt.plot(t,finf(t,vn,kn),label='n-nullcline')
#plt.gcf().subplots_adjust(left=0.15)
#plt.plot(abs(ax[0:1000])/1000,ayi[0:1000],'black')
#plt.xlim(39.97,40.17)
axs.plot(ax[4*33770:4*33970],ay[4*33770:4*33970],'black')
#plt.xlim(0,0.2)
#plt.xlim(0,0.05)
#plt.ylim(0.1,0.4)
plt.legend()
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
plt.tight_layout()
plt.savefig('inaprealanhopfreal5psh.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
file=open('/home/richard/mastergit/NetBeansProjects/realstatevar/realstate15.txt',"r")
x,y,z,a=[],[],[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
z.append(float(row[3]))
#a.append(float(row[4]))
ax=np.array(x)
ay=np.array(y)
az=40*np.array(z)-50
#aa=-np.array(a)/40
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
axs = plt.subplot(111)
plt.suptitle('$I$=$0.15\mu A/cm^2$')
#plt.suptitle('I=0')
plt.xlabel('time [s]')
plt.ylabel('membrane voltage [mV]')
plt.xlim(7.25,7.65)
axs.plot(ax/1000,ay,'black')
#plt.plot(ax/1000,az)
#plt.plot(ax,aa)
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
plt.tight_layout()
plt.savefig('realstatevar15sh.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
from scipy.optimize import curve_fit
matplotlib.rcParams.update({'font.size': 16})
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def snr(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,av,v0):
return (qr(r0m,am,bm,cm,t,D)*(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))/(v0**2*qr(r0p,ap,bp,cp,t,D)))*((((2*ap*t+bp)-(2*am*t+bm))*qr(r0p,ap,bp,cp,t,D)*v0)/(D*(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D)))+av)**2
def qbarrier(x,a,b,c):
return a*x**2+b*x+c
def qr(r0,a,b,c,t,D):
return r0*np.exp(-qbarrier(t,a,b,c)/D)
def deff(x,rp,rm,v0,av):
return ((v0+av*x)**2*rp*rm)/((rp+rm)**3)
def fano(x,rp,rm,v0,av):
return (2*(v0+av*x)*rp)/((rp+rm)**2)
def func(x, a, b):
return a * np.exp(-b * x)
def deffana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return ((barrier(av,v0,t))**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
def deffqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,av,v0):
return ((barrier(av,v0,t))**2*qr(r0p,ap,bp,cp,t,D)*qr(r0m,am,bm,cm,t,D))/((qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))**3)
def fanoana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return (2*barrier(av,v0,t)*r(r0p,ap,bp,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**2)
def vana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return barrier(av,v0,t)*r(r0m,am,bm,t,D)/(r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))
def vqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,av,v0):
return barrier(av,v0,t)*qr(r0m,am,bm,cm,t,D)/(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))
def comp(x,b,c,d,e):
return b*x**3+c*x**2+d*x+e
def comps(x,b,c,d):
return 3*b*x**2+2*c*x+d
date3='realrinzel25o'
date2='realrinzel15ninv0'
ivalues=11
l=3
D1=[]
D3=[500]
D2=[200,300]
Dvar=[]
D=D1+D2+D3+Dvar
Da=np.array(D)
btoeq=np.zeros((l,ivalues))
eqtob=np.zeros((l,ivalues))
params=np.zeros((4,ivalues))
paramsav=np.zeros((4,ivalues))
params2=np.zeros(4)
paramsq=np.zeros(6)
paramsqrate=np.zeros(6)
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/rate%s%d.txt' %(date3+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,l):
btoeq[k][k2]=1/ax[k]
eqtob[k][k2]=1/ax[k+l]
av=0.1/12
v0=0.47
xs=np.zeros(l)
for b in range(0,l):
xs[b]=10/Da[b]
for k2 in range(0,ivalues):
popt,pcov = curve_fit(func, xs, btoeq[:,k2])
params[0][k2]=popt[0]
params[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2])
params[2][k2]=popt[0]
params[3][k2]=popt[1]
rbte=np.mean(params[0,:])
retb=np.mean(params[2,:])
istart=1
xnew=np.arange(-22.5+istart,-22.5+istart+ivalues)*0.8
#barrier fit
popt,pcov = curve_fit(qbarrier, xnew, params[1,:])
paramsq[0]=popt[0]
paramsq[1]=popt[1]
paramsq[2]=popt[2]
popt,pcov = curve_fit(qbarrier, xnew, params[3,:])
paramsq[3]=popt[0]
paramsq[4]=popt[1]
paramsq[5]=popt[2]
#prefactor fit
popt,pcov = curve_fit(qbarrier, xnew, params[0,:])
paramsqrate[0]=popt[0]
paramsqrate[1]=popt[1]
paramsqrate[2]=popt[2]
popt,pcov = curve_fit(qbarrier, xnew, params[2,:])
paramsqrate[3]=popt[0]
paramsqrate[4]=popt[1]
paramsqrate[5]=popt[2]
t1=np.arange(-18,-9,0.1)
plt.figure()
plt.plot(xnew,params[1,:],'go',label='burst to eq')
plt.plot(xnew,params[3,:],'ro',label='eq to burst')
plt.plot(t1,qbarrier(t1,paramsq[0],paramsq[1],paramsq[2]),'g')
plt.plot(t1,qbarrier(t1,paramsq[3],paramsq[4],paramsq[5]),'r')
plt.legend()
plt.savefig('barrierinzelfit4.pdf')
plt.figure()
plt.plot(xnew,params[0,:],'go',label='burst to eq')
plt.plot(xnew,params[2,:],'ro',label='eq to burst')
plt.plot(t1,qbarrier(t1,paramsqrate[0],paramsqrate[1],paramsqrate[2]),'g')
plt.plot(t1,qbarrier(t1,paramsqrate[3],paramsqrate[4],paramsqrate[5]),'r')
plt.legend()
plt.savefig('raterinzelfit4.pdf')
bp = 1.74
ap = 5.64
r0p = 0.0075
bm = 3.15
am = -10.76
r0m = 0.012
date='realrinzelrangelong26d1'
date1='realrinzelrange26d1'
date0='realrinzelrangeshort26d1'
date2='realrinzel13sig1'
D=[200]
D1=[250,300]
D0=[400,500]
D2=[]
Dtot=D+D1+D0+D2
l2=len(D)+len(D1)+len(D0)+len(D2)
points=1000000
length=500000
ivalues=10
istart=1
SNR=np.zeros((l2,ivalues))
scale=np.zeros((l2,ivalues))
xvec=np.zeros((l2,ivalues))
offset=np.zeros(l2,dtype=int)
ii=0
for c in D:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date,c,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
if len(x) == 0:
offset[ii]=offset[ii]+1
continue
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date,c,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart-offset[ii]]=epsilon**2*T
omegaind=round(omega*T)
#if c==200 and z==9:
# omegaind=2105
#omegaind=141
SNR[ii][z-istart-offset[ii]]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
iv=open('/home/richard/outhome/d%s%d%d.txt' %(date,c,z),"r")
for k in iv:
row=k.split()
xvec[ii][z-istart-offset[ii]]=float(row[0])
ii=ii+1
for c1 in D1:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date1,c1,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
if len(x) == 0:
offset[ii]=offset[ii]+1
continue
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date1,c1,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart-offset[ii]]=epsilon**2*T
omegaind=round(omega*T)
#omegaind=141
SNR[ii][z-istart-offset[ii]]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
iv=open('/home/richard/outhome/d%s%d%d.txt' %(date1,c1,z),"r")
for k in iv:
row=k.split()
xvec[ii][z-istart-offset[ii]]=float(row[0])
ii=ii+1
for c0 in D0:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date0,c0,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
if len(x) == 0:
offset[ii]=offset[ii]+1
continue
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date0,c0,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart-offset[ii]]=epsilon**2*T
omegaind=round(omega*T)
#omegaind=141
SNR[ii][z-istart-offset[ii]]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
iv=open('/home/richard/outhome/d%s%d%d.txt' %(date0,c0,z),"r")
for k in iv:
row=k.split()
xvec[ii][z-istart-offset[ii]]=float(row[0])
ii=ii+1
for c2 in D2:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date2,c2,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
if len(x) == 0:
offset[ii]=offset[ii]+1
continue
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date2,c2,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart-offset[ii]]=epsilon**2*T
omegaind=round(omega*T)
#omegaind=141
SNR[ii][z-istart-offset[ii]]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
iv=open('/home/richard/outhome/d%s%d%d.txt' %(date2,c2,z),"r")
for k in iv:
row=k.split()
xvec[ii][z-istart-offset[ii]]=float(row[0])
ii=ii+1
params=4
dvalues=6
b=np.zeros(dvalues)
c=np.zeros(dvalues)
d=np.zeros(dvalues)
e=np.zeros(dvalues)
ii=0
#xnew=np.arange(-0.19,0.31,0.01)
eqfile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/detmocountparam5.txt','r')
for k in eqfile:
col=[]
row=k.split()
for l in range(0,params):
col.append(float(row[l]))
cola=np.array(col)
b[ii]=cola[0]
c[ii]=cola[1]
d[ii]=cola[2]
e[ii]=cola[3]
ii=ii+1
eqfile.close()
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
nlfile = open('nl%s.txt' % (date0+date1),'w')
for k3 in range(0,l2):
nlfile.write('%.0f\n'%offset[k3])
nlfile.close()
plt.figure()
plt.xlabel('bias current')
plt.ylabel('SNR')
t=np.arange(-18,-8,0.1)
#xs=np.arange(-21.25+istart,-21.25+istart+ivalues)*0.8
xs=np.arange(-20+istart,-20+istart+ivalues)*0.6
plt.yscale('log')
#plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
#plt.xlim(4*10**(-4),100)
colorv=['r','y','c','g','k','b'] # 6 colors
#colorv=['y','g','b'] # 3 colors
#colorv=['y','c','g','k','b'] # 5 colors
for n in range(0,l2):
nl=round(ivalues-offset[n])
#plt.plot(xvec[n,0:nl],(SNR[n,0:nl]-1)/scale[n,0:nl],colorv[n]+'o',label='D=%.2f' %(Dtot[n]*0.1))
plt.plot(xvec[n,0:nl],abs((SNR[n,0:nl]-1))/scale[n,0:nl],label='D=%.0f' %(Dtot[n]*0.1))
#for n in range(0,l2):
#bv=b[2*n+1] # 3 plots
#cv=c[2*n+1]
#dv=d[2*n+1]
#ev=e[2*n+1]
#bv=b[n+1] # 5
#cv=c[n+1]
#dv=d[n+1]
#ev=e[n+1] #plt.plot(t,snr(rbte,retb,paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[n]*0.1,comps(t,b[n+1],c[n+1],d[n+1]),comp(t,b[n+1],c[n+1],d[n+1],e[n+1]))/8,colorv[n])
#plt.plot(t,snr(rbte,retb,paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[n]*0.1,comps(t,bv,cv,dv),comp(t,bv,cv,dv,ev))/8,colorv[n])
#plt.plot(t,snr(qbarrier(t,paramsqrate[0],paramsqrate[1],paramsqrate[2]),qbarrier(t,paramsqrate[3],paramsqrate[4],paramsqrate[5]),paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[n]*0.1,comps(t,bv,cv,dv),comp(t,bv,cv,dv,ev))/8,colorv[n])
#plt.plot(t,snr(qbarrier(t,paramsqrate[0],paramsqrate[1],paramsqrate[2]),qbarrier(t,paramsqrate[3],paramsqrate[4],paramsqrate[5]),paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[3]*0.1,comps(t,b[5],c[5],d[5]),comp(t,b[5],c[5],d[5],e[5]))/8,colorv[3])
#plt.plot([0.163, 0.163], [10**(-7), 10], color='black', linestyle='-')
#plt.plot([-0.02, -0.02], [10**(-7), 10], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot(xs,SNR[2,:],label='D=3')
#plt.plot(xs,SNR[1,:],label='D=2.5')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [0,2,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
#plt.plot(sax2,say2/T2,label='e6')
plt.plot([-10.8, -10.8], [10**(-8), 10**(-3)], color='black', linestyle='-',label='$I_{crit}$')
plt.legend()
plt.tight_layout()
plt.savefig('snrinzelrange26dcompletecrit.pdf')
#plt.savefig('snrinzelonly.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
eqreltime=np.zeros((1,20))
breltime=np.zeros((1,20))
ii=0
dt=0.00001
N=50000000
Neq=10000000
Ndiff=N-Neq
for x in [30]:
for y in range(1,21):
times,avalues,j2values,state=[],[],[],[]
file=open('/home/richard/outhome/time17a%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
avalues.append(float(row[1]))
j2values.append(float(row[2]))
state.append(float(row[3]))
j2valuesa=np.array(j2values)
avaluesa=np.array(avalues)
statea=np.array(state)
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]+j2valuesa[2*z]/Ndiff:
inteq[z]=((avaluesa[2*z+1]-avaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if avaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
intb[z]=((avaluesa[2*z+2]-avaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]+j2valuesa[2*z]/Ndiff:
intb[z]=((avaluesa[2*z+1]-avaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if avaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
inteq[z]=((avaluesa[2*z+2]-avaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
#plt.figure()
#plt.hist(intbt, bins=50)
#plt.yscale('log')
#plt.title("distribution of bursting time intervals")
#plt.savefig('bdistaj2%d%d.pdf' %(x,y))
#plt.figure()
#plt.hist(inteqt, bins=50)
#plt.yscale('log')
#plt.title("distribution of equilibrium time intervals")
#plt.savefig('eqdistaj2%d%d.pdf' %(x,y))
eqtot=np.sum(inteqt)
btot=np.sum(intbt)
eqrel=eqtot/(eqtot+btot)
brel=btot/(eqtot+btot)
eqreltime[ii][y-1]=eqrel
breltime[ii][y-1]=brel
ii=ii+1
plt.figure()
xs=np.arange(-0.75,4.25,0.25)
plt.xlabel('bias current I')
plt.ylabel('proportion of simulation time')
plt.plot(xs,eqreltime[0,:],label='D=4,burst')
#plt.plot(xs,eqreltime[1,:],label='D=2,burst')
#plt.plot(xs,eqreltime[2,:],label='D=3,burst')
#plt.plot(xs,eqreltime[3,:],label='D=4,burst')
plt.plot(xs,breltime[0,:],label='D=4,equilibrium')
#plt.plot(xs,breltime[1,:],label='D=2,equilibrium')
#plt.plot(xs,breltime[2,:],label='D=3,equilibrium')
#plt.plot(xs,breltime[3,:],label='D=4,equilibrium')
plt.legend()
plt.savefig('inapiktimes173.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b):
return a * np.exp(-b * x)
def func2(x, a, b):
return a * x + b
def func3(x, a):
return a
date='29m'
params2=np.zeros(6)
params=np.zeros((4,11))
changespertime=np.zeros((3,20))
eqtottime=np.zeros((3,20))
eqreltime=np.zeros((3,20))
btottime=np.zeros((3,20))
breltime=np.zeros((3,20))
ii=0
dt=0.00001
N0=320000000
Neq0=50000000
Ndiff0=N0-Neq0
repetitions=500
runs0=10
for x in [12]:
for y in [1,2,3,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20]:
times,avalues,jrvalues,j2values,state=[],[],[],[],[]
file=open('/home/richard/outhome/time26a%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
avalues.append(float(row[1]))
jrvalues.append(float(row[2]))
j2values.append(float(row[3]))
state.append(float(row[4]))
j2valuesa=np.array(j2values)
jrvaluesa=np.array(jrvalues)
avaluesa=np.array(avalues)
statea=np.array(state)
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff0>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff0:
inteq[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff0+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff0>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff0:
intb[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff0+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff0>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff0:
intb[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff0+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff0>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff0:
inteq[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff0+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
counts=counteq+countb
countsrel=counts/Ndiff0
changespertime[ii][y-1]=countsrel/(repetitions*runs0)
#plt.figure()
#plt.hist(intbt, bins=50)
#plt.yscale('log')
#plt.title("distribution of bursting time intervals")
#plt.savefig('bdistajrj2%d%d.pdf' %(x,y))
#plt.figure()
#plt.hist(inteqt, bins=50)
#plt.yscale('log')
#plt.title("distribution of equilibrium time intervals")
#plt.savefig('eqdistajrj2%d%d.pdf' %(x,y))
eqtot=np.sum(inteqt)
btot=np.sum(intbt)
eqrel=eqtot/(eqtot+btot)
brel=btot/(eqtot+btot)
eqtottime[ii][y-1]=eqtot/counteq
btottime[ii][y-1]=btot/countb
eqreltime[ii][y-1]=eqrel
breltime[ii][y-1]=brel
changespertime[ii][3]=changespertime[ii][2]
changespertime[ii][5]=changespertime[ii][4]
btottime[ii][3]=btottime[ii][2]
btottime[ii][5]=btottime[ii][4]
eqtottime[ii][3]=eqtottime[ii][2]
eqtottime[ii][5]=eqtottime[ii][4]
breltime[ii][3]=breltime[ii][2]
breltime[ii][5]=breltime[ii][4]
eqreltime[ii][3]=eqreltime[ii][2]
eqreltime[ii][5]=eqreltime[ii][4]
#ii=ii+1
N=200000000
Neq=20000000
Ndiff=N-Neq
repetitions=200
runs=50
for x in [25]:
for y in range(1,21):
times,avalues,jrvalues,j2values,state=[],[],[],[],[]
file=open('/home/richard/outhome/time%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
avalues.append(float(row[1]))
jrvalues.append(float(row[2]))
j2values.append(float(row[3]))
state.append(float(row[4]))
j2valuesa=np.array(j2values)
jrvaluesa=np.array(jrvalues)
avaluesa=np.array(avalues)
statea=np.array(state)
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
inteq[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
intb[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
intb[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
inteq[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
counts=counteq+countb
countsrel=counts/Ndiff
changespertime[ii][y-1]=countsrel/(repetitions*runs)
#plt.figure()
#plt.hist(intbt, bins=50)
#plt.yscale('log')
#plt.title("distribution of bursting time intervals")
#plt.savefig('bdistajrj2%d%d.pdf' %(x,y))
#plt.figure()
#plt.hist(inteqt, bins=50)
#plt.yscale('log')
#plt.title("distribution of equilibrium time intervals")
#plt.savefig('eqdistajrj2%d%d.pdf' %(x,y))
eqtot=np.sum(inteqt)
btot=np.sum(intbt)
eqrel=eqtot/(eqtot+btot)
brel=btot/(eqtot+btot)
eqtottime[ii][y-1]=eqtot/counteq
btottime[ii][y-1]=btot/countb
eqreltime[ii][y-1]=eqrel
breltime[ii][y-1]=brel
#ii=ii+1
N2=100000000
Neq2=10000000
Ndiff2=N2-Neq2
runs=100
repetitions=100
for x in [30,40,50]:
for y in range(1,21):
times,avalues,jrvalues,j2values,state=[],[],[],[],[]
file=open('/home/richard/outhome/time7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
avalues.append(float(row[1]))
jrvalues.append(float(row[2]))
j2values.append(float(row[3]))
state.append(float(row[4]))
j2valuesa=np.array(j2values)
jrvaluesa=np.array(jrvalues)
avaluesa=np.array(avalues)
statea=np.array(state)
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff2>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff2:
inteq[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff2+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff2>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff2:
intb[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff2+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff2>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff2:
intb[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff2+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff2>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff2:
inteq[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff2+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
counts=counteq+countb
countsrel=counts/Ndiff2
if counts<9999:
changespertime[ii][y-1]=countsrel/(repetitions*runs)
else:
changespertime[ii][y-1]=countsrel/(avaluesa[9999]*repetitions+jrvaluesa[9999]+j2valuesa[9999]/Ndiff2)
#plt.figure()
#plt.hist(intbt, bins=50)
#plt.yscale('log')
#plt.title("distribution of bursting time intervals")
#plt.savefig('bdistajrj2%d%d.pdf' %(x,y))
#plt.figure()
#plt.hist(inteqt, bins=50)
#plt.yscale('log')
#plt.title("distribution of equilibrium time intervals")
#plt.savefig('eqdistajrj2%d%d.pdf' %(x,y))
eqtot=np.sum(inteqt)
btot=np.sum(intbt)
eqrel=eqtot/(eqtot+btot)
brel=btot/(eqtot+btot)
eqtottime[ii][y-1]=eqtot/counteq
btottime[ii][y-1]=btot/countb
eqreltime[ii][y-1]=eqrel
breltime[ii][y-1]=brel
ii=ii+1
#N3=50000000
#Neq3=10000000
#Ndiff3=N3-Neq3
#for x in [30,40]:
# for y in range(10,11):
# times,avalues,j2values,state=[],[],[],[]
# file=open('/home/richard/outhome/time17a%d%d.txt' % (x,y),"r")
# for k in file:
# row=k.split()
# avalues.append(float(row[1]))
# j2values.append(float(row[2]))
# state.append(float(row[3]))
# j2valuesa=np.array(j2values)
# avaluesa=np.array(avalues)
# statea=np.array(state)
# countb=0
# counteq=0
# if statea[0]<0.5:
# intb=np.zeros(4999)
# inteq=np.zeros(5000)
# for z in range(0,5000):
# if avaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff3>avaluesa[2*z]+j2valuesa[2*z]/Ndiff3:
# inteq[z]=((avaluesa[2*z+1]-avaluesa[2*z])*Ndiff3+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
# counteq=counteq+1
# else:
# break
# inteqt=np.zeros(counteq)
# for c in range(0,counteq):
# inteqt[c]=inteq[c]
# for z in range(0,4999):
# if avaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff3>avaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff3:
# intb[z]=((avaluesa[2*z+2]-avaluesa[2*z+1])*Ndiff3+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
# countb=countb+1
# else:
# break
# intbt=np.zeros(countb)
# for c in range(0,countb):
# intbt[c]=intb[c]
# else:
# inteq=np.zeros(4999)
# intb=np.zeros(5000)
# for z in range(0,5000):
# if avaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff3>avaluesa[2*z]+j2valuesa[2*z]/Ndiff3:
# intb[z]=((avaluesa[2*z+1]-avaluesa[2*z])*Ndiff3+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
# countb=countb+1
# else:
# break
# intbt=np.zeros(countb)
# for c in range(0,countb):
# intbt[c]=intb[c]
# for z in range(0,4999):
# if avaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff3>avaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff3:
# inteq[z]=((avaluesa[2*z+2]-avaluesa[2*z+1])*Ndiff3+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
# counteq=counteq+1
# else:
# break
# inteqt=np.zeros(counteq)
# for c in range(0,counteq):
# inteqt[c]=inteq[c]
#
# #plt.figure()
# #plt.hist(intbt, bins=50)
# #plt.yscale('log')
# #plt.title("distribution of bursting time intervals")
# #plt.savefig('bdistaj2%d%d.pdf' %(x,y))
# #plt.figure()
# #plt.hist(inteqt, bins=50)
# #plt.yscale('log')
# #plt.title("distribution of equilibrium time intervals")
# #plt.savefig('eqdistaj2%d%d.pdf' %(x,y))
# eqtot=np.sum(inteqt)
# btot=np.sum(intbt)
# eqrel=eqtot/(eqtot+btot)
# brel=btot/(eqtot+btot)
# eqreltime[ii][0]=eqrel
# breltime[ii][0]=brel
# ii=ii+1
#
#xs=np.arange(0.25,4.25,0.25)
#for k in range(0,20):
# plt.figure()
# xs=[1/2,1/3,1/4,1/5]
# plt.xlabel('inverse noise intensity 1/D')
# plt.ylabel('transition rate')
# plt.yscale('log')
# plt.plot(xs,1/breltime[:,k],label='burst to eq')
#plt.plot(xs,breltime[1,:],label='D=3,burst')
#plt.plot(xs,breltime[2,:],label='D=4,burst')
#plt.plot(xs,eqreltime[3,:],label='D=4,burst')
# plt.plot(xs,1/eqreltime[:,k],label='eq to burst')
#plt.plot(xs,eqreltime[1,:],label='D=3,equilibrium')
#plt.plot(xs,eqreltime[2,:],label='D=4,equilibrium')
#plt.plot(xs,breltime[3,:],label='D=4,equilibrium')
# plt.legend()
# plt.savefig('arrhenius%d.pdf' %(k))
for k2 in range(5,16):
plt.figure()
xs=[1/3,1/4,1/5]
plt.xlabel('inverse noise intensity 1/D')
plt.ylabel('transition rate')
plt.yscale('log')
plt.plot(xs,1/btottime[:,k2],'bo',label='burst to eq')
#plt.plot(xs,breltime[1,:],label='D=3,burst')
#plt.plot(xs,breltime[2,:],label='D=4,burst')
#plt.plot(xs,eqreltime[3,:],label='D=4,burst')
plt.plot(xs,1/eqtottime[:,k2],'ro',label='eq to burst')
#plt.plot(xs,eqreltime[1,:],label='D=3,equilibrium')
#plt.plot(xs,eqreltime[2,:],label='D=4,equilibrium')
#plt.plot(xs,breltime[3,:],label='D=4,equilibrium')
popt,pcov = curve_fit(func, xs, 1/btottime[:,k2])
plt.plot(np.array(xs), func(np.array(xs), *popt), 'b-',label='fit burst to eq: r_0=%5.3f, U_+=%5.3f' % tuple(popt))
params[0][k2-5]=popt[0]
params[1][k2-5]=popt[1]
popt,pcov = curve_fit(func, xs, 1/eqtottime[:,k2])
plt.plot(np.array(xs), func(np.array(xs), *popt), 'r-',label='fiteq to burst: r_0=%5.3f, U_-=%5.3f' % tuple(popt))
params[2][k2-5]=popt[0]
params[3][k2-5]=popt[1]
plt.legend()
plt.savefig('arrheniustot%sfit%d.pdf' %(date,k2))
eqfile = open('param%s%d.txt' % (date,k2),'w')
for k3 in range(0,4):
eqfile.write('%.6f\n'%params[k3][k2-5])
eqfile.close()
ratefile = open('rate%s%d.txt' %(date,k2),'w')
for k4 in range(0,3):
ratefile.write('%.6f\n'%btottime[k4][k2])
for k4 in range(0,3):
ratefile.write('%.6f\n'%eqtottime[k4][k2])
ratefile.close()
plt.figure()
plt.xlabel('inverse noise intensity 1/D')
plt.ylabel('correlation time')
plt.yscale('log')
plt.plot(xs,1/(1/btottime[:,k2]+1/eqtottime[:,k2]))
plt.savefig('cortime%s%d.pdf' %(date,k2))
plt.figure()
xold=np.arange(-0.75,4.25,0.25)
plt.xlabel('bias current I')
plt.ylabel('correlation time')
plt.yscale('log')
#plt.plot(xold,1/(1/btottime[0,:]+1/eqtottime[0,:]),label='D=2')
plt.plot(xold,1/(1/btottime[0,:]+1/eqtottime[0,:]),label='D=3')
plt.plot(xold,1/(1/btottime[1,:]+1/eqtottime[1,:]),label='D=4')
plt.plot(xold,1/(1/btottime[2,:]+1/eqtottime[2,:]),label='D=5')
plt.savefig('altcortime%s.pdf' %date)
plt.figure()
xnew=np.arange(0.5,3.25,0.25)
plt.xlabel('bias current')
plt.ylabel('prefactor')
plt.plot(xnew,params[0,:],label='burst to eq')
plt.plot(xnew,params[2,:],label='eq to burst')
plt.legend()
plt.savefig('prefac%s.pdf' %date)
plt.figure()
plt.xlabel('bias current')
plt.ylabel('potential barrier')
plt.plot(xnew,params[1,:],label='burst to eq')
plt.plot(xnew,params[3,:],label='eq to burst')
plt.plot(xnew,2*params[1,:],label='2x burst to eq')
plt.plot(xnew,2*params[3,:],label='2x eq to burst')
plt.legend()
plt.savefig('barrier2%s.pdf' %date)
eqfile3 = open('barrierex%s.txt' %date,'w')
for k3 in range(0,11):
eqfile3.write('%.6f %.6f %.6f %.6f %.6f\n'%(xnew[k3],params[0][k3],params[1][k3],params[2][k3],params[3][k3]))
eqfile3.close()
popt,pcov = curve_fit(func2, xnew, params[1,:])
params2[0]=popt[0]
params2[1]=popt[1]
popt,pcov = curve_fit(func2, xnew, params[3,:])
params2[3]=popt[0]
params2[4]=popt[1]
popt,pcov = curve_fit(func3, xnew, params[0,:])
params2[2]=popt[0]
popt,pcov = curve_fit(func3, xnew, params[2,:])
params2[5]=popt[0]
eqfile2 = open('parambarrier%s.txt' %date,'w')
for k4 in range(0,6):
eqfile2.write('%.6f\n'%params2[k4])
eqfile2.close()
t=np.arange(0.5,3,0.01)
plt.figure()
plt.xlabel('bias current')
plt.ylabel('potential barrier')
plt.plot(t,func2(t,params2[0],params2[1]),'y')
plt.plot(t,func2(t,params2[3],params2[4]),'y')
plt.plot(t,2*func2(t,params2[0],params2[1]),'y')
plt.plot(t,2*func2(t,params2[3],params2[4]),'y')
plt.plot(xnew,params[1,:],label='burst to eq')
plt.plot(xnew,params[3,:],label='eq to burst')
plt.plot(xnew,2*params[1,:],label='2x burst to eq')
plt.plot(xnew,2*params[3,:],label='2x eq to burst')
plt.legend()
plt.savefig('barriercomp%s.pdf' %date)
#plt.figure()
#xs1=np.arange(-0.75,4.25,0.25)
#xs2=np.arange(0.2,4.2,0.2)
#plt.xlabel('bias current')
#plt.ylabel('changes over time steps')
#plt.yscale('log')
#plt.plot(xs2,changespertime[0,:],label='D=1.2')
#plt.plot(xs1,changespertime[1,:],label='D=2')
#plt.plot(xs2,changespertime[2,:],label='D=3')
#plt.plot(xs2,changespertime[3,:],label='D=4')
#plt.plot(xs2,changespertime[4,:],label='D=5')
#plt.legend()
#plt.savefig('changespertime.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
fil1=open('/home/richard/outhome/g1s.txt',"r")
x1,y1=[],[]
for k in fil1:
row=k.split()
x1.append(float(row[0]))
y1.append(float(row[1]))
x1s,y1s = zip(*sorted(zip(x1,y1)))
#fil2=open('/home/richard/outhome/g1.2mr.txt',"r")
#x2,y2=[],[]
#for k in fil2:
# row=k.split()
# x2.append(float(row[0]))
# y2.append(float(row[1]))
#x2s,y2s = zip(*sorted(zip(x2,y2)))
#fil3=open('/home/richard/outhome/g1.5mr.txt',"r")
#x3,y3=[],[]
#for k in fil3:
# row=k.split()
# x3.append(float(row[0]))
# y3.append(float(row[1]))
#x3s,y3s = zip(*sorted(zip(x3,y3)))
fil4=open('/home/richard/outhome/g2s.txt',"r")
x4,y4=[],[]
for k in fil4:
row=k.split()
x4.append(float(row[0]))
y4.append(float(row[1]))
x4s,y4s = zip(*sorted(zip(x4,y4)))
fil5=open('/home/richard/outhome/g3s.txt',"r")
x5,y5=[],[]
for k in fil5:
row=k.split()
x5.append(float(row[0]))
y5.append(float(row[1]))
x5s,y5s = zip(*sorted(zip(x5,y5)))
fil6=open('/home/richard/outhome/g4s.txt',"r")
x6,y6=[],[]
for k in fil6:
row=k.split()
x6.append(float(row[0]))
y6.append(float(row[1]))
x6s,y6s = zip(*sorted(zip(x6,y6)))
#fil7=open('/home/richard/outhome/g5mr.txt',"r")
#x7,y7=[],[]
#for k in fil7:
# row=k.split()
# x7.append(float(row[0]))
# y7.append(float(row[1]))
#x7s,y7s = zip(*sorted(zip(x7,y7)))
#fil8=open('/home/richard/outhome/g6mr.txt',"r")
#x8,y8=[],[]
#for k in fil8:
# row=k.split()
# x8.append(float(row[0]))
# y8.append(float(row[1]))
#x8s,y8s = zip(*sorted(zip(x8,y8)))
plt.xlabel('bias current I')
plt.ylabel('firing rate')
plt.yscale('log')
plt.plot(x1s,y1s,label='D=1')
#plt.plot(x2s,y2s,label='D=1.2')
#plt.plot(x3s,y3s,label='D=1.5')
plt.plot(x4s,y4s,label='D=2')
plt.plot(x5s,y5s,label='D=3')
plt.plot(x6s,y6s,label='D=4')
#plt.plot(x7s,y7s,label='D=5')
#plt.plot(x8s,y8s,label='D=6')
plt.legend()
plt.savefig('gneurs.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
nvalues=21
vvalues=21
points=51
file=open('/home/richard/outhome/phaseliness6.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(row[2])
y.append(row[3])
ax=np.array(x)
ay=np.array(y)
xv=np.zeros((vvalues,nvalues,points))
yv=np.zeros((vvalues,nvalues,points))
for vi in range(0,vvalues):
for ni in range(0,nvalues):
for pi in range(0,points):
xv[vi][ni][pi]=ax[(ni*vvalues+vi)*points+pi]
yv[vi][ni][pi]=ay[(ni*vvalues+vi)*points+pi]
plt.figure()
plt.xlabel('membrane voltage V')
plt.ylabel('gating variable n')
for vi in range(0,vvalues):
for ni in range(0,nvalues):
plt.plot(yv[vi][ni][:],xv[vi][ni][:])
#plt.arrow(yv[vi][ni][points-2],xv[vi][ni][points-2],yv[vi][ni][points-1]-yv[vi][ni][points-2],xv[vi][ni][points-1]-xv[vi][ni][points-2],head_width=10*0.003,head_length=15*0.003)
plt.savefig('phaseliness6.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on June 27, 2019, 9:20 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <iostream>
#include <valarray>
using namespace std;
double ninf(double V, double k, double Vh);
void init(double x[],int n);
int main(int argc, char** argv) {
//ofstream myfile;
ofstream myfile2;
ofstream myfile3;
ofstream myfile4;
ofstream myfile5;
// myfile.open ("countInew.txt");
myfile2.open("voltageplusstate.txt");
myfile3.open("param.txt");
myfile4.open ("time.txt");
myfile5.open ("timenew.txt");
std::random_device rd;
std::mt19937_64 gen(rd());
std::normal_distribution<> n(0,1);
double I=0; // 0
double gL=0.3; // 8
double EL=-80; // -80
double gNa=1; // 20
double ENa=60; // 60
double gK=0.4; // 9
double EK=-90; // -90
//Na current
double km=14; // 15
double vm=-18; // -20
//fast K+ current
double kn=5; // 5
double vn=-25; // -20
double tau=3; // 0.152
int N0;
N0=5000000;
int runs=50;
int points=100000;
int sampling=N0*runs/points;
double th=-25;
double thn=0.7;
double D=1;
int j,f;
double dt;
dt=0.0001;
int timepoints=100000;
int Nsim=5000000;
double vsim,nfsim,nfsims,vsims,neq,veq;
nfsims=0.4;
vsims=-70;
for(int jsim=0;jsim<Nsim;jsim++){
vsim=I*dt+vsims-gL*(vsims-EL)*dt-gNa*ninf(vsims,km,vm)*(vsims-ENa)*dt-gK*nfsims*(vsims-EK)*dt;
nfsim=nfsims+(ninf(vsims,kn,vn)-nfsims)*dt/tau;
vsims=vsim;
nfsims=nfsim;
}
veq=vsims;
neq=nfsims;
long long int count;
std::valarray<double> state(0.0,timepoints),state2(0.0,timepoints),times(0.0,timepoints),times2(0.0,timepoints);
double Nav,Nava,Nava2,N2ava,T,vout[points],nout[points],bvout[points],bv2out[points],cout[points];
double mx,nx,nx2,v,nf,nfs,vs,Deff,vav,vavalt,sigmav,Fano,lastcount;
std::valarray<int> avalue(timepoints),avalue2(timepoints),j2value(timepoints),j2value2(timepoints),jrvalue(timepoints),jrvalue2(timepoints);
avalue[0]=0;
j2value[0]=0;
jrvalue[0]=0;
avalue2[0]=0;
j2value2[0]=0;
jrvalue2[0]=0;
count=0;
int bv,bv2,lastbv,lastbv2,sv,svlocked,t,t2,tv,j22,p;
times[0]=0;times2[0]=0;lastcount=0;Nava=0;Nava2=0;sv=0;t=0;t2=0;tv=0;svlocked=0;
mx=0.0309-0.0047*I;
nx=1.654+0.01*I;
nx2=mx*63;
p=0;
vs=-30;
nfs=0.2;
if(nfs>mx*vs+nx2){
bv=0;
bv2=0;
}
else{
bv=1;
bv2=1;
}
lastbv=bv;
lastbv2=bv2;
for(int a=0;a<runs;a++){
for(j=0;j<N0;j++){
j22=a*N0+j;
v=I*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt+sqrt(2*D*dt)*n(gen);
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
if(v > th && vs < th){
sv=1;
}
if(sv==1 && nf > thn && nfs < thn){
count=count+1;
sv=0;
bv2=1;
svlocked=0;
lastcount=j22;
}
if(bv2==1 && v<veq+5 && nf<neq+0.1){
if(svlocked==0){
if(v < veq && vs > veq){
svlocked=1;
}}
if(svlocked==0){
if(nf < neq && nfs > neq){
svlocked=-1;
}
}
if(svlocked==1){
if(nf < neq && nfs > neq){
bv2=0;
svlocked=2;
}
}
if(svlocked==-1){
if(v < veq && vs > veq){
bv2=0;
svlocked=2;
}
}
}
if((bv==1 && nf>mx*v+nx2) || (bv==1 && (j22-lastcount)>20/dt)){
bv=0;
}
if(bv==0 && nf<mx*v+nx){
bv=1;
}
if(j22==4000*tv){
if((t<timepoints) && (0.5<bv+lastbv) && (1.5>bv+lastbv)){
times[t]=j22*dt;
state[t]=bv;
avalue[t]=a;
jrvalue[t]=j;
t=t+1;
}
tv=tv+1;
lastbv=bv;
}
if((t2<timepoints) && (0.5<bv2+lastbv2) && (1.5>bv2+lastbv2)){
times2[t2]=j22*dt;
state2[t2]=bv2;
avalue2[t2]=a;
jrvalue2[t2]=j;
t2=t2+1;
lastbv2=bv2;
}
if(j22==p*sampling){vout[p]=v;
nout[p]=nf;
bvout[p]=bv;
bv2out[p]=bv2;
cout[p]=count;
p=p+1;
}
vs=v;
nfs=nf;
}
}
/*for(f=0;f<runs;f++){
myfile << dt0*f << " " << count[f] << "\n";
}
myfile.close(); */
for(int rv=0;rv<timepoints;rv++){
myfile4 << times[rv] <<" " << avalue[rv] << " " << jrvalue[rv] <<" " <<state[rv] <<"\n";
}
myfile4.close();
for(int rv=0;rv<timepoints;rv++){
myfile5 << times2[rv] <<" " << avalue2[rv] << " " << jrvalue2[rv] <<" " <<state2[rv] << "\n";
}
myfile5.close();
for(f=0;f<points;f++){
myfile2 << f*sampling*dt << " " << vout[f] << " "<< nout[f] << " "<< bvout[f]<<" " << cout[f] << "\n";
}
myfile2.close();
myfile3 << veq << " "<< neq << "\n";
myfile3.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
void init(double x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
epsilon=0.01
omega=0.01
tau=3
runs=2000
points=100000
length=50000
N=10000000
dt=0.001
T=N*dt
T2=T*10
S=np.zeros(length)
amp=epsilon**2*T/(4*(1+((omega/2)*tau)**2))
def spectrum(f,tau,sigma):
return (2*tau*sigma**2)/(1+(2*np.pi*f*tau)**2)
file=open('/home/richard/mastergit/NetBeansProjects/oup/xtraje18f.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
ax2=np.zeros(length)
ay2=np.zeros(length)
for l in range(0,length):
ax2[l]=ax[l]
ay2[l]=ay[l]
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('frequency')
plt.ylabel('power spectrum')
plt.yscale('log')
plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
#plt.xlim(4*10**(-4),100)
plt.plot(ax2,ay2/T,label='sim')
plt.plot(ax2,spectrum(ax2,3,5),label='theory')
plt.plot(omega/2,amp+spectrum(omega/(4*np.pi),3,5),'x',label="delta")
#plt.plot(sax2,say2/T2,label='e6')
plt.legend()
plt.savefig('oup18ftheo3.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on January 8, 2019, 12:48 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <iostream>
using namespace std;
double ninf(double V, double k, double Vh);
double init(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
myfile.open ("phasenraumstab.txt");
double I=0; // 0
double gL=8; // 8
double EL=-80; // -80
double gNa=20; // 20
double ENa=60; // 60
double gK=9; // 9
double EK=-90; // -90
double gM=5; // 5
//slow K+ current
double kinf=5; // 5
double vinf=-20; // -20
double tauM=30; // 20
//Na current
double km=15; // 15
double vm=-20; // -20
//fast K+ current
double kn=5; // 5
double vn=-25; // -20
double tau=0.152; // 0.152
int N=1000000;
int nvalues=11;
int vvalues=11;
int runs=nvalues*vvalues;
double count[runs],vendvalue[runs],nendvalue[runs];
double v,vs,nf,nfs;
double th=-25;
double vstart=-80;
double vend=0;
double dv=(vend-vstart)/(vvalues-1);
double nstart=0.1;
double nend=0.9;
double dn=(nend-nstart)/(nvalues-1);
nfs=0;
int j,f,f2;
double dt=0.00001;
init(count,runs);
for(int b=0;b<vvalues;b++){
for(int a=0;a<nvalues;a++){
vs=vstart+b*dv;
nfs=nstart+a*dn;
for(j=0;j<N;j++){
v=I*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt;
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
if(v > th && vs < th){
count[b*nvalues+a]=count[b*nvalues+a]+1;
}
vs=v;
nfs=nf;
}
vendvalue[b*nvalues+a]=v;
nendvalue[b*nvalues+a]=nf;
}
}
for(f=0;f<nvalues;f++){
for(f2=0;f2<vvalues;f2++){
myfile << vstart+f2*dv << " " << nstart+f*dn << " " << count[f2*nvalues+f] << " "
<< nendvalue[f2*nvalues+f] << " " << vendvalue[f2*nvalues+f] << "\n";
}
}
myfile.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double init(double x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
from scipy.optimize import curve_fit
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def snr(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,av,v0):
return (qr(r0m,am,bm,cm,t,D)*(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))/(v0**2*qr(r0p,ap,bp,cp,t,D)))*((((2*ap*t+bp)-(2*am*t+bm))*qr(r0p,ap,bp,cp,t,D)*v0)/(D*(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D)))+av)**2
def qbarrier(x,a,b,c):
return a*x**2+b*x+c
def qr(r0,a,b,c,t,D):
return r0*np.exp(-qbarrier(t,a,b,c)/D)
def deff(x,rp,rm,v0,av):
return ((v0+av*x)**2*rp*rm)/((rp+rm)**3)
def fano(x,rp,rm,v0,av):
return (2*(v0+av*x)*rp)/((rp+rm)**2)
def func(x, a, b):
return a * np.exp(-b * x)
def deffana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return ((barrier(av,v0,t))**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
def deffqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,v0):
return (v0**2*qr(r0p,ap,bp,cp,t,D)*qr(r0m,am,bm,cm,t,D))/((qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))**3)
def fanoana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return (2*barrier(av,v0,t)*r(r0p,ap,bp,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**2)
def fanoqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,v0):
return 2*deffqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,v0)/vqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,v0)
def vana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return barrier(av,v0,t)*r(r0m,am,bm,t,D)/(r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))
def vqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,v0):
return v0*qr(r0m,am,bm,cm,t,D)/(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))
def comp(x,b,c,d,e):
return b*x**3+c*x**2+d*x+e
def comps(x,b,c,d):
return 3*b*x**2+2*c*x+d
date3='realrinzel25o'
date2='realrinzel15ninv0'
ivalues=10
l=3
D1=[]
D3=[200,300,500]
D2=[]
Dvar=[]
D=D1+D2+D3+Dvar
Da=np.array(D)
btoeq=np.zeros((l,ivalues))
eqtob=np.zeros((l,ivalues))
params=np.zeros((4,ivalues))
paramsav=np.zeros((4,ivalues))
params2=np.zeros(4)
paramsq=np.zeros(6)
paramsqrate=np.zeros(6)
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/rate%s%d.txt' %(date3+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,l):
btoeq[k][k2]=1/ax[k]
eqtob[k][k2]=1/ax[k+l]
av=0.1/12
v0=0.47
xs=np.zeros(l)
for b in range(0,l):
xs[b]=10/Da[b]
for k2 in range(0,ivalues):
popt,pcov = curve_fit(func, xs, btoeq[:,k2])
params[0][k2]=popt[0]
params[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2])
params[2][k2]=popt[0]
params[3][k2]=popt[1]
rbte=np.mean(params[0,:])
retb=np.mean(params[2,:])
istart=1
xnew=np.arange(-22.5+istart,-22.5+istart+ivalues)*0.8
#barrier fit
popt,pcov = curve_fit(qbarrier, xnew, params[1,:])
paramsq[0]=popt[0]
paramsq[1]=popt[1]
paramsq[2]=popt[2]
popt,pcov = curve_fit(qbarrier, xnew, params[3,:])
paramsq[3]=popt[0]
paramsq[4]=popt[1]
paramsq[5]=popt[2]
#prefactor fit
popt,pcov = curve_fit(qbarrier, xnew, params[0,:])
paramsqrate[0]=popt[0]
paramsqrate[1]=popt[1]
paramsqrate[2]=popt[2]
popt,pcov = curve_fit(qbarrier, xnew, params[2,:])
paramsqrate[3]=popt[0]
paramsqrate[4]=popt[1]
paramsqrate[5]=popt[2]
#ivalues=5
ii=0
date='realrinzel25o'#'realrinzelpoi17dlong1'
date1='realrinzelpoi17d1'
D=[200,300,500]
D1=[]
Dtot=D+D1
l=len(D)+len(D1)
vec=np.zeros((l,ivalues))
vecx=np.zeros((l,ivalues))
offset=np.zeros(l,dtype=int)
for x in D:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
offset[ii]=ivalues-len(cola)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
offset[ii]=ivalues-len(cola)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
dvalues=6
dparams=4
b=np.zeros(dvalues)
c=np.zeros(dvalues)
d=np.zeros(dvalues)
e=np.zeros(dvalues)
ii=0
#xnew=np.arange(-0.19,0.31,0.01)
eqfile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/detmocountparam5.txt','r')
for k in eqfile:
col=[]
row=k.split()
for l in range(0,dparams):
col.append(float(row[l]))
cola=np.array(col)
b[ii]=cola[0]
c[ii]=cola[1]
d[ii]=cola[2]
e[ii]=cola[3]
ii=ii+1
eqfile.close()
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('bias current')
plt.ylabel('firing rate')
t=np.arange(-18,-9,0.1)
xs=np.arange(-22.5+istart,-22.5+istart+ivalues)*0.8
#plt.yscale('log')
#plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
#plt.xlim(4*10**(-4),100)
colorv=['y','g','b','r','c']
for n in range(0,l):
plt.plot(vecx[n,0:(ivalues-offset[n])],vec[n,0:(ivalues-offset[n])],colorv[n]+'o',label='D=%.2f' %(Dtot[n]*0.1))
for n in range(0,l):
bv=b[2*n+1]
cv=c[2*n+1]
dv=d[2*n+1]
ev=e[2*n+1] #plt.plot(t,snr(rbte,retb,paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[n]*0.1,comps(t,b[n+1],c[n+1],d[n+1]),comp(t,b[n+1],c[n+1],d[n+1],e[n+1]))/8,colorv[n])
plt.plot(t,vqana(qbarrier(t,paramsqrate[0],paramsqrate[1],paramsqrate[2]),qbarrier(t,paramsqrate[3],paramsqrate[4],paramsqrate[5]),paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[n]*0.1,comp(t,bv,cv,dv,ev)),colorv[n])
#plt.plot([0.163, 0.163], [10**(-7), 10], color='black', linestyle='-')
#plt.plot([-0.02, -0.02], [10**(-7), 10], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot(xs,SNR[2,:],label='D=3')
#plt.plot(xs,SNR[1,:],label='D=2.5')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [0,2,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
#plt.plot(sax2,say2/T2,label='e6')
plt.legend()
plt.savefig('gcomprate25onologwlp.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
#datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
#Dvar=np.array([30])
#lvar=len(Dvar)
#yvar=[4,13,3]
#yvalues=len(yvar)
timefac=1000
date='realanhopf3mlogcorner2'
date1='realanhopf3mlogcorner'
date2='realanhopf21flogcorner'
date3='realanhopf3mlogcorner'
datevar=['realanhopf17mlogcorner2','realanhopf11mlogcorner2']
datevar2=['realanhopf17mlogcorner','realanhopf11mlogcorner']
D=[]
D1=[10]
D2=[10]
D3=[]
Dvar=[10]
Dvar2=[10]
Dtot=D+D1+D2+D3+Dvar+Dvar2
l=len(Dtot)
istart=1
ivalues=10
vecx=np.zeros((l,ivalues))
vec=np.zeros((l,ivalues))
ii=0
offset=np.zeros(l,dtype=int)
#istart0=1
#ivalues0=3
yvar=[4,6]
yvalues=len(yvar)
ystart=1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/d%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
if len(colvar)+offset[ii]<y+kk*yvar[kk]-istart+1:
offset[ii]=offset[ii]+1
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=colavar[z]
vecx[ii][z]=colxavar[z]
ii=ii+1
for x in D:
col,colx=[],[]
for y in range(istart0,istart0+ivalues0):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart0+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues0-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
yvar2=[4,6]
yvalues2=len(yvar2)
ystart2=1
for x in Dvar2:
colvar2,colxvar2=[],[]
for kk in range(0,yvalues2):
for y in range(ystart2,ystart2+yvar2[kk]):
file=open('/home/richard/outhome/d%s%d%d.txt' % (datevar2[kk],x,y),"r")
for k in file:
row=k.split()
colxvar2.append(float(row[0]))
colvar2.append(float(row[1]))
if len(colvar2)+offset[ii]<y+kk*yvar2[kk]-istart+1:
offset[ii]=offset[ii]+1
colxavar2=np.array(colxvar2)
colavar2=np.array(colvar2)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=colavar2[z]
vecx[ii][z]=colxavar2[z]
ii=ii+1
for x in D2:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D3:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
#xs=np.arange(-0.08,0.32,0.02)
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ $[s^{-1}]$')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,1):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='$T=0.1\cdot T_{long}$')
for n in range(1,2):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='$T=0.2\cdot T_{long}$')
for n in range(2,3):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='$T=0.5\cdot T_{long}$')
for n in range(3,4):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='$T=T_{long}$')
#for n in range(0,1):
# plt.plot(vecx[n,0:3],vec[n,0:3]*timefac,label='D=%.2f' %(Dtot[n]/100))#kurz
#plt.xlim(46,47)
#for n in range(1,2):
# nl=round(ivalues-offset[n])
# plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='D=%.2f,mittel' %(Dtot[n]/100))
#for n in range(2,3):
# nl=round(ivalues-offset[n])
# plt.plot(vecx[n,0:nl],vec[n,0:nl]*timefac,label='D=%.2f,lang' %(Dtot[n]/100))
#plt.plot([46.1, 46.1], [10**(-2), 10**2], color='black', linestyle='-',label='$I_{crit}$')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend()
plt.savefig('dneurall%s.pdf' %(date+date1))
vec=np.zeros((l,ivalues))
vecx=np.zeros((l,ivalues))
ii=0
#for x in Dvar:
# colvar,colxvar=[],[]
# for kk in range(0,yvalues):
# ystart=1
# jj=0
# while jj < kk:
# ystart=ystart+yvar[jj]
# jj=jj+1
# for y in range(ystart,ystart+yvar[kk]):
# file=open('/home/richard/outhome/f%s%d%d.txt' % (datevar[kk],x,y),"r")
# for k in file:
# row=k.split()
# colxvar.append(float(row[0]))
# colvar.append(float(row[1]))
# colxavar=np.array(colxvar)
# colavar=np.array(colvar)
# for z in range(0,20):
# vec[ii][z]=colavar[z]
# ii=ii+1
offset2=np.zeros(l,dtype=int)
for x in D:
col,colx=[],[]
for y in range(istart0,istart0+ivalues0):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset2[ii]<y-istart0+1:
offset2[ii]=offset2[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues0-offset2[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset2[ii]<y-istart+1:
offset2[ii]=offset2[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset2[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D2:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset2[ii]<y-istart+1:
offset2[ii]=offset2[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset2[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D3:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset2[ii]<y-istart+1:
offset2[ii]=offset2[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset2[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
plt.figure()
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Fano factor')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,l):
nl=round(ivalues-offset2[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl],label='D=%.2f' %(Dtot[n]/100))
#plt.plot([46.1, 46.1], [10**(-4), 1], color='black', linestyle='-',label='$I_{crit}$')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend()
plt.savefig('fneur%s.pdf' %(date+date1))
vec=np.zeros((l,ivalues))
vecx=np.zeros((l,ivalues))
ii=0
offset3=np.zeros(l,dtype=int)
for x in D:
col,colx=[],[]
for y in range(istart0,istart0+ivalues0):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset3[ii]<y-istart0+1:
offset3[ii]=offset3[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues0-offset3[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset3[ii]<y-istart+1:
offset3[ii]=offset3[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset3[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D2:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset3[ii]<y-istart+1:
offset3[ii]=offset3[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset3[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D3:
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset3[ii]<y-istart+1:
offset3[ii]=offset3[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,ivalues-offset3[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
N=50000000
dt=0.005
T=N*dt
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countanhopf.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
plt.figure()
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I')
plt.ylabel('firing rate')
#plt.yscale('log')
#plt.xscale('log')
plt.xlim(vecx[0,0],vecx[0,-1])
plt.plot(colxa,cola/T,label='running firing rate',color='black')
for n in range(0,l):
nl=round(ivalues-offset3[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl],label='D=%.2f' %(Dtot[n]/100))
#plt.plot(colxa,vec[0,:],label='D=%.2f' %(D[0]/100))
#plt.plot(xs,vec[3,:],label='D=1.5')
#plt.plot(xs,vec[0,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(colxa,cola,label='D=3e-3')
plt.legend()
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [3,1,2,0]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('gneur%s.pdf' %(date+date1))
<file_sep>#
# Generated - do not edit!
#
# NOCDDL
#
CND_BASEDIR=`pwd`
CND_BUILDDIR=build
CND_DISTDIR=dist
# Debug configuration
CND_PLATFORM_Debug=GNU-Linux
CND_ARTIFACT_DIR_Debug=dist/Debug/GNU-Linux
CND_ARTIFACT_NAME_Debug=realstatevar
CND_ARTIFACT_PATH_Debug=dist/Debug/GNU-Linux/realstatevar
CND_PACKAGE_DIR_Debug=dist/Debug/GNU-Linux/package
CND_PACKAGE_NAME_Debug=realstatevar.tar
CND_PACKAGE_PATH_Debug=dist/Debug/GNU-Linux/package/realstatevar.tar
# Release configuration
CND_PLATFORM_Release=GNU-Linux
CND_ARTIFACT_DIR_Release=dist/Release/GNU-Linux
CND_ARTIFACT_NAME_Release=realstatevar
CND_ARTIFACT_PATH_Release=dist/Release/GNU-Linux/realstatevar
CND_PACKAGE_DIR_Release=dist/Release/GNU-Linux/package
CND_PACKAGE_NAME_Release=realstatevar.tar
CND_PACKAGE_PATH_Release=dist/Release/GNU-Linux/package/realstatevar.tar
#
# include compiler specific variables
#
# dmake command
ROOT:sh = test -f nbproject/private/Makefile-variables.mk || \
(mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk)
#
# gmake command
.PHONY: $(shell test -f nbproject/private/Makefile-variables.mk || (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk))
#
include nbproject/private/Makefile-variables.mk
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def fit(x,x0,sigma):
return np.exp(-(x-x0)**2/(2*sigma**2))/((2*sigma**2)**(0.5))
x=np.arange(-0.2,0.3,0.01)
plt.plot(x,fit(x,0.08,0.09))
plt.yscale('log')
plt.savefig('fit.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def deff(rp,rm,v):
return (v**2*rp*rm)/((rp+rm)**3)
def func(x, a, b):
return a * np.exp(-b * x)
def deffana(r0p,r0m,ap,am,bp,bm,t,D,v):
return (v**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
def fanoana(r0p,r0m,ap,am,bp,bm,t,D,v):
return (2*v*r(r0p,ap,bp,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**2)
def vfunc(x):
return 1.204+174/(9.8*500)*x
first=5
total=11
deffs=3
epsilon = 0.00001
btoeq=np.zeros((deffs,total))
eqtob=np.zeros((deffs,total))
params=np.zeros((4,total))
paramsav=np.zeros((4,total))
params2=np.zeros(4)
for k2 in range(first,first+total):
x=[]
ratefile = open('rate29m%d.txt' %k2,'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,deffs):
btoeq[k][k2-first]=1/ax[k]
eqtob[k][k2-first]=1/ax[k+deffs]
v=1.35
xs=[1/3,1/4,1/5]
for k2 in range(first,first+total):
popt,pcov = curve_fit(func, xs, btoeq[:,k2-first])
params[0][k2-first]=popt[0]
params[1][k2-first]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2-first])
params[2][k2-first]=popt[0]
params[3][k2-first]=popt[1]
rbte=np.mean(params[0,:])
retb=np.mean(params[2,:])
for k2 in range(first,first+total):
popt,pcov = curve_fit(func, xs, btoeq[:,k2-first],bounds=((rbte-epsilon,-np.inf), (rbte+epsilon,np.inf)))
paramsav[0][k2-first]=popt[0]
paramsav[1][k2-first]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2-first],bounds=((retb-epsilon,-np.inf), (retb+epsilon,np.inf)))
paramsav[2][k2-first]=popt[0]
paramsav[3][k2-first]=popt[1]
xnew=np.arange(0.5,3.25,0.25)
popt,pcov = curve_fit(barrier, xnew, paramsav[1,:])
params2[0]=popt[0]
params2[1]=popt[1]
popt,pcov = curve_fit(barrier, xnew, paramsav[3,:])
params2[2]=popt[0]
params2[3]=popt[1]
eqfile2 = open('paramsdf16m.txt','w')
for k4 in range(0,2):
eqfile2.write('%.6f\n'%params2[k4])
eqfile2.write('%.6f\n'%rbte)
for k4 in range(2,4):
eqfile2.write('%.6f\n'%params2[k4])
eqfile2.write('%.6f\n'%retb)
eqfile2.close()
veco=np.zeros((1,16))
vec=np.zeros((4,20))
ii=0
for x in [25]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/d29m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
for x in [30,40,50]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/d7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
#for x in [40]:
# col=[]
# for y in range(5,21):
# file=open('/home/richard/outhome/g17a%d%d.txt' % (x,y),"r")
# for k in file:
# row=k.split()
# col.append(row[1])
# cola=np.array(col)
# for z in range(0,16):
# vec[ii][z]=cola[z]
# ii=ii+1
xfit=np.arange(0.5,3.25,0.25)
xso=np.arange(0.25,4.25,0.25)
xs=np.arange(-0.75,4.25,0.25)
xsh=np.arange(1,4.2,0.2)
plt.xlabel('bias current I')
plt.ylabel('$D_{eff}$')
plt.xlim(0,3.5)
plt.ylim(5*10**(-2),2*10**3)
plt.yscale('log')
ap=ax[0]
am=ax[3]
bp=ax[1]
bm=ax[4]
r0p=rbte
r0m=retb
t=np.arange(0,4,0.01)
plt.plot(t,deffana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,2.5,vfunc(2.5)),'y')
plt.plot(t,deffana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,3,vfunc(3)),'g')
plt.plot(t,deffana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,4,vfunc(4)),'b')
plt.plot(t,deffana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,5,vfunc(5)),'r')
#plt.plot(xsh,veco[0,:],label='D=1.2')
plt.plot(xs,vec[0,:],'yo',label='D=2.5')
plt.plot(xs,vec[1,:],'go',label='D=3')
plt.plot(xs,vec[2,:],'bo',label='D=4')
plt.plot(xs,vec[3,:],'ro',label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('dcompdf29mvarv.pdf')
fano=np.zeros((4,20))
ii=0
for x in [25]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/f29m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
fano[ii][z]=cola[z]
ii=ii+1
for x in [30,40,50]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/f7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
fano[ii][z]=cola[z]
ii=ii+1
plt.figure()
plt.xlabel('bias current I')
plt.ylabel('Fano factor')
plt.yscale('log')
t=np.arange(-1,4,0.01)
plt.plot(t,fanoana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,2.5,vfunc(2.5)),'y')
plt.plot(t,fanoana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,3,vfunc(3)),'g')
plt.plot(t,fanoana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,4,vfunc(4)),'b')
plt.plot(t,fanoana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,5,vfunc(5)),'r')
#plt.plot(xsh,veco[0,:],label='D=1.2')
plt.plot(xs,fano[0,:],'yo',label='D=2.5')
plt.plot(xs,fano[1,:],'go',label='D=3')
plt.plot(xs,fano[2,:],'bo',label='D=4')
plt.plot(xs,fano[3,:],'ro',label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('fcompdf29mvarv.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
t1=-18.91
a1=
vnc=((-1-(t+70))*(1+np.exp((-40-t)/15))**3)/(10*(t-60))
nnc=1/(1+np.exp((42+t)/12))
plt.figure()
plt.xlabel('membrane voltage V')
plt.ylabel('gating variable n')
plt.plot(t,vnc,label='v-nullcline')
plt.plot(t,nnc,label='n-nullcline')
plt.legend()
plt.savefig('inatnc1.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
vecx=np.zeros((5,30))
vecy=np.zeros((5,30))
ii=0
colx,coly=[],[]
for y in range(1,31):
file=open('/home/richard/outhome/dex%dkt0.txt' % (y),"r")
for k in file:
row=k.split()
colx.append(row[0])
coly.append(row[1])
colxa=np.array(colx)
colya=np.array(coly)
for z in range(0,30):
vecx[ii][z]=colxa[z]
vecy[ii][z]=colya[z]
ii=ii+1
for x in range(1,5):
colx,coly=[],[]
for y in range(1,31):
file=open('/home/richard/outhome/mechdex%dkt%d.txt' % (y,x),"r")
for k in file:
row=k.split()
colx.append(row[0])
coly.append(row[1])
colxa=np.array(colx)
colya=np.array(coly)
for z in range(0,30):
vecx[ii][z]=colxa[z]
vecy[ii][z]=colya[z]
ii=ii+1
plt.xlabel('bias force F')
plt.ylabel('$D_{eff}$')
plt.yscale('log')
plt.ylim(1,3*10**4)
plt.plot(vecx[0,:],vecy[0,:],label='kT=0.033')
plt.plot(vecx[1,:],vecy[1,:],label='kT=0.043')
plt.plot(vecx[2,:],vecy[2,:],label='kT=0.056')
plt.plot(vecx[3,:],vecy[3,:],label='kT=0.072')
plt.plot(vecx[4,:],vecy[4,:],label='kT=0.094')
plt.legend()
plt.savefig('dmechexaktnew.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
vec=np.zeros((2,20))
ii=0
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/d20%d.txt' % (y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/d20a20%d.txt' % (y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
xs=np.arange(-0.75,4.25,0.25)
plt.xlabel('bias current I')
plt.ylabel('firing rate')
plt.yscale('log')
plt.plot(xs,vec[0,:],label='D=2,old')
plt.plot(xs,vec[1,:],label='D=2,new')
plt.legend()
plt.savefig('d2neurpcomp.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
file=open('/home/richard/NetBeansProjects/inatbursting/detinatopt2i0d0.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
plt.figure()
plt.xlabel('time')
plt.ylabel('membrane voltage')
plt.plot(ax,ay)
plt.savefig('detinatopt2i0d0.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
#matplotlib.rcParams.update({'font.size': 22})
timefac=1000 #convert ms to s
date=['realfast16alcoarsewstf','realfast9acoarsetf','realfast23mtf','realfast19mtf']
D=[25,30,35,45]
l=len(D)
istart=1
ivalues=20
vec=np.zeros((l,20))
vecx=np.zeros((l,ivalues))
ii=0
offset=np.zeros(l,dtype=int)
for m in range(0,l):
x=D[m]
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date[m],x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola[z]*timefac
vecx[ii][z]=colxa[z]
ii=ii+1
plt.figure()
colorv=['g','y','b','r']
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ $[s^{-1}]$')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,l):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl],label='D=%.2f' %(D[n]/100))
#plt.plot([0.16, 0.16], [5*10**(-1), 50000], color='black', linestyle='-',label='$I_{crit}$')
plt.plot([0.06, 0.06], [5*10**(-1), 50000], color='black', linestyle='-')
plt.legend()
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [1,0,2,3]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('dneur25nocritspmax%s.pdf' %(date[0]+date[1]))
vec=np.zeros((l,20))
vecx=np.zeros((l,ivalues))
ii=0
offset=np.zeros(l,dtype=int)
for m in range(0,l):
x=D[m]
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date[m],x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
plt.figure()
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Fano factor F')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,l):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl],label='D=%.2f' %(D[n]/100))
#plt.plot([0.16, 0.16], [10**(-2), 30000], color='black', linestyle='-',label='$I_{crit}$')
plt.plot([0.06, 0.06], [10**(-2), 30000], color='black', linestyle='-')
plt.legend()
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [1,0,2,3]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('fneur25nocritspmax%s.pdf' %(date[0]+date[1]))
vec=np.zeros((l,20))
vecx=np.zeros((l,ivalues))
ii=0
offset=np.zeros(l,dtype=int)
for m in range(0,l):
x=D[m]
col,colx=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date[m],x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola[z]*timefac
vecx[ii][z]=colxa[z]
ii=ii+1
N=50000000
dt=0.0005
T=N*dt
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countI9a.txt',"r")
col=[]
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)*timefac
xburst=np.arange(-0.20,0.31,0.01)
plt.figure()
#colorv=['y','g','b','r','c']
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('average firing rate <v>$[s^{-1}]$')
#plt.yscale('log')
#plt.xscale('log')
plt.plot(xburst[12:51],cola[12:51]/T,label='spiking firing rate $v_0$',color='black')
for n in range(0,l):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl])#,label='D=%.2f' %(D[n]/100))
#plt.plot([0.165, 0.165], [5*10**(-1), 50000], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot([-0.022, -0.022], [5*10**(-1), 50000], color='black', linestyle='-')
#plt.xlim(-0.08,0.3)
plt.legend()
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [1,0,2,3]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('gneur26critsp%s.pdf' %(date[0]+date[1]))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b):
return a * np.exp(-b * x)
def func2(x, a, b):
return a * x + b
def func3(x, a):
return a
D1=[200,300,500]
D2=[]
D3=[]
Dvar=[]
D=D1+D2+D3+Dvar
l1=len(D1)
l2=len(D2)
l3=len(D3)
lvar=len(Dvar)
l=l1+l2+l3+lvar
date1='realrinzel25o'
date2='new'+'realfast19jjem2st'
date3='new'+'realfast11jjem2st'
datevar=['new'+'realfast11jjem2','new'+'realfast11jjem2sh','new'+'realfast11jjem2']
istart=11
ivalues=1
params2=np.zeros(6)
params=np.zeros((4,ivalues))
changespertime=np.zeros((l,ivalues))
eqtottime=np.zeros((l,ivalues))
eqreltime=np.zeros((l,ivalues))
btottime=np.zeros((l,ivalues))
breltime=np.zeros((l,ivalues))
ii=0
for x in D1:
for y in range(istart,istart+ivalues):
avalues,jrvalues,j2values,state=[],[],[],[]
file=open('/home/richard/outhome/timenew%s%d%d.25.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
avalues.append(float(row[0]))
jrvalues.append(float(row[1]))
j2values.append(float(row[2]))
state.append(float(row[3]))
j2valuesa=np.array(j2values)
jrvaluesa=np.array(jrvalues)
avaluesa=np.array(avalues)
statea=np.array(state)
param=open('/home/richard/outhome/param%s%d%d.25.txt' %(date1,x,y),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
Ndiff=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
runs=value[name.index('runs')]
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
inteq[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
intb[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
intb[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
inteq[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
counts=counteq+countb
countsrel=counts/Ndiff
changespertime[ii][y-istart]=countsrel/(repetitions*runs)
plt.figure()
plt.xlabel('interval length [ms]')
plt.ylabel('number of intervals')
plt.hist(intbt, bins=50)
plt.yscale('log')
plt.title("distribution of bursting time intervals")
plt.savefig('bdistajrj2%s%d%d.pdf' %(date1,x,y))
plt.figure()
plt.xlabel('interval length [ms]')
plt.ylabel('number of intervals')
plt.hist(inteqt, bins=50)
plt.yscale('log')
plt.title("distribution of equilibrium time intervals")
plt.savefig('eqdistajrj2%s%d%d.pdf' %(date1,x,y))
eqtot=np.sum(inteqt)
btot=np.sum(intbt)
eqrel=eqtot/(eqtot+btot)
brel=btot/(eqtot+btot)
eqtottime[ii][y-istart]=eqtot/counteq
btottime[ii][y-istart]=btot/countb
eqreltime[ii][y-istart]=eqrel
breltime[ii][y-istart]=brel
ii=ii+1
#xs=np.arange(0.25,4.25,0.25)
#for k in range(0,20):
# plt.figure()
# xs=[1/2,1/3,1/4,1/5]
# plt.xlabel('inverse noise intensity 1/D')
# plt.ylabel('transition rate')
# plt.yscale('log')
# plt.plot(xs,1/breltime[:,k],label='burst to eq')
#plt.plot(xs,breltime[1,:],label='D=3,burst')
#plt.plot(xs,breltime[2,:],label='D=4,burst')
#plt.plot(xs,eqreltime[3,:],label='D=4,burst')
# plt.plot(xs,1/eqreltime[:,k],label='eq to burst')
#plt.plot(xs,eqreltime[1,:],label='D=3,equilibrium')
#plt.plot(xs,eqreltime[2,:],label='D=4,equilibrium')
#plt.plot(xs,breltime[3,:],label='D=4,equilibrium')
# plt.legend()
# plt.savefig('arrhenius%d.pdf' %(k))
if l > 1:
for k2 in range(0,ivalues):
plt.figure()
xs=np.zeros(l)
for xf in range(0,l):
xs[xf]=10/D[xf]
plt.suptitle('I=%.2f$\mu A/cm^2$' %(-17.2+0.8*k2))
plt.xlabel('inverse noise intensity 1/D')
plt.ylabel('transition rate w $[10^3s^{-1}]$')
plt.yscale('log')
plt.plot(xs,1/btottime[:,k2],'bo',label='burst to eq')
#plt.plot(xs,breltime[1,:],label='D=3,burst')
#plt.plot(xs,breltime[2,:],label='D=4,burst')
#plt.plot(xs,eqreltime[3,:],label='D=4,burst')
plt.plot(xs,1/eqtottime[:,k2],'ro',label='eq to burst')
#plt.plot(xs,eqreltime[1,:],label='D=3,equilibrium')
#plt.plot(xs,eqreltime[2,:],label='D=4,equilibrium')
#plt.plot(xs,breltime[3,:],label='D=4,equilibrium')
popt,pcov = curve_fit(func, xs, 1/btottime[:,k2])
plt.plot(np.array(xs), func(np.array(xs), *popt), 'b-',label='fit burst to eq: r_0=%5.3f, U_+=%5.3f' % tuple(popt))
params[0][k2]=popt[0]
params[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, 1/eqtottime[:,k2])
plt.plot(np.array(xs), func(np.array(xs), *popt), 'r-',label='fiteq to burst: r_0=%5.3f, U_-=%5.3f' % tuple(popt))
params[2][k2]=popt[0]
params[3][k2]=popt[1]
plt.legend()
plt.savefig('arrheniustot1125%sfit%d.pdf' %(date1+date2,k2))
eqfile = open('param1125%s%d.txt' % (date1+date2,k2),'w')
for k3 in range(0,4):
eqfile.write('%.6f\n'%params[k3][k2])
eqfile.close()
ratefile = open('rate1125%s%d.txt' %(date1+date2,k2),'w')
for k4 in range(0,l):
ratefile.write('%.6f\n'%btottime[k4][k2])
for k4 in range(0,l):
ratefile.write('%.6f\n'%eqtottime[k4][k2])
ratefile.close()
plt.figure()
plt.xlabel('inverse noise intensity 1/D')
plt.ylabel('correlation time')
plt.yscale('log')
plt.plot(xs,1/(1/btottime[:,k2]+1/eqtottime[:,k2]))
plt.savefig('cortime1125%s%d.pdf' %(date1+date2,k2))
<file_sep>#
# Generated - do not edit!
#
# NOCDDL
#
CND_BASEDIR=`pwd`
CND_BUILDDIR=build
CND_DISTDIR=dist
# Debug configuration
CND_PLATFORM_Debug=GNU-Linux
CND_ARTIFACT_DIR_Debug=dist/Debug/GNU-Linux
CND_ARTIFACT_NAME_Debug=phasenraum
CND_ARTIFACT_PATH_Debug=dist/Debug/GNU-Linux/phasenraum
CND_PACKAGE_DIR_Debug=dist/Debug/GNU-Linux/package
CND_PACKAGE_NAME_Debug=phasenraum.tar
CND_PACKAGE_PATH_Debug=dist/Debug/GNU-Linux/package/phasenraum.tar
# Release configuration
CND_PLATFORM_Release=GNU-Linux
CND_ARTIFACT_DIR_Release=dist/Release/GNU-Linux
CND_ARTIFACT_NAME_Release=phasenraum
CND_ARTIFACT_PATH_Release=dist/Release/GNU-Linux/phasenraum
CND_PACKAGE_DIR_Release=dist/Release/GNU-Linux/package
CND_PACKAGE_NAME_Release=phasenraum.tar
CND_PACKAGE_PATH_Release=dist/Release/GNU-Linux/package/phasenraum.tar
#
# include compiler specific variables
#
# dmake command
ROOT:sh = test -f nbproject/private/Makefile-variables.mk || \
(mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk)
#
# gmake command
.PHONY: $(shell test -f nbproject/private/Makefile-variables.mk || (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk))
#
include nbproject/private/Makefile-variables.mk
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
date0='raterealrinzelpoi26n1realrinzel15ninv00'
file0=open('%s.txt'%date0,"r")
x0=[]
for k in file0:
row=k.split()
x0.append(float(row[0]))
ax0=np.array(x0)
datem1='raterealrinzel25onewrealfast19jjem2st6'
filem1=open('%s.txt'%datem1,"r")
xm1=[]
for k in filem1:
row=k.split()
xm1.append(float(row[0]))
axm1=np.array(xm1)
datep1='raterealrinzel25onewrealfast19jjem2st9'
filep1=open('%s.txt'%datep1,"r")
xp1=[]
for k in filep1:
row=k.split()
xp1.append(float(row[0]))
axp1=np.array(xp1)
y=np.array([ax0[1],ax0[3],ax0[5]])
y2=np.array([ax0[7],ax0[9],ax0[11]])
x=np.array([1/20,1/30,1/50])
plt.figure()
plt.ylabel('transition rate')
plt.xlabel('inverse noise intensity')
plt.yscale('log')
plt.plot(x,1/y,label='btoeq I=-11.4 with signal')
plt.plot(x,1/axm1[0:3],label='btoeq I=-12.4 without signal')
plt.plot(x,1/axp1[0:3],label='btoeq I=-10 without signal')
plt.plot(x,1/y2,label='eqtob I=-11.4 with signal')
plt.plot(x,1/axm1[3:6],label='eqtob I=-12.4 without signal')
plt.plot(x,1/axp1[3:6],label='eqtob I=-10 without signal')
plt.legend()
plt.savefig('arrhcomp.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
def spectrum(omega,a0,a1,omegas,eta0,c2,T):
return (1-(a1**2*eta0**2)/(2*(a0**2+omegas**2)))*((4*c2*a0)/(a0**2+omega**2))
Q=3
epsilon=1
omegas=0.001*2*np.pi
runs=500
points=1000000
length=500000
N=100000000
repetitions=10
dt=0.00001
T=N*repetitions*dt
T2=T*10
S=np.zeros(length)
#omegaind=round(omega*T)
file=open('/home/richard/outhome/ft8je1long3011.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
ax2=np.zeros(length)
ay2=np.zeros(length)
for l in range(0,length):
ax2[l]=ax[l]
ay2[l]=ay[l]
#background=np.mean([ay2[omegaind-1],ay2[omegaind-2],ay2[omegaind+1],ay2[omegaind+2],ay2[omegaind-3]])
#SNR=ay2[omegaind]/background
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
file2=open('/home/richard/NetBeansProjects/paramsdf16m.txt',"r")
param=[]
for k2 in file2:
row=k2.split()
param.append(float(row[0]))
aparam=np.array(param)
a0=2*aparam[2]*np.exp(-(aparam[1]*1.75+aparam[0])/Q)
a1=a0
a=(aparam[1]+aparam[4])/2
eta0=a*epsilon/Q
#c2=1.35**2/4
c2=126
amp=(np.pi*c2*a1**2*eta0**2*T)/(a0**2+omegas**2)
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('frequency')
plt.ylabel('power spectrum')
plt.yscale('log')
plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
#plt.xlim(4*10**(-4),100)
plt.plot(ax2*2*np.pi,ay2/T,label='Simulation')
plt.plot(ax2*2*np.pi,spectrum(ax2*2*np.pi,a0,a1,omegas,eta0,c2,T),label='theory')
plt.plot(omegas,amp,'x',label='deltapeak')
#plt.plot(omega,background/T,'kx')
plt.legend()
#plt.plot(sax2,say2/T2,label='e6')
plt.savefig('inapik8je1long3011wfom4.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def an(V):
return (10-V)/(100*(np.exp((10-V)/10)-1))
def am(V):
return (25-V)/(10*(np.exp((25-V)/10)-1))
def ah(V):
return 7*np.exp(-V/20)/100
def bn(V):
return np.exp(-V/80)/8
def bm(V):
return 4*np.exp(-V/18)
def bh(V):
return 1/(np.exp((30-V)/10)+1)
def minf(V):
return am(V)/(am(V)+bm(V))
def hinf(V):
return ah(V)/(ah(V)+bh(V))
def ninf(V):
return an(V)/(an(V)+bn(V))
def tau(V):
return 5*np.exp(-(((V+10)/55)**2))+1
def winf(S,V):
return S*(ninf(V)+S*(1-hinf(V)))/(1+S**2) # entspricht w-isokline
gL=0.3
VL=10
gNa=120
VNa=115
gK=36
VK=12 #12
phi=3.82
Iapp=-15 #-12
SV=1.27
def viso(W,V):
return W**4+(Iapp-gNa*((minf(V))**3)*(1-W)*(V-VNa)-gL*(V-VL))/(-gK*((1/SV)**4)*(V-VK))
v=np.arange(-50,150,0.01)
lv=len(v)
w=np.arange(-0.1,1.1,0.0001)
vvalues=np.zeros(lv)
edgepoints=np.zeros(4,dtype=int)
ii=0
vold=0
eqpoifile = open('eqpointsrinzelcorI%d.txt' %Iapp, 'w')
for k in range(0,lv):
vnew=w[np.where(abs(viso(w,v[k]))==min(abs(viso(w,v[k]))))[0][0]]
if abs(viso(vnew,v[k]))<0.1:
vvalues[k]=vnew
else:
vvalues[k]=vold
if k>0:
#if (winf(SV,v[k])-vold)*(winf(SV,v[k])-vnew)<0:
# eqpoifile.write('%.2f\n'%v[k])
if (winf(SV,v[k])-vvalues[k])*(winf(SV,v[k-1])-vvalues[k-1])<=0:
eqpoifile.write('%.2f\n'%v[k])
if ii==0:
if vold<0 and vnew>0 and v[k]<-10:
edgepoints[ii]=k
ii=ii+1
if ii==1:
if vold>0 and vnew<0 and v[k]>0:
edgepoints[ii]=k+1
ii=ii+1
if ii==2:
if vold<1 and vnew>1 and v[k]>10:
edgepoints[ii]=k
ii=ii+1
if ii==3:
if vold>0 and vnew<0 and v[k]>100:
edgepoints[ii]=k
vold=vnew
eqpoifile.close()
vrinzelfile = open('vncrinzel%d.txt' %Iapp, "w")
for kk in range(0,lv):
vrinzelfile.write('%.4f %.4f\n'%(v[kk],vvalues[kk]))
vrinzelfile.close()
edgepointfile= open('edgerinzel%d.txt' %Iapp, "w")
for ll in range(0,4):
edgepointfile.write('%d\n' %edgepoints[ll])
edgepointfile.close()
plt.figure()
plt.xlabel('membrane voltage V')
plt.ylabel('recovery variable W')
plt.plot(v,winf(SV,v),label='W-nullcline')
plt.plot(v[edgepoints[0]:edgepoints[1]],vvalues[edgepoints[0]:edgepoints[1]],'orange',label='V-nullcline')
plt.plot(v[edgepoints[2]:edgepoints[3]],vvalues[edgepoints[2]:edgepoints[3]],'orange')
plt.ylim(0,1)
plt.legend()
plt.savefig('rinzelclinescorm15a62.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
veco=np.zeros((2,15))
vec=np.zeros((4,20))
ii=0
for x in [12]:
col=[]
for y in range(5,6):
file=open('/home/richard/outhome/d26a%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
for y in range(7,21):
file=open('/home/richard/outhome/d26a%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
for z in range(0,15):
veco[0][z]=cola[z]
for x in [25]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/f29m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
for x in [30,40,50]:
col=[]
for y in range(1,21):
file=open('/home/richard/outhome/f7m%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
for z in range(0,20):
vec[ii][z]=cola[z]
ii=ii+1
#for x in [40]:
# col=[]
# for y in range(5,21):
# file=open('/home/richard/outhome/g17a%d%d.txt' % (x,y),"r")
# for k in file:
# row=k.split()
# col.append(row[1])
# cola=np.array(col)
# for z in range(0,16):
# vec[ii][z]=cola[z]
# ii=ii+1
xso=np.arange(0.5,4.25,0.25)
xs=np.arange(-0.75,4.25,0.25)
xsh=np.arange(1,4.2,0.2)
plt.xlabel('bias current I')
plt.ylabel('Fano factor')
plt.yscale('log')
#plt.plot(xsh,veco[0,:],label='D=1.2')
plt.plot(xs,vec[0,:],label='D=2.5')
plt.plot(xs,vec[1,:],label='D=3')
plt.plot(xs,vec[2,:],label='D=4')
plt.plot(xs,vec[3,:],label='D=5')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.legend()
plt.savefig('fneurp29mc.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def comp(x,a,b):
return a*x+b
N=50000000
dt=0.0005
T=N*dt
file=open('/home/richard/NetBeansProjects/detmodel/countI9a.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
cola=np.array(col)
colxa=np.array(colx)
a=174/9.8
a2=82/4
#xnew=np.arange(-0.19,0.31,0.01)
#popt,pcov = curve_fit(comp, xnew, cola/T)
t=np.arange(-0.2,0.3,0.01)
plt.xlabel('bias current I')
plt.ylabel('firing rate')
#plt.xlim(0,4)
#plt.ylim(1.2,1.4)
#plt.yscale('log')
plt.plot(colxa,cola/T)
#plt.plot(t,comp(t,popt[0],popt[1]),label='linear appr %f %f'%(popt[0],popt[1]))
#plt.legend()
plt.savefig('detmocount.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on April 9, 2019, 9:48 AM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <ios>
#include <iomanip>
using namespace std;
double average(long long int x[],int n);
double square(long long int x[],int n);
double ninf(double V, double k, double Vh);
double init(long long int x[],int n);
double initd(double x[],int n);
int main(int argc, char** argv) {
double D=atof(argv[1]);
double d=D*10;
double nr=atof(argv[2]);
double I=-1+0.25*nr;
ostringstream d_convert;
ostringstream nr_convert;
d_convert << d;
nr_convert << nr;
string d_str = d_convert.str();
string nr_str = nr_convert.str();
string filenamef="fa"+d_str+nr_str+".txt";
string filenamed="da"+d_str+nr_str+".txt";
string filenameg="ga"+d_str+nr_str+".txt";
string filenametime="timea"+d_str+nr_str+".txt";
string filenamevalues="valuesa"+d_str+nr_str+".txt";
ofstream myfile;
ofstream myfile2;
ofstream myfile3;
ofstream myfile4;
ofstream myfile5;
myfile.open (filenamed);
myfile2.open (filenameg);
myfile3.open (filenamef);
myfile4.open (filenametime);
myfile5.open (filenamevalues);
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
//double I0=-1; // 0
//double dI=0.2;
double gL=8; // 8
double EL=-80; // -80
double gNa=20; // 20
double ENa=60; // 60
double gK=9; // 9
double EK=-90; // -90
double gM=5; // 5
//slow K+ current
double kinf=5; // 5
double vinf=-20; // -20
double tauM=30; // 20
//Na current
double km=15; // 15
double vm=-20; // -20
//fast K+ current
double kn=5; // 5
double vn=-25; // -20
double tau=0.152; // 0.152
int N=50000000; //5*10⁷
int Neq=10000000; //10⁷
int points=10000;
int j;
double dt=0.00001;
//int spikes=100;
//double* spike=new double[spikes];
double th=-25;
double thn=0.5;
int runs=2; //5000
int sampling=runs*(N-Neq)/points;
//int Ivalues=25;
long long int count;
double Nav,N2av,T;
double mx,nx,nx2,v,nf,nfs,vs,Deff,vav,Fano,state[10000],times[10000],lastcount,prelastchange,lastchange,lasttime;
double vout[points],nout[points],bvout[points],cout[points];
int bv,lastbv,sv,t,p,j22,tv;
tv=0;
lastcount=0;
prelastchange=0;
lastchange=0;
lasttime=0;
sv=0;
t=1;
times[0]=0;
p=0;
//int s;
//for(s=0;s<Ivalues;s++){
nfs=0;
vs=-60;
mx=0.0285-0.0006*I;
nx=1.5-I/80;
nx2=1.65-I/80;
if(nfs>mx*vs+nx2){
bv=0;
}
else{
bv=1;
}
lastbv=bv;
state[0]=bv;
count=0;
for(int a=0;a<runs;a++){
for(j=0;j<Neq;j++){
v=I*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt/*+sqrt(2*D*dt)*n(gen)*/;
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
vs=v;
nfs=nf;
}
}
long long int e=0;
for(int a=0;a<runs;a++){
count=0;
for(int j2=0;j2<N-Neq;j2++){
j22=a*(N-Neq)+j2;
v=I*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt/*+sqrt(2*D*dt)*n(gen)*/;
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
if(v > th && vs < th){
sv=1;
}
if(sv==1 && nf > thn && nfs < thn){
count=count+1;
sv=0;
lastcount=j22;
}
if((bv==1 && nf>mx*v+nx2) || (bv==1 && (j22-lastcount)*dt>2)){
//if((j22-lastchange)*dt<0.4){
//bv=0;
//lastchange=prelastchange;
//}
//else{
bv=0;
//prelastchange=lastchange;
//lastchange=j22;
// if(t<10000){
// if(lastchange==times[t-1]*100000){}
// else{
//times[t]=lastchange*dt;
//t=t+1;
//}
}
if(bv==0 && nf<mx*v+nx){
//if((j22-lastchange)*dt<0.4){
// bv=1;
//lastchange=prelastchange;
//}
//else{
bv=1;
//prelastchange=lastchange;
//lastchange=j22;
//if(lastchange==times[t-1]*100000){}
// else{
// if(t<10000){
//times[t]=lastchange*dt;
//t=t+1;
//}
}
if(j22==40000*tv){
if((t<10000) && (0.5 < bv+lastbv) && (1.5 > bv+lastbv)){
times[t]=j22*dt;
state[t]=bv;
t=t+1;
}
tv=tv+1;
lastbv=bv;
}
if(j22==p*sampling){vout[p]=v;
nout[p]=nf;
bvout[p]=bv;
cout[p]=count;
p=p+1;
}
vs=v;
nfs=nf;
Nav=(Nav*e+count/runs)/(e+1);
N2av=(N2av*e+(count*count)/runs)/(e+1);
e=e+1;
}
}
T=2*N*dt;
Deff=(N2av-Nav*Nav)/T;
vav=2*Nav/T;
Fano=2*Deff/vav;
//}
myfile << I << " " << Deff << "\n";
myfile.close();
myfile2 << I << " " << vav <<"\n";
myfile2.close();
myfile3 << I << " " << Fano << "\n";
myfile3.close();
for(int rv=0;rv<10000;rv++){
myfile4 << times[rv] << " "<< state[rv]<< "\n";
}
myfile4.close();
for(int k=0;k<points;k++){
myfile5 << k*sampling*dt << " " << vout[k] << " "<< nout[k] << " " << bvout[k] << " " << cout[k]<< "\n";
}
myfile5.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(long long int x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
double square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
double init(long long int x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on March 26, 2019, 9:43 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
using namespace std;
double average(long long int x[],int n);
double square(long long int x[],int n);
double ninf(double V, double k, double Vh);
double init(long long int x[],int n);
double initd(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
myfile.open ("chaymodelvm62.txt");
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
double I0=0; // 0
double dI=0.5;
double gm=8; // 8
double Vm=-62; // -81
double gI=20; // 20
double VI=60; // 60
double gK=11; // 9
double VK=-90; // -90
//slow K+ current
double kn=7; // 12
double vn=-21; // -26
double tau=0.38; // 3
//Na current
double km=10; // 15
double vm=-20; // -20
//fast K+ current
double kh=-7; // -7
double vh=-3; // 7
int Neq=3000000;
int points=10000;
int sampling=Neq/points;
int j,f;
double dt=0.0001;
double D=0;
int runs=1;
double v[runs],nf[runs],nfs[runs],vs[runs],vout[points],hout[points];
int p=0;
nfs[0]=0.08;
vs[0]=-20;
for(j=0;j<Neq;j++){
for(int a=0;a<runs;a++){
v[a]=I0*dt+vs[a]-gm*(vs[a]-Vm)*dt-gI*ninf(vs[a],km,vm)*ninf(vs[a],kh,vh)*(vs[a]-VI)*dt-gK*(vs[a]-VK)*nfs[a]*dt-sqrt(2*D*dt)*n(gen);
nf[a]=nfs[a]+(ninf(vs[a],kn,vn)-nfs[a])*dt/tau;
if(j==p*sampling){vout[p]=v[a];
hout[p]=nf[a];
p=p+1;
}
vs[a]=v[a];
nfs[a]=nf[a];
}
}
for(f=0;f<points;f++){
myfile << f*sampling*dt << " " << vout[f] << " "<< hout[f] << "\n";
}
myfile.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(long long int x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
double square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
double init(long long int x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def deff(r0p,r0m,ap,am,bp,bm,t,D,v):
return (v**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
file=open('/home/richard/NetBeansProjects/parambarrier7m.txt',"r")
x=[]
for k in file:
row=k.split()
x.append(float(row[0]))
ax=np.array(x)
t=np.arange(0,4,0.01)
ap=ax[0]
am=ax[3]
bp=ax[1]
bm=ax[4]
r0p=ax[2]
r0m=ax[5]
v=1.33
plt.figure()
plt.xlabel('bias current I')
plt.ylabel('barrier height')
#plt.yscale('log')
plt.plot(t,barrier(am,bm,t),label='eq to burst')
plt.plot(t,barrier(ap,bp,t),label='burst to eq')
plt.plot(t,2*barrier(am,bm,t),label='2x eq to burst')
plt.plot(t,2*barrier(ap,bp,t),label='2x burst to eq')
plt.legend()
plt.savefig('calcbarr7m.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
#datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
#Dvar=np.array([30])
#lvar=len(Dvar)
#yvar=[4,13,3]
#yvalues=len(yvar)
timefac=1000
date='realrinzelrangelong26d1'
#date='realrinzelrangeshort1mtf1'
date1='realrinzelrange26d1'
date2='realrinzelrangeshort26d1'
D=[200]
#D=[50]
D1=[250,300]
D2=[400,500]
Dtot=D+D1+D2
l=len(D)+len(D1)+len(D2)
vecx=np.zeros((l,10))
vec=np.zeros((l,10))
ii=0
#for x in Dvar:
# colvar,colxvar=[],[]
# for kk in range(0,yvalues):
# ystart=1
# jj=0
# while jj < kk:
# ystart=ystart+yvar[jj]
# jj=jj+1
# for y in range(ystart,ystart+yvar[kk]):
# file=open('/home/richard/outhome/d%s%d%d.txt' % (datevar[kk],x,y),"r")
# for k in file:
# row=k.split()
# colxvar.append(float(row[0]))
# colvar.append(float(row[1]))
# colxavar=np.array(colxvar)
# colavar=np.array(colvar)
# for z in range(0,20):
# vec[ii][z]=colavar[z]
# ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D2:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
#xs=np.arange(-0.08,0.32,0.02)
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ $[s^{-1}]$')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,l):
# plt.plot(vecx[n,:],vec[n,:],label='D=%.2f,ic%i' %(Dtot[n]/10,round(n/3)))
plt.plot(vecx[n,:],vec[n,:]*timefac,label='D=%.0f' %(Dtot[n]/10))
plt.plot([-10.8, -10.8], [10, 10**6], color='black', linestyle='-',label='$I_{crit}$')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [3,4,2,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend()
plt.savefig('dneursinglecrit%s.pdf' %(date+date1))
vec=np.zeros((l,10))
vecx=np.zeros((l,10))
ii=0
#for x in Dvar:
# colvar,colxvar=[],[]
# for kk in range(0,yvalues):
# ystart=1
# jj=0
# while jj < kk:
# ystart=ystart+yvar[jj]
# jj=jj+1
# for y in range(ystart,ystart+yvar[kk]):
# file=open('/home/richard/outhome/f%s%d%d.txt' % (datevar[kk],x,y),"r")
# for k in file:
# row=k.split()
# colxvar.append(float(row[0]))
# colvar.append(float(row[1]))
# colxavar=np.array(colxvar)
# colavar=np.array(colvar)
# for z in range(0,20):
# vec[ii][z]=colavar[z]
# ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D2:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
plt.figure()
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Fano factor F')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,l):
#plt.plot(vecx[n,:],vec[n,:],label='D=%.2f,ic%i' %(Dtot[n]/10,round(n/3)))
plt.plot(vecx[n,:],vec[n,:],label='D=%.0f' %(Dtot[n]/10))
plt.plot([-10.8, -10.8], [0.07, 10**4], color='black', linestyle='-',label='$I_{crit}$')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [3,4,2,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend()
plt.savefig('fneursinglecrit%s.pdf' %(date+date1))
vec=np.zeros((l,10))
vecx=np.zeros((l,10))
ii=0
#for x in Dvar:
# colvar,colxvar=[],[]
# for kk in range(0,yvalues):
# ystart=1
# jj=0
# while jj < kk:
# ystart=ystart+yvar[jj]
# jj=jj+1
# for y in range(ystart,ystart+yvar[kk]):
# file=open('/home/richard/outhome/g%s%d%d.txt' % (datevar[kk],x,y),"r")
# for k in file:
# row=k.split()
# colxvar.append(float(row[0]))
# colvar.append(float(row[1]))
# colxavar=np.array(colxvar)
# colavar=np.array(colvar)
# for z in range(0,20):
# vec[ii][z]=colavar[z]
# ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D1:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
for x in D2:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
vecx[ii][z]=colxa[z]
ii=ii+1
N=50000000
dt=0.0005
T=N*dt
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countI9a.txt',"r")
col=[]
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
xburst=np.arange(-0.20,0.31,0.01)
plt.figure()
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('average firing rate <v> [$s^{-1}$]')
#plt.yscale('log')
#plt.xscale('log')
#plt.plot(xburst,cola/T,label='measured bursting rate',color='black')
for n in range(0,l):
#plt.plot(vecx[n,:],vec[n,:],label='D=%.2f,ic%i' %(Dtot[n]/10,round(n/3)))
plt.plot(vecx[n,:],vec[n,:]*timefac,label='D=%.0f' %(Dtot[n]/10))
#plt.plot(colxa,vec[0,:],label='D=%.2f' %(D[0]/100))
#plt.plot(xs,vec[3,:],label='D=1.5')
#plt.plot(xs,vec[0,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(colxa,cola,label='D=3e-3')
plt.legend()
plt.savefig('gneursingle3%s.pdf' %(date+date1))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
#matplotlib.rcParams.update({'font.size': 22})
timefac=1000 #convert ms to s
date='realfast19mtf'
date0='realfast23mtf'
date1='realfast9acoarsetf'
D=[45]
D1=[30]
datefull=date+date1+date0
l1=len(D1)
D0=[25,35]
l0=len(D0)
l=len(D)
ltot=l0+l+l1
Dtot=D1+D0+D
istart=1
ivalues=20
vec=np.zeros((ltot,20))
vecx=np.zeros((ltot,ivalues))
ii=0
offset=np.zeros(ltot,dtype=int)
for x in D1:
col1,colx1=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
if len(col1)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola1[z]*timefac
vecx[ii][z]=colxa1[z]
ii=ii+1
for x in D0:
col0,colx0=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date0,x,y),"r")
for k in file:
row=k.split()
colx0.append(float(row[0]))
col0.append(float(row[1]))
if len(col0)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa0=np.array(colx0)
cola0=np.array(col0)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola0[z]*timefac
vecx[ii][z]=colxa0[z]
ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola[z]*timefac
vecx[ii][z]=colxa[z]
ii=ii+1
plt.figure()
colorv=['y','g','b','r','c']
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ $[s^{-1}]$')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,ltot):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl],colorv[n],label='D=%.2f' %(Dtot[n]/100))
#plt.plot([0.165, 0.165], [5*10**(-1), 50000], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot([-0.022, -0.022], [5*10**(-1), 50000], color='black', linestyle='-')
#plt.legend()
handles, labels = plt.gca().get_legend_handles_labels()
order = [1,0,2,3]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('dneur%s.pdf' %datefull)
vec=np.zeros((ltot,20))
vecx=np.zeros((ltot,ivalues))
ii=0
offset=np.zeros(ltot,dtype=int)
for x in D1:
col1,colx1=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
if len(col1)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola1[z]*timefac
vecx[ii][z]=colxa1[z]
ii=ii+1
for x in D0:
col0,colx0=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date0,x,y),"r")
for k in file:
row=k.split()
colx0.append(float(row[0]))
col0.append(float(row[1]))
if len(col0)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa0=np.array(colx0)
cola0=np.array(col0)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola0[z]*timefac
vecx[ii][z]=colxa0[z]
ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola[z]*timefac
vecx[ii][z]=colxa[z]
ii=ii+1
plt.figure()
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Fano factor F')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,ltot):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl],colorv[n],label='D=%.2f' %(Dtot[n]/100))
#plt.plot([0.165, 0.165], [5*10**(-1), 50000], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot([-0.022, -0.022], [5*10**(-1), 50000], color='black', linestyle='-')
#plt.legend()
handles, labels = plt.gca().get_legend_handles_labels()
order = [1,0,2,3]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('fneur%s.pdf' %datefull)
vec=np.zeros((ltot,20))
vecx=np.zeros((ltot,ivalues))
ii=0
offset=np.zeros(ltot,dtype=int)
for x in D1:
col1,colx1=[],[]
for y in range(istart,istart+ivalues):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date1,x,y),"r")
for k in file:
row=k.split()
colx1.append(float(row[0]))
col1.append(float(row[1]))
if len(col1)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa1=np.array(colx1)
cola1=np.array(col1)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola1[z]*timefac
vecx[ii][z]=colxa1[z]
ii=ii+1
for x in D0:
col0,colx0=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date0,x,y),"r")
for k in file:
row=k.split()
colx0.append(float(row[0]))
col0.append(float(row[1]))
if len(col0)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa0=np.array(colx0)
cola0=np.array(col0)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola0[z]*timefac
vecx[ii][z]=colxa0[z]
ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
if len(col)+offset[ii]<y-istart+1:
offset[ii]=offset[ii]+1
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,20-offset[ii]):
vec[ii][z]=cola[z]*timefac
vecx[ii][z]=colxa[z]
ii=ii+1
N=50000000
dt=0.0005
T=N*dt
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countI9a.txt',"r")
col=[]
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)*timefac
xburst=np.arange(-0.20,0.31,0.01)
plt.figure()
colorv=['y','g','b','r','c']
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('average firing rate <v>$[s^{-1}]$')
#plt.yscale('log')
#plt.xscale('log')
plt.plot(xburst[12:51],cola[12:51]/T,label='running firing rate $v_0$',color='black')
for n in range(0,ltot):
nl=round(ivalues-offset[n])
plt.plot(vecx[n,0:nl],vec[n,0:nl],colorv[n])#,label='D=%.2f' %(Dtot[n]/100))
#plt.plot([0.165, 0.165], [5*10**(-1), 50000], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot([-0.022, -0.022], [5*10**(-1), 50000], color='black', linestyle='-')
#plt.xlim(-0.08,0.3)
plt.legend()
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [1,0,2,3]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('gneur%s.pdf' %datefull)
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on February 8, 2019, 1:40 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
using namespace std;
double average(long long int x[],int n);
double square(long long int x[],int n);
double ninf(double V, double k, double Vh);
double init(long long int x[],int n);
double initd(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
ofstream myfile2;
ofstream myfile3;
myfile.open ("defft.txt");
myfile2.open ("vavt.txt");
myfile3.open ("fanot.txt");
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
double I0=0; // 0
double gL=8; // 8
double EL=-80; // -80
double gNa=20; // 20
double ENa=60; // 60
double gK=9; // 9
double EK=-90; // -90
double gM=5; // 5
//slow K+ current
double kinf=5; // 5
double vinf=-20; // -20
double tauM=30; // 20
//Na current
double km=15; // 15
double vm=-20; // -20
//fast K+ current
double kn=5; // 5
double vn=-25; // -20
double tau=0.152; // 0.152
int N=500000;
int Neq=100000;
int j,f;
double dt=0.00001;
double D=5;
//int spikes=100;
//double* spike=new double[spikes];
double th=-25;
int runs=100;
long long int count[runs],sqcount[runs];
double Nav,N2av,T;
int points=1000;
int sampling=(N-Neq)/points;
double v[runs],nf[runs],nfs[runs],vs[runs],Deff,Deff2,Deffv[points],vav[points],Fano[points];
initd(nfs,runs);
initd(vs,runs);
init(count,runs);
for(j=0;j<Neq;j++){
for(int a=0;a<runs;a++){
v[a]=I0*dt+vs[a]-gL*(vs[a]-EL)*dt-gNa*ninf(vs[a],km,vm)*(vs[a]-ENa)*dt-gK*nfs[a]*(vs[a]-EK)*dt+sqrt(2*D*dt)*n(gen);
nf[a]=nfs[a]+(ninf(vs[a],kn,vn)-nfs[a])*dt/tau;
if(v[a] > th && vs[a] < th){
count[a]=count[a]+1;
}
vs[a]=v[a];
nfs[a]=nf[a];
}
}
int e=0;
double av=0;
double avv=0;
double avd=0;
double uG=0;
int p=0;
for(int j2=Neq;j2<N;j2++){
for(int a=0;a<runs;a++){
v[a]=I0*dt+vs[a]-gL*(vs[a]-EL)*dt-gNa*ninf(vs[a],km,vm)*(vs[a]-ENa)*dt-gK*nfs[a]*(vs[a]-EK)*dt+sqrt(2*D*dt)*n(gen);
nf[a]=nfs[a]+(ninf(vs[a],kn,vn)-nfs[a])*dt/tau;
if(v[a] > th && vs[a] < th){
count[a]=count[a]+1;
}
vs[a]=v[a];
nfs[a]=nf[a];
}
Nav=average(count,runs);
for(int j4=0;j4<runs;j4++){
sqcount[j4]=count[j4]*count[j4];
}
N2av=average(sqcount,runs);
T=2*j2*dt;
Deff=(N2av-Nav*Nav)/T;
Deff2=Deff*Deff;
av=(e*av+Deff)/(e+1);
avv=(e*avv+Nav/(T/2))/(e+1);
uG=(e*uG+4*Nav*Nav/(T*T))/(e+1);
avd=(e*avd+Deff2)/(e+1);
e=e+1;
if(j2==Neq+p*sampling){
Deffv[p]=Deff;
vav[p]=avv;
Fano[p]=2*Deffv[p]/vav[p];
p++;
}
}
Deffv[999]=Deff;
vav[999]=avv;
Fano[999]=2*Deff/avv;
for(f=0;f<points;f++){
myfile << Neq*dt+f*sampling*dt << " " << Deffv[f] << "\n";
}
myfile.close();
for(f=0;f<points;f++){
myfile2 << Neq*dt+f*sampling*dt << " " << vav[f] <<"\n";
}
myfile2.close();
for(f=0;f<points;f++){
myfile3 << Neq*dt+f*sampling*dt << " " << Fano[f] << "\n";
}
myfile3.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(long long int x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
double square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
double init(long long int x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
def spectrum(f,tau,sigma):
return (2*tau*sigma**2)/(1+(2*np.pi*f*tau)**2)
matplotlib.rcParams.update({'font.size': 16}) #20
omega=0.000005
runs=50
timefac=1000
date='realfast15mtf'
mode='spike'
D=45
istart=6
ivalues=1
nr=9
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/%s%s%d%d.txt' %(mode,date,D,z),"r")
#file=open('/home/richard/outhome/spikerealrinzel25o%d%d.txt' %(z,nr),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
l=len(ax)
if l==0:
continue
file2=open('/home/richard/outhome/%sshort%s%d%d.txt' %(mode,date,D,z),"r")
#file=open('/home/richard/outhome/spikerealrinzel25o%d%d.txt' %(z,nr),"r")
x,y=[],[]
for k in file2:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax2=np.array(x)
ay2=np.array(y)
l2=len(ax2)
if l2==0:
continue
param=open('/home/richard/outhome/param%s%d%d.txt' %(date,D,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
T=N*repetitions*dt
rate=open('/home/richard/outhome/g%s%d%d.txt' %(date,D,z),"r")
for k in rate:
row=k.split()
r=float(row[1])
deff=open('/home/richard/outhome/d%s%d%d.txt' %(date,D,z),"r")
for k in deff:
row=k.split()
d=float(row[1])
rate0=open('/home/richard/outhome/grealfast3jje02020.txt',"r")
for k in rate0:
row=k.split()
r0=float(row[1])
#background=np.mean([ay2[omegaind-1],ay2[omegaind-2],ay2[omegaind+1],ay2[omegaind+2],ay2[omegaind-3]])
#SNR=ay2[omegaind]/background
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
axmax=np.argmin(abs(ax-ax2[10]))+1
ind11=np.argmin(abs(ax-r0))
ind21=np.argmin(abs(ax2-r0))
ind1=np.argmax(ay[ind11-5:ind11+5])+ind11-5
ind2=np.argmax(ay2[ind21-5:ind21+5])+ind21-5
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plot1= plt.subplot(111)
plt.suptitle('I=%.2f, D=%.2f' %(-0.1+z*0.02,D*0.01))
#plt.suptitle('I=%.2f, D=%.2f' %(43+z*0.25,D/100))
plt.xlabel('Frequency $[s^{-1}]$')
plt.ylabel('Spectral power $[s^{-1}]$')
plt.yscale('log')
plt.xscale('log')
# plt.xlim(ax[0]*timefac,10000000/(2*T)*timefac)
#plt.xlim(4*10**(-4),100)
plt.plot(ax[0:axmax]*timefac,ay[0:axmax]*ax[0]*timefac,'blue')#,label='Simulation')
plt.plot(ax[l-11:l]*timefac,ay[l-11:l]*ax[0]*timefac,'blue')
plt.plot(ax2[10:-1]*timefac,ay2[10:-1]*ax2[0]*timefac,'blue')#,label='Simulation')
#plt.plot(ax[ind1]*timefac,ay[ind1]*timefac*ax[0],'x',color='blue')
#plt.plot(ax2[ind2]*timefac,ay2[ind2]*timefac*ax2[0],'x',color='orange')
plt.plot(ax[0:axmax]*timefac,r*np.ones(axmax)*timefac,'g',label='overall firing rate')
plt.plot(ax2[0:l2]*timefac,r*np.ones(l2)*timefac,'g')
plt.plot(ax[0:axmax]*timefac,5200*np.ones(axmax),'r--',label='background')
plt.plot(ax2[0:l2]*timefac,5200*np.ones(l2),'r--')
#plt.plot(ax[0:axmax]*timefac,2*d*np.ones(axmax)*timefac,'y',label='$2D_{eff}$')
#plt.plot(ax2[0:l2]*timefac,2*d*np.ones(l2)*timefac,'y')
#xdisplay, ydisplay = plot1.transAxes.transform_point((1, 2*d*timefac))
#plt.arrow(0.1, 0.1, -0.1, 0,transform=plot1.transAxes, length_includes_head=True,head_width=0.01,head_length=0.03)
#plt.plot(ax[0:axmax]*timefac,3*np.ones(axmax),'r--',label='background')
#plt.plot(ax2[0:l2]*timefac,3*np.ones(l2),'r--')
#plt.arrow(5*10**(-3),300,0,-299,length_includes_head=True)
plt.arrow(0.222, 0.75, 0, -0.75, transform=plot1.transAxes, length_includes_head=True,head_width=0.01,head_length=0.03)
#plt.arrow(0.222, 0.23, 0, -0.23, transform=plot1.transAxes, length_includes_head=True,head_width=0.01,head_length=0.03)
#plt.text(10**(-2),1,'signal')
#plt.text(10**(-2),0.7,'frequency')
plt.text(10**(-2),0.5,'signal')
plt.text(10**(-2),0.2,'frequency')
#plt.arrow(70,10,0,-9,length_includes_head=True)
#plt.arrow(0.5862, 0.6, 0, -0.6, transform=plot1.transAxes, length_includes_head=True,head_width=0.01,head_length=0.03)
plt.arrow(0.5862, 0.3, 0, -0.3, transform=plot1.transAxes, length_includes_head=True,head_width=0.01,head_length=0.03)
#plt.text(10**2,1,'firing rate')
#plt.text(10**(2),0.7,'in spiking state')
plt.text(10**2,0.5,'firing rate in')
plt.text(10**(2),0.2,'spiking state')
plt.text(8*10**(-7),1.3*d*timefac,'$2D_{eff}$')
#plt.plot(10**(-4),2*d*timefac,'bx')
plt.arrow(0.05, 0.778, -0.05, 0,transform=plot1.transAxes, length_includes_head=True,head_width=0.01,head_length=0.03)
#plt.plot(ax2,spectrum(ax2,1/(4.748*10**(-3)),13),label='theory')
#plt.plot(omega,background/T,'kx')
#plt.legend(bbox_to_anchor=(0.4, 0.65))
#plt.legend(loc='center right')
plt.legend()
#plt.plot(sax2,say2/T2,label='e6')
#plt.savefig('specglue%s%sD=%.2fI=%.2f.pdf' %(mode,date,D*0.01,-0.1+z*0.02))
#plot1.set_yticks(list(plot1.get_yticks()) +[2*d*timefac])
plot1.spines['right'].set_visible(False)
plot1.spines['top'].set_visible(False)
plt.tight_layout()
plt.savefig('specpaper62.pdf')
#plt.savefig('inapikanhopf%s2%sfourierD=%.2fI=%.2f.pdf' %(mode,date,D/100,43+z*0.25))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def an(V):
return (10-V)/(100*(np.exp((10-V)/10)-1))
def ah(V):
return 7*np.exp(-V/20)/100
def bn(V):
return np.exp(-V/80)/8
def bh(V):
return 1/(np.exp((30-V)/10)+1)
def hinf(V):
return ah(V)/(ah(V)+bh(V))
def ninf(V):
return an(V)/(an(V)+bn(V))
def winf(S,V):
return S*(ninf(V)+S*(1-hinf(V)))/(1+S**2) # entspricht w-isokline
gL=0.3
VL=10
gNa=120
VNa=115
gK=36
VK=12 #12
phi=3.82
Iapp=-10 #-12
SV=1.27
vec=np.arange(-50,150,0.01)
vrinzelfile = open('vncrinzel%d.txt' %Iapp, "r")
colx,col=[],[]
for k in vrinzelfile:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
edgepointfile= open('edgerinzel%d.txt' %Iapp, "r")
edge=[]
for k2 in edgepointfile:
row2=k2.split()
edge.append(int(row2[0]))
date='rinzela12time'
I=-10
v=open('/home/richard/cppworkshop/phasev%s%d.txt' %(date,I),"r")
#v=open('/home/richard/outhome/phasev%s%d.txt' %(date,I),"r")
vv=[]
for k in v:
num = float(k.rstrip())
vv.append(num)
av=np.array(vv)
vl=len(av)
n=open('/home/richard/cppworkshop/phasen%s%d.txt' %(date,I),"r")
#n=open('/home/richard/outhome/phasen%s%d.txt' %(date,I),"r")
vn=[]
for k2 in n:
num = float(k2.rstrip())
vn.append(num)
avn=np.array(vn)
nl=len(avn)
z=open('/home/richard/cppworkshop/phasez%s%d.txt' %(date,I),"r")
#z=open('/home/richard/outhome/phasez%s%d.txt' %(date,I),"r")
vz=np.zeros((nl,vl))
v=0
for k3 in z:
rowz=k3.split()
rowza=np.array(rowz)
for f in range(0,vl):
vz[v][f]=rowza[f]
v=v+1
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
plt.contourf(av,avn,abs(vz))
plt.colorbar()
plt.plot(colx[edge[0]:edge[1]],col[edge[0]:edge[1]],'blue',label='V-nullcline')
plt.plot(colx[edge[2]:edge[3]],col[edge[2]:edge[3]],'blue')
plt.plot(vec,winf(SV,vec),'orange',label='W-nullcline')
#plt.plot(t,b,label='barrier')
#plt.plot(t,s,label='barrier2')
#plt.plot(-62.5701,0.00054509, 'bo')
plt.ylim(-0.1,avn[-1])
#plt.xlim(8,12)
plt.suptitle('equil. time [ms]')
#plt.suptitle('spikes/starting point')
plt.xlabel('initial $V_0$')
plt.ylabel('initial $W_0$')
plt.legend(loc='upper right')
plt.tight_layout()
plt.savefig('contour%s.pdf' %date)
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
vec=np.zeros(20)
col,colx=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/d%d.txt' % (y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
colx.append(float(row[0]))
cola=np.array(col)
colxa=np.array(colx)
plt.xlabel('time constant k')
plt.ylabel('$D_{eff}$')
plt.yscale('log')
plt.plot(colxa,cola)
plt.savefig('dneurkvar.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on March 27, 2019, 2:51 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
ofstream myfile;
myfile.open("simplemodel5d2.txt");
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
double I,D,dt,vr,vs,vt,vpeak,k,b,a,c,d,vnew,vold,unew,uold;
int p,N,T,points,sampling,j,f;
I=0;
D=2;
vr=-60;
vs=-57;
vt=-55;
k=0.001;
b=0.2;
a=0.03;
c=-70;
d=-4;
vpeak=35;
T=10000;
dt=0.1;
N=T/dt;
points=10000;
double vout[points],uout[points];
sampling=N/points;
vold=0;
uold=0;
p=0;
for(j=0;j<N;j++){
vnew=vold+k*(vold-vr)*(vold-vt)*dt-uold*dt+I*dt+sqrt(2*D*dt)*n(gen);
unew=uold+a*(b*(vold-vs)-uold)*dt;
if(vnew>=vpeak){
vnew=c;
unew=d;
}
if(j==p*sampling){
vout[p]=vnew;
uout[p]=unew;
p=p+1;
}
uold=unew;
vold=vnew;
}
for(f=0;f<points;f++){
myfile << f*sampling*dt << " " << vout[f]<< " "<< uout[f]<<"\n";
}
myfile.close();
return 0;
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def finf(x,v12,k):
return 1/(1+np.exp((v12-x)/k))
def vnc(x,I,v12,k,gL,EL,gNa,ENa,gK,EK):
return (I-gL*(x-EL)-gNa*finf(x,v12,k)*(x-ENa))/(gK*(x-EK))
matplotlib.rcParams.update({'font.size': 22})
plt.axes().set_aspect(1)
style="Simple,tail_width=0.5,head_width=4,head_length=8"
kw = dict(arrowstyle=style, color="k")
a1 = patches.FancyArrowPatch((-36,0.87), (-70,0.5),connectionstyle="arc3,rad=.3",**kw )
a2 = patches.FancyArrowPatch((-70,0.45), (-55,0.15),connectionstyle="arc3,rad=.5",**kw)
a3 = patches.FancyArrowPatch((-52,0.15), (-30,0.7),connectionstyle="arc3,rad=.5", **kw)
a4 = patches.FancyArrowPatch((-30,0.75), (-35,0.85),connectionstyle="arc3,rad=.4", **kw)
I=46
gL=1
EL=-78
gNa=4
ENa=60
gK=4
EK=-90
km=7
vm=-30
kn=5
vn=-45
tau=1
t=np.arange(-75,-10,0.1)
plt.figure()
for a in [a1,a2,a3,a4]:
plt.gca().add_patch(a)
plt.xlabel('membrane voltage V [mV]')
plt.ylabel('gating variable n')
plt.plot(t,vnc(t,I,vm,km,gL,EL,gNa,ENa,gK,EK),label='v-nullcline')
plt.plot(t,finf(t,vn,kn),label='n-nullcline')
plt.plot(-50.2138,finf(-50.2138,vn,kn),'bo')
plt.text(-50.2138-1,finf(-50.2138,vn,kn)+0.02,'$P$')
plt.xlim((-75,-10))
plt.ylim((-0.1,1.1))
plt.legend()
plt.tight_layout()
plt.savefig('inapikanhopfnc.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
from scipy.optimize import curve_fit
matplotlib.rcParams.update({'font.size': 18})
def barrier(a,b,x):
return a * x + b
def r(r0,U,D):
return r0*np.exp(-U/D)
def snr(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,av,v0):
return (qr(r0m,am,bm,cm,t,D)*(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))/(v0**2*qr(r0p,ap,bp,cp,t,D)))*((((2*ap*t+bp)-(2*am*t+bm))*qr(r0p,ap,bp,cp,t,D)*v0)/(D*(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D)))+av)**2
def qbarrier(x,a,b,c):
return a*x**2+b*x+c
def qr(r0,a,b,c,t,D):
return r0*np.exp(-qbarrier(t,a,b,c)/D)
def deff(x,rp,rm,v0,av):
return ((v0+av*x)**2*rp*rm)/((rp+rm)**3)
def fano(x,rp,rm,v0,av):
return (2*(v0+av*x)*rp)/((rp+rm)**2)
def func(x, a, b):
return a * np.exp(-b * x)
def deffana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return ((barrier(av,v0,t))**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
def deffqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,av,v0):
return ((barrier(av,v0,t))**2*qr(r0p,ap,bp,cp,t,D)*qr(r0m,am,bm,cm,t,D))/((qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))**3)
def fanoana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return (2*barrier(av,v0,t)*r(r0p,ap,bp,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**2)
def vana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return barrier(av,v0,t)*r(r0m,am,bm,t,D)/(r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))
def vqana(r0p,r0m,ap,am,bp,bm,cp,cm,t,D,av,v0):
return barrier(av,v0,t)*qr(r0m,am,bm,cm,t,D)/(qr(r0p,ap,bp,cp,t,D)+qr(r0m,am,bm,cm,t,D))
def comp(x,b,c,d,e):
return b*x**3+c*x**2+d*x+e
def comps(x,b,c,d):
return 3*b*x**2+2*c*x+d
def fit(x,a,b):
return a/x+b
def rprime(r0,r0s,Us,D):
return (r0s/r0-Us/D)
def snrcor(r0p,r0m,up,um,ups,ums,D,av,v0,r0ps,r0ms):
return ((av*r(r0m,um,D)*(r(r0m,um,D)+r(r0p,up,D))+v0*(rprime(r0m,r0ms,ums,D)-rprime(r0p,r0ps,ups,D))*r(r0p,up,D)*r(r0m,um,D))**2)/((r(r0p,up,D)+r(r0m,um,D))*v0**2*r(r0p,up,D)*r(r0m,um,D))
#date3='realrinzel25o'
#date2='realrinzel15ninv0'
date1='realrinzelrange26d1'
date2='realrinzelrange26d1'
istart=1
ivalues=10
#l=3
#D1=[]
#D3=[500]
#D2=[200,300]
#Dvar=[]
#D=D1+D2+D3+Dvar
#Da=np.array(D)
#btoeq=np.zeros((l,ivalues))
#eqtob=np.zeros((l,ivalues))
#params=np.zeros((4,ivalues))
#paramsav=np.zeros((4,ivalues))
#params2=np.zeros(4)
#paramsq=np.zeros(6)
#paramsqrate=np.zeros(6)
#for k2 in range(0,ivalues):
# x=[]
# ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/rate%s%d.txt' %(date3+date2,k2),'r')
# for k4 in ratefile:
# row=k4.split()
# x.append(float(row[0]))
# ax=np.array(x)
# for k in range(0,l):
# btoeq[k][k2]=1/ax[k]
# eqtob[k][k2]=1/ax[k+l]
#
#xs=np.zeros(l)
#for b in range(0,l):
# xs[b]=10/Da[b]
#for k2 in range(0,ivalues):
# popt,pcov = curve_fit(func, xs, btoeq[:,k2])
# params[0][k2]=popt[0]
# params[1][k2]=popt[1]
# popt,pcov = curve_fit(func, xs, eqtob[:,k2])
# params[2][k2]=popt[0]
# params[3][k2]=popt[1]
#rbte=np.mean(params[0,:])
#retb=np.mean(params[2,:])
#istart=1
#xnew=np.arange(-22.5+istart,-22.5+istart+ivalues)*0.8
#barrier fit
#popt,pcov = curve_fit(qbarrier, xnew, params[1,:])
#paramsq[0]=popt[0]
#paramsq[1]=popt[1]
#paramsq[2]=popt[2]
#popt,pcov = curve_fit(qbarrier, xnew, params[3,:])
#paramsq[3]=popt[0]
#paramsq[4]=popt[1]
#paramsq[5]=popt[2]
#prefactor fit
#popt,pcov = curve_fit(qbarrier, xnew, params[0,:])
#paramsqrate[0]=popt[0]
#paramsqrate[1]=popt[1]
#paramsqrate[2]=popt[2]
#popt,pcov = curve_fit(qbarrier, xnew, params[2,:])
#paramsqrate[3]=popt[0]
#paramsqrate[4]=popt[1]
#paramsqrate[5]=popt[2]
#t1=np.arange(-18,-9,0.1)
#plt.figure()
#plt.plot(xnew,params[1,:],'go',label='burst to eq')
#plt.plot(xnew,params[3,:],'ro',label='eq to burst')
#plt.plot(t1,qbarrier(t1,paramsq[0],paramsq[1],paramsq[2]),'g')
#plt.plot(t1,qbarrier(t1,paramsq[3],paramsq[4],paramsq[5]),'r')
#plt.legend()
#plt.savefig('barrierinzelfit4.pdf')
#plt.figure()
#plt.plot(xnew,params[0,:],'go',label='burst to eq')
#plt.plot(xnew,params[2,:],'ro',label='eq to burst')
#plt.plot(t1,qbarrier(t1,paramsqrate[0],paramsqrate[1],paramsqrate[2]),'g')
#plt.plot(t1,qbarrier(t1,paramsqrate[3],paramsqrate[4],paramsqrate[5]),'r')
#plt.legend()
#plt.savefig('raterinzelfit4.pdf')
file=open('/home/richard/mastergit/pythonplots/arrhenius_analytics/detmocountparamparam.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
cola=np.array(col)
colxa=np.array(colx)
rbtoeq=np.zeros(ivalues)
ubtoeq=np.zeros(ivalues)
reqtob=np.zeros(ivalues)
ueqtob=np.zeros(ivalues)
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/param%s%d.txt' %(date1+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
rbtoeq[k2]=x[0]
ubtoeq[k2]=x[1]
reqtob[k2]=x[2]
ueqtob[k2]=x[3]
ups=np.zeros(ivalues-2)
ums=np.zeros(ivalues-2)
r0ms=np.zeros(ivalues-2)
r0ps=np.zeros(ivalues-2)
istep=0.8
xnew=np.arange(-21.25+istart,-21.25+istart+ivalues)*istep
for k3 in range(0,ivalues-2):
ups[k3]=(ubtoeq[k3+2]-ubtoeq[k3])/(2*istep)
ums[k3]=(ueqtob[k3+2]-ueqtob[k3])/(2*istep)
r0ps[k3]=(rbtoeq[k3+2]-rbtoeq[k3])/(2*istep)
r0ms[k3]=(reqtob[k3+2]-reqtob[k3])/(2*istep)
date='realrinzelrangelong26d1'
date1='realrinzelrange26d1'
date0='realrinzelrangeshort26d1'
date2='realrinzel13sig1'
D=[200]
D1=[250,300]
D0=[400,500]
D2=[]
Dto=D+D1+D0+D2
Dtot=np.array(Dto)
l2=len(Dtot)
points=1000000
length=500000
ivalues=10
istart=1
SNR=np.zeros((l2,ivalues))
scale=np.zeros((l2,ivalues))
xvec=np.zeros((l2,ivalues))
offset=np.zeros(l2,dtype=int)
ii=0
for c in D:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date,c,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
if len(x) == 0:
offset[ii]=offset[ii]+1
continue
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date,c,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart-offset[ii]]=epsilon**2*T
omegaind=round(omega*T)
#if c==200 and z==9:
# omegaind=2105
#omegaind=141
SNR[ii][z-istart-offset[ii]]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
iv=open('/home/richard/outhome/d%s%d%d.txt' %(date,c,z),"r")
for k in iv:
row=k.split()
xvec[ii][z-istart-offset[ii]]=float(row[0])
ii=ii+1
for c1 in D1:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date1,c1,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
if len(x) == 0:
offset[ii]=offset[ii]+1
continue
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date1,c1,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart-offset[ii]]=epsilon**2*T
omegaind=round(omega*T)
#omegaind=141
SNR[ii][z-istart-offset[ii]]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
iv=open('/home/richard/outhome/d%s%d%d.txt' %(date1,c1,z),"r")
for k in iv:
row=k.split()
xvec[ii][z-istart-offset[ii]]=float(row[0])
ii=ii+1
for c0 in D0:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date0,c0,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
if len(x) == 0:
offset[ii]=offset[ii]+1
continue
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date0,c0,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart-offset[ii]]=epsilon**2*T
omegaind=round(omega*T)
#omegaind=141
SNR[ii][z-istart-offset[ii]]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
iv=open('/home/richard/outhome/d%s%d%d.txt' %(date0,c0,z),"r")
for k in iv:
row=k.split()
xvec[ii][z-istart-offset[ii]]=float(row[0])
ii=ii+1
for c2 in D2:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date2,c2,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
if len(x) == 0:
offset[ii]=offset[ii]+1
continue
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date2,c2,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart-offset[ii]]=epsilon**2*T
omegaind=round(omega*T)
#omegaind=141
SNR[ii][z-istart-offset[ii]]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
iv=open('/home/richard/outhome/d%s%d%d.txt' %(date2,c2,z),"r")
for k in iv:
row=k.split()
xvec[ii][z-istart-offset[ii]]=float(row[0])
ii=ii+1
#params=4
#dvalues=6
#b=np.zeros(dvalues)
#c=np.zeros(dvalues)
#d=np.zeros(dvalues)
#e=np.zeros(dvalues)
#ii=0
#xnew=np.arange(-0.19,0.31,0.01)
#eqfile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/detmocountparam5.txt','r')
#for k in eqfile:
# col=[]
# row=k.split()
# for l in range(0,params):
# col.append(float(row[l]))
# cola=np.array(col)
# b[ii]=cola[0]
# c[ii]=cola[1]
# d[ii]=cola[2]
# e[ii]=cola[3]
# ii=ii+1
#eqfile.close()
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Signal-to-noise ratio SNR')
t=np.arange(-18,-8,0.1)
#xs=np.arange(-21.25+istart,-21.25+istart+ivalues)*0.8
xs=np.arange(-20+istart,-20+istart+ivalues)*0.6
plt.yscale('log')
#plt.xscale('log')
#plt.ylim(7*10**(-8),5*10**(-3))
plt.xlim(xnew[1]-0.4,xnew[ivalues-2]+0.4)
#plt.xlim(4*10**(-4),100)
#colorv=['r','y','c','g','k','b'] #6 colors
colorv=[ '#1f77b4', '#ff7f0e', '#2ca02c','#d62728','#9467bd']
#colorv=['y','g','b'] # 3 colors
#colorv=['y','c','g','k','b'] # 5 colors
#for n in range(0,1):
# nl=round(ivalues-offset[n])
#plt.plot(xvec[n,0:nl],(SNR[n,0:nl]-1)/scale[n,0:nl],colorv[n]+'o',label='D=%.2f' %(Dtot[n]*0.1))
# plt.plot(xvec[n,0:nl],abs((SNR[n,0:nl]-1))/scale[n,0:nl],'o',label='D=%.0f*' %(Dtot[n]*0.1))
for n in range(0,l2):
nl=round(ivalues-offset[n])
# plt.plot(xvec[n,0:nl],(SNR[n,0:nl]-1)/scale[n,0:nl],colorv[n]+'o',label='D=%.2f' %(Dtot[n]*0.1))
plt.plot(xvec[n,0:nl],abs((SNR[n,0:nl]-1))/scale[n,0:nl],label='D=%.0f' %(Dtot[n]*0.1))
#Dtot=[30,40,50,60]
#l2=len(Dtot)
#for n in range(0,l2):
#plt.plot(xnew[1:ivalues-1],snrcor(rbtoeq[1:ivalues-1],reqtob[1:ivalues-1],ubtoeq[1:ivalues-1],ueqtob[1:ivalues-1],ups,ums,Dtot[n]*0.1,comps(xnew[1:ivalues-1],fit(Dtot[n]/10,colxa[0],cola[0]),fit(Dtot[n]/10,colxa[1],cola[1]),fit(Dtot[n]/10,colxa[2],cola[2])),comp(xnew[1:ivalues-1],fit(Dtot[n]/10,colxa[0],cola[0]),fit(Dtot[n]/10,colxa[1],cola[1]),fit(Dtot[n]/10,colxa[2],cola[2]),fit(Dtot[n]/10,colxa[3],cola[3])),r0ps,r0ms)/8,colorv[n])#,label='D=%.0f' %(Dtot[n]*0.1))
#bv=b[2*n+1] # 3 plots
#cv=c[2*n+1]
#dv=d[2*n+1]
#ev=e[2*n+1]
#bv=b[n+1] # 5
#cv=c[n+1]
#dv=d[n+1]
#ev=e[n+1] #plt.plot(t,snr(rbte,retb,paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[n]*0.1,comps(t,b[n+1],c[n+1],d[n+1]),comp(t,b[n+1],c[n+1],d[n+1],e[n+1]))/8,colorv[n])
#plt.plot(t,snr(rbte,retb,paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[n]*0.1,comps(t,bv,cv,dv),comp(t,bv,cv,dv,ev))/8,colorv[n])
#plt.plot(t,snr(qbarrier(t,paramsqrate[0],paramsqrate[1],paramsqrate[2]),qbarrier(t,paramsqrate[3],paramsqrate[4],paramsqrate[5]),paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[n]*0.1,comps(t,bv,cv,dv),comp(t,bv,cv,dv,ev))/8,colorv[n])
#plt.plot(t,snr(qbarrier(t,paramsqrate[0],paramsqrate[1],paramsqrate[2]),qbarrier(t,paramsqrate[3],paramsqrate[4],paramsqrate[5]),paramsq[0],paramsq[3],paramsq[1],paramsq[4],paramsq[2],paramsq[5],t,Dtot[3]*0.1,comps(t,b[5],c[5],d[5]),comp(t,b[5],c[5],d[5],e[5]))/8,colorv[3])
#plt.plot([0.163, 0.163], [10**(-7), 10], color='black', linestyle='-')
#plt.plot([-0.02, -0.02], [10**(-7), 10], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot(xs,SNR[2,:],label='D=3')
#plt.plot(xs,SNR[1,:],label='D=2.5')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [0,2,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
#plt.plot(sax2,say2/T2,label='e6')
plt.plot([-10.8, -10.8], [10**(-8), 10**(-3)], color='black', linestyle='-',label='$I_{crit}$')
plt.plot([-13, -13], [10**(-8), 10**(-3)], color='black', linestyle='--',label='$I_{max}$')
#plt.plot([-10.8, -10.8], [10**(-38), 10**(5)], color='black', linestyle='-',label='$I_{crit}$')
plt.legend()
plt.tight_layout()
#plt.savefig('snrinzelrange26dcompletecritnofit3big.pdf')
#plt.savefig('snrinzelpred2big.pdf')
plt.savefig('snrinzelonlycritmaxdef.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
date3='ratenewrealfast11jjem2shnewrealfast19jjem2st'
date2=''
istart=1
ivalues=20
l=5
D=[35,45,40,50,30]
Da=np.array(D)
btoeq=np.zeros((l,ivalues))
eqtob=np.zeros((l,ivalues))
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/%s%d.txt' %(date3+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,l):
btoeq[k][k2]=1000/ax[k]
eqtob[k][k2]=1000/ax[k+l]
#xnew=np.arange(-22.5+istart,-22.5+istart+ivalues)*0.8
xnew=np.arange(-5+istart,-5+istart+ivalues)*0.02
#colorv=['y','g','b','r','c','k']
colorv=[ '#2ca02c', '#d62728','#9467bd','#1f77b4', '#ff7f0e']
#colorv=['b','r','k','g','y']
plt.figure()
plt.yscale('log')
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('transition rate r $[s^{-1}]$')
for n in range(0,2):
plt.plot(xnew,btoeq[n,:],colorv[n],marker='x',label='D=%.2f, sp. to eq.'%(Da[n]*0.01))
plt.plot(xnew,btoeq[n,:],colorv[n])
plt.plot(xnew,eqtob[n,:],colorv[n],marker='+')
plt.plot(xnew,eqtob[n,:],colorv[n])
for n in range(4,5):
plt.plot(xnew,btoeq[n,:],colorv[n],marker='x',label='D=%.2f, sp. to eq.'%(Da[n]*0.01))
plt.plot(xnew,btoeq[n,:],colorv[n])
plt.plot(xnew,eqtob[n,:],colorv[n],marker='+')
plt.plot(xnew,eqtob[n,:],colorv[n])
#plt.legend()
handles, labels = plt.gca().get_legend_handles_labels()
order = [2,0,1]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.savefig('tranratesneur32.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
def spectrum(f,tau,sigma):
return (2*tau*sigma**2)/(1+(2*np.pi*f*tau)**2)
omega=0.000005
runs=50
points=1000000
length=500000
date='realanhopftest'
D=20
istart=10
ivalues=1
nr=9
S=np.zeros(length)
#omegaind=round(omega*T)
for z in range(istart,istart+ivalues):
file=open('/home/richard/cppworkshop/spike%s%d%d.txt' %(date,D,z),"r")
#file=open('/home/richard/outhome/spikerealrinzel25o%d%d.txt' %(z,nr),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
if len(ax)==0:
continue
#ax2=np.zeros(length)
#ax2=np.zeros(points)
#ay2=np.zeros(points)
#ay2=np.zeros(length)
#for l in range(0,length):
#for l in range(0,points):
# ax2[l]=ax[l]
# ay2[l]=ay[l]
param=open('/home/richard/cppworkshop/param%s%d%d.txt' %(date,D,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
T=N*repetitions*dt
#rate=open('/home/richard/outhome/g%s%d%d.txt' %(date,D,z),"r")
#for k in rate:
# row=k.split()
# r=float(row[1])
#background=np.mean([ay2[omegaind-1],ay2[omegaind-2],ay2[omegaind+1],ay2[omegaind+2],ay2[omegaind-3]])
#SNR=ay2[omegaind]/background
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
ax3=np.arange(0,length)
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
#plt.suptitle('I=%.2f, D=%.2f' %(-0.1+z*0.02,D*0.01))
plt.suptitle('I=%.2f, D=%.2f' %(43+z*0.25,D/100))
plt.xlabel('Frequency $[10^3s^{-1}]$')
plt.ylabel('Spectral power')
plt.yscale('log')
plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
#plt.xlim(4*10**(-4),100)
plt.plot(ax,ay/T,label='Simulation')
#plt.plot(ax3/T,r*np.ones(length),label='running firing rate')
#plt.plot(ax2,spectrum(ax2,1/(4.748*10**(-3)),13),label='theory')
#plt.plot(omega,background/T,'kx')
#plt.legend()
#plt.plot(sax2,say2/T2,label='e6')
#plt.savefig('inapikrealfrange9aspD=%.2fI=%.2f.pdf' %(D*0.01,-0.1+z*0.02))
plt.savefig('inapikanhopf2%sfourierD=%.2fI=%.2f.pdf' %(date,D/100,43+z*0.25))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
#datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
#Dvar=np.array([30])
#lvar=len(Dvar)
#yvar=[4,13,3]
#yvalues=len(yvar)
date='realrinzel28o'
D=np.array([150,200])
l=len(D)
vec=np.zeros((l,10))
ii=0
#for x in Dvar:
# colvar,colxvar=[],[]
# for kk in range(0,yvalues):
# ystart=1
# jj=0
# while jj < kk:
# ystart=ystart+yvar[jj]
# jj=jj+1
# for y in range(ystart,ystart+yvar[kk]):
# file=open('/home/richard/outhome/d%s%d%d.txt' % (datevar[kk],x,y),"r")
# for k in file:
# row=k.split()
# colxvar.append(float(row[0]))
# colvar.append(float(row[1]))
# colxavar=np.array(colxvar)
# colavar=np.array(colvar)
# for z in range(0,20):
# vec[ii][z]=colavar[z]
# ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
# if x==300 and y==4:
# colx.append(float(row[0])+0.8)
# colx.append(float(row[0])+1.6)
# col.append(float(row[1]))
# col.append(float(row[1]))
# colx.append(float(row[0]))
# col.append(float(row[1]))
# for y in range(5,7):
# file=open('/home/richard/outhome/d%s%d%d.txt' % (date,x,y),"r")
# for k in file:
# row=k.split()
# colx.append(float(row[0]))
# col.append(float(row[1]))
# colx.append(float(row[0]))
# col.append(float(row[1]))
# for y in range(8,21):
# file=open('/home/richard/outhome/d%s%d%d.txt' % (date,x,y),"r")
# for k in file:
# row=k.split()
# colx.append(float(row[0]))
# col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
ii=ii+1
#xs=np.arange(-0.08,0.32,0.02)
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ $[10^3s^{-1}]$')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,l):
plt.plot(colxa,vec[n,:],label='D=%.2f' %(D[n]/10))
#plt.plot(colxa,vec[0,:],label='D=%.2f' %(D[0]/10))
plt.legend()
plt.savefig('dneursingle%s.pdf' %date)
vec=np.zeros((l,10))
ii=0
#for x in Dvar:
# colvar,colxvar=[],[]
# for kk in range(0,yvalues):
# ystart=1
# jj=0
# while jj < kk:
# ystart=ystart+yvar[jj]
# jj=jj+1
# for y in range(ystart,ystart+yvar[kk]):
# file=open('/home/richard/outhome/f%s%d%d.txt' % (datevar[kk],x,y),"r")
# for k in file:
# row=k.split()
# colxvar.append(float(row[0]))
# colvar.append(float(row[1]))
# colxavar=np.array(colxvar)
# colavar=np.array(colvar)
# for z in range(0,20):
# vec[ii][z]=colavar[z]
# ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/f%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
# if x==300 and y==4:
# colx.append(float(row[0])+0.8)
# colx.append(float(row[0])+1.6)
# col.append(float(row[1]))
# col.append(float(row[1]))
# colx.append(float(row[0]))
# col.append(float(row[1]))
# for y in range(5,7):
# file=open('/home/richard/outhome/f%s%d%d.txt' % (date,x,y),"r")
# for k in file:
# row=k.split()
# colx.append(float(row[0]))
# col.append(float(row[1]))
# colx.append(float(row[0]))
# col.append(float(row[1]))
# for y in range(8,21):
# file=open('/home/richard/outhome/f%s%d%d.txt' % (date,x,y),"r")
# for k in file:
# row=k.split()
# colx.append(float(row[0]))
# col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
ii=ii+1
plt.figure()
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Fano factor')
plt.yscale('log')
#plt.xscale('log')
for n in range(0,l):
plt.plot(colxa,vec[n,:],label='D=%.2f' %(D[n]/10))
#plt.plot(colxa,vec[0,:],label='D=%.2f' %(D[0]/10))
plt.legend()
plt.savefig('fneursingle%s.pdf' %date)
vec=np.zeros((l,10))
ii=0
#for x in Dvar:
# colvar,colxvar=[],[]
# for kk in range(0,yvalues):
# ystart=1
# jj=0
# while jj < kk:
# ystart=ystart+yvar[jj]
# jj=jj+1
# for y in range(ystart,ystart+yvar[kk]):
# file=open('/home/richard/outhome/g%s%d%d.txt' % (datevar[kk],x,y),"r")
# for k in file:
# row=k.split()
# colxvar.append(float(row[0]))
# colvar.append(float(row[1]))
# colxavar=np.array(colxvar)
# colavar=np.array(colvar)
# for z in range(0,20):
# vec[ii][z]=colavar[z]
# ii=ii+1
for x in D:
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
# if x==300 and y==4:
# colx.append(float(row[0])+0.8)
# colx.append(float(row[0])+1.6)
# col.append(float(row[1]))
# col.append(float(row[1]))
# colx.append(float(row[0]))
# col.append(float(row[1]))
# for y in range(5,7):
# file=open('/home/richard/outhome/g%s%d%d.txt' % (date,x,y),"r")
# for k in file:
# row=k.split()
# colx.append(float(row[0]))
# col.append(float(row[1]))
# colx.append(float(row[0]))
# col.append(float(row[1]))
# for y in range(8,21):
# file=open('/home/richard/outhome/g%s%d%d.txt' % (date,x,y),"r")
# for k in file:
# row=k.split()
# colx.append(float(row[0]))
# col.append(float(row[1]))
colxa=np.array(colx)
cola=np.array(col)
for z in range(0,10):
vec[ii][z]=cola[z]
ii=ii+1
N=50000000
dt=0.0005
T=N*dt
file=open('/home/richard/mastergit/NetBeansProjects/detmodel/countI9a.txt',"r")
col=[]
for k in file:
row=k.split()
col.append(float(row[1]))
cola=np.array(col)
xburst=np.arange(-0.20,0.31,0.01)
plt.figure()
#xs=np.arange(-0.75,4.25,0.25)
#xs=np.arange(0.25,2,0.25)
plt.xlabel('bias current I')
plt.ylabel('firing rate')
#plt.yscale('log')
#plt.xscale('log')
#plt.plot(xburst,cola/T,label='measured bursting rate',color='black')
for n in range(0,l):
plt.plot(colxa,vec[n,:],label='D=%.2f' %(D[n]/10))
#plt.plot(colxa,vec[0,:],label='D=%.2f' %(D[0]/100))
#plt.plot(xs,vec[3,:],label='D=1.5')
#plt.plot(xs,vec[0,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(colxa,cola,label='D=3e-3')
plt.legend()
plt.savefig('gneursingle%s.pdf' %date)
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
import matplotlib.patches as patches
plt.xlim(-5,5)
plt.ylim(-9,7)
plt.axes().set_aspect(1)
style="Simple,tail_width=0.5,head_width=4,head_length=8"
kw = dict(arrowstyle=style, color="k")
a1 = patches.FancyArrowPatch((-4,-6), (0,6),**kw )
a2 = patches.FancyArrowPatch((0,6), (4,-6),**kw)
a3 = patches.FancyArrowPatch((-4,-6), (4,-6),connectionstyle="arc3,rad=.5", **kw)
for a in [a1,a2,a3]:
plt.gca().add_patch(a)
plt.savefig('test2.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
axs=np.zeros(10000)
ays=np.zeros(10000)
azs=np.zeros(10000)
file=open('/home/richard/mainp2new/trainstatecomp5011.txt',"r")
x,y,z,a=[],[],[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
z.append(float(row[3]))
a.append(float(row[4]))
ax=np.array(x)
ay=np.array(y)
az=np.array(z)
aa=np.array(a)
#file2=open('/home/richard/mainp2new/train229a404.txt',"r")
#x2,y2,z2=[],[],[]
#for k in file2:
# row=k.split()
# x2.append(float(row[0]))
# y2.append(float(row[1]))
# z2.append(float(row[4]))
#ax2=np.array(x2)
#ay2=np.array(y2)
#az2=np.array(z2)
plt.figure()
plt.xlabel('time')
plt.ylabel('membrane voltage V')
#plt.xlim(850,950)
plt.plot(ax,ay,label='spike train')
plt.plot(ax,40*az-65,label='new bursting variable')
plt.plot(ax,40*aa-65,label='old bursting variable')
plt.legend()
plt.savefig('mainp2statecomp.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def barrier(a,b,x):
return a * x + b
def qbarrier(x,a,b,c):
return a*x**2+b*x+c
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def deff(x,rp,rm,v0,av):
return ((v0+av*x)**2*rp*rm)/((rp+rm)**3)
def v(x,rp,rm,v0,av):
return ((v0+av*x)*rm)/(rp+rm)
def func(x, a, b):
return a * np.exp(-b * x)
def deffana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return ((barrier(av,v0,t))**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
def fanoana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return (2*barrier(av,v0,t)*r(r0p,ap,bp,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**2)
def vana(r0p,r0m,ap,am,bp,bm,t,D,av,v0):
return barrier(av,v0,t)*r(r0m,am,bm,t,D)/(r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))
def fanofun(x,rp,rm,v0,av):
return 2*deff(x,rp,rm,v0,av)/v(x,rp,rm,v0,av)
def fit(x,a,b):
return a/x+b
def comp(x,b,c,d,e):
return b*x**3+c*x**2+d*x+e
matplotlib.rcParams.update({'font.size': 18})
timefac=1000
D2=[20,25,30]
D3=[]
D1=[15]
Dvar=[]
D=D1+D2+D3+Dvar
Da=np.array(D)
l1=len(D1)
l2=len(D2)
l3=len(D3)
lvar=len(Dvar)
l=l1+l2+l3+lvar
date1='realrinzelrange26d1'
date2='realrinzelrange26d1'
istart=1
ivalues=10
xnew=np.arange(172+istart,172+istart+ivalues)*0.25
file=open('/home/richard/mastergit/pythonplots/arrhenius_analytics/detmocountparamparam2.txt',"r")
col,colx=[],[]
for k in file:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
cola=np.array(col)
colxa=np.array(colx)
ivalues=10
rbtoeq=np.zeros(ivalues)
ubtoeq=np.zeros(ivalues)
reqtob=np.zeros(ivalues)
ueqtob=np.zeros(ivalues)
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/param%s%d.txt' %(date1+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
rbtoeq[k2]=x[0]
ubtoeq[k2]=x[1]
reqtob[k2]=x[2]
ueqtob[k2]=x[3]
def rred(r0,U,D):
return r0*np.exp(-U/D)
def deffred(rp,up,rm,um,v,D):
return (v**2*rred(rp,up,D)*rred(rm,um,D))/((rred(rp,up,D)+rred(rm,um,D))**3)
def vred(rp,up,rm,um,v,D):
return v*rred(rm,um,D)/(rred(rp,up,D)+rred(rm,um,D))
def fanored(rp,up,rm,um,v,D):
return 2*deffred(rp,up,rm,um,v,D)/vred(rp,up,rm,um,v,D)
#xs=np.arange(-5+istart,-5+istart+ivalues)*0.02
pv=np.arange(0,ivalues)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('$D_{eff}$ [$s^{-1}$]')
#plt.xlim(0,3.5)
#plt.ylim(5*10**(-2),2*10**3)
plt.yscale('log')
#plt.xlim(-0.08,0.2)
Dvec=np.array([2,3,4,5])
#colorv=['g','y','b','r','c']
colorv=[ '#1f77b4', '#ff7f0e', '#2ca02c','#d62728','#9467bd']
#t=np.arange(-0.1,0.3,0.01)
#for n in range(0,l):
# plt.plot(t,deffana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#for n in range(0,l):
# plt.plot(t,deffana(axx[2],axx[5],axx[0],axx[3],axx[1],axx[4],t,Da[n]/100,av,v0),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,l):
plt.plot((pv-20.25)*0.8,deffred(rbtoeq[pv],ubtoeq[pv],reqtob[pv],ueqtob[pv],comp((pv-20.25)*0.8,fit(Dvec[n],colxa[0],cola[0]),fit(Dvec[n],colxa[1],cola[1]),fit(Dvec[n],colxa[2],cola[2]),fit(Dvec[n],colxa[3],cola[3])),Dvec[n])*timefac,colorv[n],label='D=%.0f'%(Dvec[n]))
plt.plot([-10.8, -10.8], [10**(-26), 10**22], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,3,0,1,4]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order],loc='upper right', bbox_to_anchor=(0.65, 0.55))
plt.legend()#(loc='upper right', bbox_to_anchor=(0.8, 0.67))
plt.tight_layout()
plt.savefig('dcompdfpwnewpred4%s.pdf' %(date1+date2))
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('firing rate r [$s^{-1}$]')
#plt.yscale('log')
#colorv=['b','r','g','y','c']
t=np.arange(-0.1,0.3,0.01)
#for n in range(0,l):
# plt.plot(t,vana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,l):
plt.plot((pv-20.25)*0.8,vred(rbtoeq[pv],ubtoeq[pv],reqtob[pv],ueqtob[pv],comp((pv-20.25)*0.8,fit(Dvec[n],colxa[0],cola[0]),fit(Dvec[n],colxa[1],cola[1]),fit(Dvec[n],colxa[2],cola[2]),fit(Dvec[n],colxa[3],cola[3])),Dvec[n])*timefac,colorv[n],label='D=%.0f'%(Dvec[n]))
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,3,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order],loc='lower right')
plt.legend()
plt.tight_layout()
plt.savefig('gcompdfpwnewpred4%s.pdf' %(date1+date2))
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('Fano factor F')
plt.yscale('log')
#plt.xlim(-0.08,0.2)
#colorv=['b','r','g','y','c']
t=np.arange(-0.1,0.3,0.01)
#for n in range(0,l):
# plt.plot(t,fanoana(rbte,retb,params2[1],params2[3],params2[0],params2[2],t,Da[n]/100,v),colorv[n])
#plt.plot(xsh,veco[0,:],label='D=1.2')
for n in range(0,l):
plt.plot((pv-20.25)*0.8,fanored(rbtoeq[pv],ubtoeq[pv],reqtob[pv],ueqtob[pv],comp((pv-20.25)*0.8,fit(Dvec[n],colxa[0],cola[0]),fit(Dvec[n],colxa[1],cola[1]),fit(Dvec[n],colxa[2],cola[2]),fit(Dvec[n],colxa[3],cola[3])),Dvec[n])*timefac,colorv[n],label='D=%.0f'%(Dvec[n]))
#plt.plot(xs,vec[4,:],label='D=2')
#plt.plot(xs,vec[5,:],label='D=3')
#plt.plot(xs,vec[6,:],label='D=4')
plt.plot([-10.8, -10.8], [10**(-14), 10**25], color='black', linestyle='-',label='$I_{crit}$')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,3,0,1,4]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order],loc='lower left')
plt.legend()
plt.tight_layout()
plt.savefig('fcompdfpwnewpred4%s.pdf' %(date1+date2))
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
date3='raterealanhopf19flog'
date2='realanhopf11flog'
istart=4
ivalues=12
l=4
D=[20,25,30,35]
Da=np.array(D)
btoeq=np.zeros((l,ivalues))
eqtob=np.zeros((l,ivalues))
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/%s%d.txt' %(date3+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,l):
btoeq[k][k2]=1000/ax[k]
eqtob[k][k2]=1000/ax[k+l]
#xnew=np.arange(-22.5+istart,-22.5+istart+ivalues)*0.8
xnew=np.arange(172+istart,172+istart+ivalues)*0.25
#colorv=['y','g','b','r','c','k']
colorv=[ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
#colorv=['b','r','k','g','y']
plt.figure()
plt.yscale('log')
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('transition rate r $[s^{-1}]$')
for n in range(0,l-1):
plt.plot(xnew,btoeq[n,:],colorv[n+1],marker='x',label='D=%.2f, sp. to eq.'%(Da[n]*0.01))
plt.plot(xnew,btoeq[n,:],colorv[n+1])
plt.plot(xnew,eqtob[n,:],colorv[n+1],marker='+')
plt.plot(xnew,eqtob[n,:],colorv[n+1])
#plt.legend()
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [2,0,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
plt.legend()
plt.savefig('tranratesanhopfsp.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def comp(x,b,c,d,e):
return b*x**3+c*x**2+d*x+e
matplotlib.rcParams.update({'font.size': 20})
N=5000000
dt=0.005
T=N*dt
dvalues=6
ivalues=51
D=[150,200,250,300,400,500]
count=np.zeros((dvalues,ivalues))
ii=0
file=open('/home/richard/NetBeansProjects/detrinzel/countrinzelnoise5.txt',"r")
colx=[]
for k in file:
col=[]
row=k.split()
colx.append(float(row[0]))
for l in range(1,dvalues+1):
col.append(float(row[l]))
cola=np.array(col)
for l in range(0,dvalues):
count[l][ii]=cola[l]
ii=ii+1
colxa=np.array(colx)
a=174/9.8
a2=82/4
#a=np.zeros(dvalues)
b=np.zeros(dvalues)
c=np.zeros(dvalues)
d=np.zeros(dvalues)
e=np.zeros(dvalues)
#xnew=np.arange(-0.19,0.31,0.01)
eqfile = open('detmocountparam6.txt','w')
for n in range(0,dvalues):
popt,pcov = curve_fit(comp, colxa, count[n,:]/T)
# a[n]=popt[0]
b[n]=popt[0]
c[n]=popt[1]
d[n]=popt[2]
e[n]=popt[3]
for k3 in range(0,4):
eqfile.write('%.6f '%popt[k3])
eqfile.write('\n')
eqfile.close()
#colorv=['y','g','b','r','c','k']
colorv=[ '#1f77b4', '#ff7f0e', '#2ca02c','#d62728','#9467bd']
t=np.arange(-21,-6,0.1)
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('spiking firing rate $v_0$ [$s^{-1}$]')
#plt.xlim(0,4)
#plt.ylim(1.2,1.4)
#plt.yscale('log')
for n in range(2,dvalues):
plt.plot(colxa,count[n,:]/T*1000,'x',color=colorv[n-1],label='D=%.2s' %(D[n]/10))
plt.plot(t,comp(t,b[n],c[n],d[n],e[n])*1000,colorv[n-1])
#plt.plot(t,comp(t,popt[0],popt[1]),label='linear appr %f %f'%(popt[0],popt[1]))
plt.legend()
plt.tight_layout()
plt.savefig('detmocountrinzelcomp6big.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on February 13, 2019, 3:58 PM
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cmath>
#include <random>
#include <map>
#include <string>
#include <iomanip>
using namespace std;
double average(double x[],int n);
double square(double x[],int n);
double init(double x[],int n);
int main(int argc, char** argv) {
int filename=atof(argv[1]);
ostringstream filename_convert;
filename_convert << filename;
string filename_str = filename_convert.str();
string filename_str1="deffaism"+filename_str+".txt";
string filename_str2="vavaism"+filename_str+".txt";
string filename_str3="fanoaism"+filename_str+".txt";
string filename_str4="deffais"+filename_str+".txt";
string filename_str5="vavais"+filename_str+".txt";
string filename_str6="fanoais"+filename_str+".txt";
ofstream myfile;
ofstream myfile2;
ofstream myfile3;
ofstream myfile4;
ofstream myfile5;
ofstream myfile6;
myfile.open (filename_str1);
myfile2.open (filename_str2);
myfile3.open (filename_str3);
myfile4.open (filename_str4);
myfile5.open (filename_str5);
myfile6.open (filename_str6);
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
int T=5000;//Simulationszeit
//int O=1;//Anzahl der Kraftschritte
int P=1000;//Zeit, ab der gemittelt wird
//double df=0.02;
double dvalues[5]={0.033,0.043,0.056,0.072,0.094};
double v[100],vs[100];
double x[100],xs[100];
double dt=0.01;
int N=T/dt;
double F=0.7;//kleinste Kraft 0.55
double kT=dvalues[filename-1];
double gam=0.4;
int Neq=P/dt;
int points=1000;
int sampling=(N-Neq)/points;
int j,l,a2,f,g,g2;
double vavt,xavt,x2avt,defft;
double Deff[points],vav[points],Fano[points],Deffm[points],vavm[points],Fanom[points];
//Schleife über versch Kräfte
//Initialisierung von x
init(x,100);
init(xs,100);
//Initialisierung von v
init(v,100);
init(vs,100);
//Schleife über die ersten Zeitschritte
for(j=0;j<Neq;j++){
//Schleife über alle Teilchen
for(l=0;l<100;l++){
v[l]=vs[l]-gam*vs[l]*dt+F*dt-sin(xs[l])*dt+sqrt(2*kT*gam*dt)*n(gen);
x[l]=xs[l]+vs[l]*dt;
xs[l]=x[l];
vs[l]=v[l];
}
}
int p=0;
int e=0;
double av=0;
double avv=0;
//Schleife über die letzten Zeitschritte
for(a2=Neq;a2<N;a2++){
//Schleife über alle Teilchen
for(l=0;l<100;l++){
v[l]=vs[l]-gam*vs[l]*dt+F*dt-sin(xs[l])*dt+sqrt(2*kT*gam*dt)*n(gen);
x[l]=xs[l]+vs[l]*dt;
vs[l]=v[l];
xs[l]=x[l];
}
vavt=average(v,100);//mittl Geschwindigkeit
xavt=average(x,100);//mittl Position
square(x,100);
x2avt=average(x,100);//Mittel der Positionsquadrate
defft=(x2avt-xavt*xavt)/(2*(a2+1)*dt);//Diffusionskoeffizient
//Finden des Mittels der letzten Werte
av=(e*av+defft)/(e+1);
avv=(e*avv+vavt)/(e+1);
e=e+1;
if(a2==Neq+p*sampling){
Deff[p]=defft;
Deffm[p]=av;
vav[p]=vavt;
vavm[p]=avv;
Fano[p]=2*Deff[p]/vav[p];
Fanom[p]=2*Deffm[p]/vavm[p];
p++;
}
}
for(f=0;f<points;f++){
myfile << Neq*dt+f*sampling*dt << " " << Deffm[f] <<"\n";
}
for(g=0;g<points;g++){
myfile2 << Neq*dt+g*sampling*dt<< " " << vavm[g] << "\n";
}
for(g2=0;g2<points;g2++){
myfile3 << Neq*dt+g2*sampling*dt<< " " <<Fanom[g2] << "\n";
}
for(f=0;f<points;f++){
myfile4 << Neq*dt+f*sampling*dt << " " << Deff[f] <<"\n";
}
for(g=0;g<points;g++){
myfile5 << Neq*dt+g*sampling*dt<< " " << vav[g] << "\n";
}
for(g2=0;g2<points;g2++){
myfile6 << Neq*dt+g2*sampling*dt<< " " <<Fano[g2] << "\n";
}
myfile.close();
myfile2.close();
myfile3.close();
return 0;
}
double average(double x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
double square(double x[],int n){
int j;
for(j=0;j<n;j++){
x[j]*=x[j];
}
}
double init(double x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
col=[]
for y in range(1,31):
file=open('/home/richard/outhome/mechd%d.txt' % (y),"r")
for k in file:
row=k.split()
col.append(row[1])
cola=np.array(col)
xs=np.arange(-0.75,4.25,0.25)
plt.xlabel('bias current I')
plt.ylabel('$D_eff$')
plt.yscale('log')
plt.plot(xs,vec[4],label='D=1')
plt.plot(xs,vec[0,:],label='D=1.2')
plt.plot(xs,vec[1,:],label='D=2')
#plt.plot(xs,vec[[2],:],label='D=2')
plt.plot(xs,vec[2,:],label='D=3')
plt.plot(xs,vec[3,:],label='D=4')
#plt.plot(xs,vec[[5],:],label='D=5')
#plt.plot(xs,vec[[6],:],label='D=6')
plt.legend()
plt.savefig('dneurp.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b):
return a * np.exp(-b * x)
def func2(x, a, b):
return a * x + b
def func3(x, a):
return a
def fund(x,a,b,alpha):
return a * (1/x)**alpha * np.exp(-b * x)
D1=[35]
D2=[45]
D3=[40,50]
Dvar=[30]
D=D1+D2+D3+Dvar
l1=len(D1)
l2=len(D2)
l3=len(D3)
lvar=len(Dvar)
l=l1+l2+l3+lvar
date2='realfast19mtf'
date1='new'+'realfast19jjem2st'
date3='new'+'realfast11jjem2st'
datevar=['new'+'realfast11jjem2','new'+'realfast11jjem2sh','new'+'realfast11jjem2']
istart=9
ivalues=1
params2=np.zeros(6)
params=np.zeros((4,ivalues))
changespertime=np.zeros((l,ivalues))
eqtottime=np.zeros((l,ivalues))
eqreltime=np.zeros((l,ivalues))
btottime=np.zeros((l,ivalues))
breltime=np.zeros((l,ivalues))
intdelay=np.zeros((l,ivalues))
matplotlib.rcParams.update({'font.size': 22})
ii=0
for x in D2:
for y in range(istart,istart+ivalues):
avalues,jrvalues,j2values,state=[],[],[],[]
file=open('/home/richard/outhome/timenew%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
avalues.append(float(row[0]))
jrvalues.append(float(row[1]))
j2values.append(float(row[2]))
state.append(float(row[3]))
j2valuesa=np.array(j2values)
jrvaluesa=np.array(jrvalues)
avaluesa=np.array(avalues)
statea=np.array(state)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date2,x,y),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
Ndiff=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
runs=value[name.index('runs')]
countb=0
counteq=0
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
inteq[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
intb[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
if avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff>avaluesa[2*z]*repetitions+jrvaluesa[2*z]+j2valuesa[2*z]/Ndiff:
intb[z]=(((avaluesa[2*z+1]-avaluesa[2*z])*repetitions+jrvaluesa[2*z+1]-jrvaluesa[2*z])*Ndiff+j2valuesa[2*z+1]-j2valuesa[2*z])*dt
countb=countb+1
else:
break
intbt=np.zeros(countb)
for c in range(0,countb):
intbt[c]=intb[c]
for z in range(0,4999):
if avaluesa[2*z+2]*repetitions+jrvaluesa[2*z+2]+j2valuesa[2*z+2]/Ndiff>avaluesa[2*z+1]*repetitions+jrvaluesa[2*z+1]+j2valuesa[2*z+1]/Ndiff:
inteq[z]=(((avaluesa[2*z+2]-avaluesa[2*z+1])*repetitions+jrvaluesa[2*z+2]-jrvaluesa[2*z+1])*Ndiff+j2valuesa[2*z+2]-j2valuesa[2*z+1])*dt
counteq=counteq+1
else:
break
inteqt=np.zeros(counteq)
for c in range(0,counteq):
inteqt[c]=inteq[c]
intdelay[ii][y-istart]=sum(i < 500 for i in intbt)/countb
counts=counteq+countb
countsrel=counts/Ndiff
changespertime[ii][y-istart]=countsrel/(repetitions*runs)
plt.figure()
plt.xlabel('interval length [s]')
plt.ylabel('number of intervals')
plt.hist(intbt/1000, bins=50)
plt.yscale('log')
plt.title("sp. intervals, $I=%.2f$, $D=%.2f$" %((-5+y)*0.02,x/100), fontsize=22)
plt.tight_layout()
plt.savefig('bdistplotmaster3.pdf')# %(date1,x,y))
plt.figure()
plt.xlabel('interval length [s]')
plt.ylabel('number of intervals')
plt.hist(inteqt/1000, bins=50)
plt.yscale('log')
plt.title("eq. intervals, $I=%.2f$, $D=%.2f$" %((-5+y)*0.02,x/100), fontsize=22)
plt.tight_layout()
plt.savefig('eqdistplotmaster3.pdf')# %(date1,x,y))
eqtot=np.sum(inteqt)
btot=np.sum(intbt)
eqrel=eqtot/(eqtot+btot)
brel=btot/(eqtot+btot)
eqtottime[ii][y-istart]=eqtot/counteq
btottime[ii][y-istart]=btot/countb
eqreltime[ii][y-istart]=eqrel
breltime[ii][y-istart]=brel
ii=ii+1
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on March 25, 2019, 4:02 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
using namespace std;
double average(long long int x[],int n);
double square(long long int x[],int n);
double init(long long int x[],int n);
double initd(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
myfile.open ("mechdet2.txt");
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> n(0,1);
int O=1;//Anzahl der Kraftschritte
int P=20;//Zeit, ab der gemittelt wird
double dt=0.0001;
double F=0.7;//kleinste Kraft 0.55
double kT=0;
double gam=0.4;
int Neq=P/dt;
int j,l,a2,f,g,g2,s;
double vavt,xavt,x2avt,defft;
int points=10000;
int sampling=Neq/points;
double v,x,xs,vs,vout[points],xout[points];
int p=0;
vs=1.4;
//Schleife über die ersten Zeitschritte
for(j=0;j<Neq;j++){
//Schleife über alle Teilchen
v=vs-gam*vs*dt+F*dt-sin(xs)*dt+sqrt(2*kT*gam*dt)*n(gen);
x=xs+vs*dt;
if(j==p*sampling){vout[p]=v;
xout[p]=x;
p=p+1;
}
xs=x;
vs=v;
}
for(f=0;f<points;f++){
myfile << f*sampling*dt << " " << vout[f] << " "<< xout[f] << "\n";
}
myfile.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(long long int x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
double square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
double init(long long int x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def deff(r0p,r0m,ap,am,bp,bm,t,D,v):
return (v**2*r(r0p,ap,bp,t,D)*r(r0m,am,bm,t,D))/((r(r0p,ap,bp,t,D)+r(r0m,am,bm,t,D))**3)
file=open('/home/richard/NetBeansProjects/parambarrier16m.txt',"r")
x=[]
for k in file:
row=k.split()
x.append(float(row[0]))
ax=np.array(x)
t=np.arange(0,4,0.01)
ap=ax[0]
am=ax[3]
bp=ax[1]
bm=ax[4]
r0p=ax[2]
r0m=ax[5]
v=1.33
plt.figure()
plt.xlabel('bias current I')
plt.ylabel('$D_{eff}$')
plt.yscale('log')
for k in range(2,6):
plt.plot(t,deff(r0p,r0m,ap,am,bp,bm,t,k,v),label='D=%d' %k)
plt.legend()
plt.savefig('arrhdeff16m.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
def finf(x,v12,k):
return 1/(1+np.exp((v12-x)/k))
def vnc(x,I,v12,k,gL,EL,gNa,ENa,gK,EK):
return (I-gL*(x-EL)-gNa*finf(x,v12,k)*(x-ENa))/(gK*(x-EK))
I=0.2
gL=0.3
EL=-80
gNa=1
ENa=60
gK=0.4
EK=-90
km=14
vm=-18
kn=5
vn=-25
tau=3
file=open('/home/richard/mastergit/NetBeansProjects/inapik/inapreali20.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[1]))
y.append(float(row[2]))
ax=np.array(x)
ay=np.array(y)
t=np.arange(-60,5,0.1)
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
#plt.xlabel('time [s]')
plt.xlabel('membrane voltage V [mV]')
plt.ylabel('gating variable n')
plt.plot(t,vnc(t,I,vm,km,gL,EL,gNa,ENa,gK,EK),label='v-nullcline')
plt.plot(t,finf(t,vn,kn),label='n-nullcline')
#plt.gcf().subplots_adjust(left=0.15)
plt.plot(ax,ay,'black')
#plt.xlim(0,0.5)
#plt.legend()
plt.tight_layout()
plt.savefig('inapreali20fontblack.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on June 27, 2019, 9:20 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <iostream>
using namespace std;
double ninf(double V, double k, double Vh);
void init(double x[],int n);
int main(int argc, char** argv) {
ofstream myfile;
myfile.open ("countanhopfa16.txt");
double I0=43; // 0
double gL=1; // 8
double EL=-78; // -80
double gNa=4; // 20
double ENa=60; // 60
double gK=4; // 9
double EK=-90; // -90
//Na current
double km=7; // 15
double vm=-30; // -20
//fast K+ current
double kn=5; // 5
double vn=-45; // -20
double tau=1; // 0.152
int N0;
N0=500000000;
int runs=50;
double count[runs];
double v,vs,nf,nfs;
double th=-60;
vs=-50;
nfs=0.7;
int j,f;
double dt,dt0;
dt0=0.00005;
init(count,runs);
for(int a=0;a<runs;a++){
dt=dt0*pow(1.1,a);
int N=round(N0/(pow(1.1,a)));
for(j=0;j<N;j++){
v=I0*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt;
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
if(v > th && vs < th){
count[a]=count[a]+1;
}
vs=v;
nfs=nf;
}
}
for(f=0;f<runs;f++){
myfile << dt0*pow(1.1,f) << " " << count[f] << "\n";
}
myfile.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
void init(double x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
points=100000
file=open('/home/richard/NetBeansProjects/inapik/inapi18d3.txt',"r")
x,y,z,a=[],[],[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
v2=np.zeros(points)
vav=np.mean(ay)
for i in range(0,points):
v2[i]=(ay[i]-vav)**2
v2av=np.mean(v2)
plt.figure()
plt.xlabel('time')
plt.ylabel('membrane voltage')
plt.xlim(50,70)
plt.plot(ax,ay,label='%.6f' %v2av)
#plt.plot(ax,az)
#plt.plot(ax,aa)
plt.legend()
plt.savefig('inapivar3.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
eqreltime=np.zeros((4,20))
breltime=np.zeros((4,20))
ii=0
for x in [10,20,30,40]:
times,state=[],[]
for y in range(1,21):
file=open('/home/richard/outhome/times11a%d%d.txt' % (x,y),"r")
for k in file:
row=k.split()
times.append(float(row[0]))
state.append(float(row[1]))
timesa=np.array(times)
statea=np.array(state)
if statea[0]<0.5:
intb=np.zeros(4999)
inteq=np.zeros(5000)
for z in range(0,5000):
inteq[z]=timesa[2*z+1]-timesa[2*z]
for z in range(0,4999):
intb[z]=timesa[2*z+2]-timesa[2*z+1]
else:
inteq=np.zeros(4999)
intb=np.zeros(5000)
for z in range(0,5000):
intb[z]=timesa[2*z+1]-timesa[2*z]
for z in range(0,4999):
inteq[z]=timesa[2*z+2]-timesa[2*z+1]
plt.hist(intb, bins=50)
plt.title("distribution of bursting time intervals")
plt.savefig('bdist%d%d.pdf' %(x,y))
plt.hist(inteq, bins=50)
plt.title("distribution of equilibrium time intervals")
plt.savefig('eqdist%d%d.pdf' %(x,y))
eqtot=np.sum(inteq)
btot=np.sum(intb)
eqrel=eqtot/(eqtot+btot)
brel=btot/(eqtot+btot)
eqreltime[ii][y]=eqrel
breltime[ii][y]=brel
ii=ii+1
xs=np.arange(-0.75,4.25,0.25)
plt.xlabel('bias current I')
plt.ylabel('proportion of simulation time')
plt.plot(xs,eqreltime[0,:],label='D=1,burst')
plt.plot(xs,eqreltime[1,:],label='D=2,burst')
plt.plot(xs,eqreltime[2,:],label='D=3,burst')
plt.plot(xs,eqreltime[3,:],label='D=4,burst')
plt.plot(xs,breltime[0,:],label='D=1,equilibrium')
plt.plot(xs,breltime[1,:],label='D=2,equilibrium')
plt.plot(xs,breltime[2,:],label='D=3,equilibrium')
plt.plot(xs,breltime[3,:],label='D=4,equilibrium')
plt.legend()
plt.savefig('inapiktimes.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
matplotlib.rcParams.update({'font.size': 16})
def qbarrier(x,a,b,c):
return a*x**2+b*x+c
def func(x, a, b):
return a * np.exp(-b * x)
date2='realanhopf11flog'
date1='realanhopf19flog'
ivalues=12
l=4
D1=[20,25,30,35]
D3=[]
D2=[]
Dvar=[]
D=D1+D2+D3+Dvar
Da=np.array(D)
btoeq=np.zeros((l,ivalues))
eqtob=np.zeros((l,ivalues))
params=np.zeros((4,ivalues))
paramsq=np.zeros(6)
paramsqrate=np.zeros(6)
for k2 in range(0,ivalues):
x=[]
ratefile = open('/home/richard/mastergit/pythonplots/arrhenius_analytics/rate%s%d.txt' %(date1+date2,k2),'r')
for k4 in ratefile:
row=k4.split()
x.append(float(row[0]))
ax=np.array(x)
for k in range(0,l):
btoeq[k][k2]=1/ax[k]
eqtob[k][k2]=1/ax[k+l]
av=0.1/12
v0=0.47
xs=np.zeros(l)
for b in range(0,l):
xs[b]=100/Da[b]
for k2 in range(0,ivalues):
popt,pcov = curve_fit(func, xs, btoeq[:,k2])
params[0][k2]=popt[0]
params[1][k2]=popt[1]
popt,pcov = curve_fit(func, xs, eqtob[:,k2])
params[2][k2]=popt[0]
params[3][k2]=popt[1]
rbte=np.mean(params[0,:])
retb=np.mean(params[2,:])
istart=4
xnew=np.arange(172+istart,172+istart+ivalues)*0.25
#barrier fit
popt,pcov = curve_fit(qbarrier, xnew, params[1,:])
paramsq[0]=popt[0]
paramsq[1]=popt[1]
paramsq[2]=popt[2]
popt,pcov = curve_fit(qbarrier, xnew, params[3,:])
paramsq[3]=popt[0]
paramsq[4]=popt[1]
paramsq[5]=popt[2]
#prefactor fit
popt,pcov = curve_fit(qbarrier, xnew, params[0,:])
paramsqrate[0]=popt[0]
paramsqrate[1]=popt[1]
paramsqrate[2]=popt[2]
popt,pcov = curve_fit(qbarrier, xnew, params[2,:])
paramsqrate[3]=popt[0]
paramsqrate[4]=popt[1]
paramsqrate[5]=popt[2]
t1=np.arange(-0.1,0.32,0.01)
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('potential barrier')
plt.plot(xnew,params[1,:],'go',label='sp. to eq.')
plt.plot(xnew,params[3,:],'ro',label='eq. to sp.')
plt.plot(xnew,params[1,:],'g')
plt.plot(xnew,params[3,:],'r')
#plt.plot(t1,qbarrier(t1,paramsq[0],paramsq[1],paramsq[2]),'g')
#plt.plot(t1,qbarrier(t1,paramsq[3],paramsq[4],paramsq[5]),'r')
plt.legend()
plt.tight_layout()
plt.savefig('barrieranhopfbig.pdf')
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('rate prefactor')
plt.plot(xnew,params[0,:],'go',label='sp. to eq.')
plt.plot(xnew,params[2,:],'ro',label='eq. to sp.')
plt.plot(xnew,params[0,:],'g')
plt.plot(xnew,params[2,:],'r')
#plt.plot(t1,qbarrier(t1,paramsqrate[0],paramsqrate[1],paramsqrate[2]),'g')
#plt.plot(t1,qbarrier(t1,paramsqrate[3],paramsqrate[4],paramsqrate[5]),'r')
plt.legend()
plt.tight_layout()
plt.savefig('rateranhopfbig.pdf')
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('potential barrier')
plt.plot(xnew,params[1,:],'g^',label='sp. to eq.')
plt.plot(xnew,params[3,:],'r^',label='eq. to sp.')
plt.plot(xnew,2*params[1,:],'gs',label='2x sp. to eq.')
plt.plot(xnew,2*params[3,:],'rs',label='2x eq. to sp.')
plt.plot(xnew,params[1,:],'g')
plt.plot(xnew,params[3,:],'r')
plt.plot(xnew,2*params[1,:],'g')
plt.plot(xnew,2*params[3,:],'r')
plt.plot([44.98, 44.98], [0,6], color='black', linestyle='-',label='$I_{crit}$')
plt.plot([46.1, 46.1], [0,6], color='black', linestyle='-')
plt.legend()
plt.tight_layout()
plt.savefig('barriercompanhopfcritbig.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on January 8, 2019, 12:48 PM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <iostream>
using namespace std;
double ninf(double V, double k, double Vh);
double init(double x[],int n);
double an(double V);
double bn(double V);
double am(double V);
double bm(double V);
double ah(double V);
double bh(double V);
int main(int argc, char** argv) {
ofstream myfile;
myfile.open ("counthh.txt");
double mu=6.5; // 0
double dI=0.06;
double gL=0.3; // 8
double EL=10; // -80
double gNa=120; // 20
double ENa=115; // 60
double gK=36; // 9
double EK=-12; // -90
int N0;
N0=50000000;
int runs=51;
double count[runs];
double v,vs,nf,nfs,mf,mfs,hf,hfs;
double th=50;
vs=0;
nfs=0.35;
mfs=0.6;
hfs=0.6;
int j,f;
double dt;
dt=0.0005;
init(count,runs);
for(int a=0;a<runs;a++){
for(j=0;j<N0;j++){
v=(mu+a*dI)*dt+vs+gL*(EL-vs)*dt+gNa*pow(mfs,3)*hfs*(ENa-vs)*dt+gK*pow(nfs,4)*(EK-vs)*dt;
nf=nfs+an(vs)*(1-nfs)*dt-bn(vs)*nfs*dt;
mf=mfs+am(vs)*(1-mfs)*dt-bm(vs)*mfs*dt;
hf=hfs+ah(vs)*(1-hfs)*dt-bh(vs)*hfs*dt;
if(v > th && vs < th){
count[a]=count[a]+1;
}
vs=v;
nfs=nf;
mfs=mf;
hfs=hf;
}
}
for(f=0;f<runs;f++){
myfile << mu+dI*f << " " << count[f] << "\n";
}
myfile.close();
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double init(double x[],int n){
int k;
for(k=0;k<n;k++){
x[k]=0;
}
}
double an(double V){
double f=(10-V)/(100*(exp((10-V)/10)-1));
return f;
}
double am(double V){
double f=(25-V)/(10*(exp((25-V)/10)-1));
return f;
}
double ah(double V){
double f=7*exp(-V/20)/100;
return f;
}
double bn(double V){
double f=exp(-V/80)/8;
return f;
}
double bm(double V){
double f=4*exp(-V/18);
return f;
}
double bh(double V){
double f=1/(exp((30-V)/10)+1);
return f;
}<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def an(V):
return (10-V)/(100*(np.exp((10-V)/10)-1))
def am(V):
return (25-V)/(10*(np.exp((25-V)/10)-1))
def ah(V):
return 7*np.exp(-V/20)/100
def bn(V):
return np.exp(-V/80)/8
def bm(V):
return 4*np.exp(-V/18)
def bh(V):
return 1/(np.exp((30-V)/10)+1)
def minf(V):
return am(V)/(am(V)+bm(V))
def hinf(V):
return ah(V)/(ah(V)+bh(V))
def ninf(V):
return an(V)/(an(V)+bn(V))
def tau(V):
return 5*np.exp(-(((V+10)/55)**2))+1
def winf(S,V):
return S*(ninf(V)+S*(1-hinf(V)))/(1+S**2) # entspricht w-isokline
gL=0.3
VL=10
gNa=120
VNa=115
gK=36
VK=12 #12
phi=3.82
Iapp=-10 #-12
SV=1.27
def viso(W,V):
return W**4+(Iapp-gNa*((minf(V))**3)*(1-W)*(V-VNa)-gL*(V-VL))/(-gK*((1/SV)**4)*(V-VK))
vrinzelfile = open('vncrinzel%d.txt' %Iapp, "r")
colx,col=[],[]
for k in vrinzelfile:
row=k.split()
colx.append(float(row[0]))
col.append(float(row[1]))
edgepointfile= open('edgerinzel%d.txt' %Iapp, "r")
edge=[]
for k2 in edgepointfile:
row2=k2.split()
edge.append(int(row2[0]))
plt.axes().set_aspect(1)
style="Simple,tail_width=0.5,head_width=4,head_length=8"
kw = dict(arrowstyle=style, color="k")
a1 = patches.FancyArrowPatch((55,1.07), (13,1),connectionstyle="arc3,rad=.3",**kw )
a2 = patches.FancyArrowPatch((3,0.9), (8,0.7),connectionstyle="arc3,rad=.2",**kw)
a3 = patches.FancyArrowPatch((15,0.7), (75,0.85),connectionstyle="arc3,rad=.3", **kw)
a4 = patches.FancyArrowPatch((75,0.9), (60,1.05),connectionstyle="arc3,rad=.4", **kw)
v=np.arange(-50,150,0.01)
plt.figure()
for a in [a1,a2,a3,a4]:
plt.gca().add_patch(a)
plt.xlabel('membrane voltage V [mV]')
plt.ylabel('recovery variable W')
plt.plot(v,winf(SV,v),'orange',label='W-nullcline')
plt.plot(colx[edge[0]:edge[1]],col[edge[0]:edge[1]],'blue',label='V-nullcline')
plt.plot(colx[edge[2]:edge[3]],col[edge[2]:edge[3]],'blue')
plt.plot(-23.2,winf(SV,-23.2),'bo')
plt.plot(1.3,winf(SV,1.3),'o',color='purple')
plt.plot(20.9,winf(SV,20.9),'ro')
plt.text(-23.2-7,winf(SV,-23.2)+0.02,'$P_1$')
plt.text(1.3-6,winf(SV,1.3)+0.02,'$P_2$')
plt.text(20.9-5,winf(SV,20.9)+0.02,'$P_3$')
plt.ylim(0,1.1)
plt.legend()
plt.savefig('rinzelclinesarrowwp.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
file=open('/home/richard/mastergit/NetBeansProjects/realstatevar/realstate125.txt',"r")
x,y,z,a=[],[],[],[]
for k in file:
row=k.split()
x.append(float(row[1]))
y.append(float(row[2]))
z.append(float(row[3]))
a.append(float(row[4]))
ax=np.array(x)
ay=np.array(y)
az=40*np.array(z)-65
aa=-np.array(a)/40
def finf(x,v12,k):
return 1/(1+np.exp((v12-x)/k))
def vnc(x,I,v12,k,gL,EL,gNa,ENa,gK,EK):
return (I-gL*(x-EL)-gNa*finf(x,v12,k)*(x-ENa))/(gK*(x-EK))
I=0.1
gL=0.3
EL=-80
gNa=1
ENa=60
gK=0.4
EK=-90
km=14
vm=-18
kn=5
vn=-25
tau=3
t=np.arange(-80,0,0.01)
matplotlib.rcParams.update({'font.size': 22})
plt.figure()
axs = plt.subplot(111)
plt.plot(t,vnc(t,I,vm,km,gL,EL,gNa,ENa,gK,EK),label='v-nullcline')
plt.plot(t,finf(t,vn,kn),label='n-nullcline')
plt.suptitle('$I$=-0.1$\mu A/cm^2$')
plt.ylabel('gating variable n')
plt.xlabel('membrane voltage [mV]')
#plt.xlim(3.75,4.25)
axs.plot(ax[25001:28433],ay[25001:28433],'black')
#plt.plot(ax,az)
#plt.plot(ax,aa)
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
plt.legend()
plt.tight_layout()
plt.savefig('realstatep125vshbig.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft
def barrier(a,b,x):
return a * x + b
def r(r0,a,b,t,D):
return r0*np.exp(-barrier(a,b,t)/D)
def drdi(t,r0,a,b):
return (a*r0)/((1+np.exp(-barrier(a,b,t)))*(1+np.exp(barrier(a,b,t))))
def snr(r0p,r0m,ap,am,bp,bm,t,D):
return (ap-am)**2/(D**2*(r(r0p,ap,bp,t,D)**(-1)+r(r0m,am,bm,t,D)**(-1)))
def snrtheo(t,r0,a,b,f):
return drdi(t,r0,a,b)**2/(8*f**2)
def snrmeas(drdr,f):
return (drdr**2/(8*f**2))
f=1
date='realrinzel25o'
date1='realfast9aem2sh'
D=[200,300,500]
D1=[]
Dtot=D+D1
l=len(D)+len(D1)
points=1000000
length=500000
ivalues=10
SNR=np.zeros((l,ivalues))
scale=np.zeros((l,ivalues))
ii=0
#for c in D:
# for z in range(1,21):
# file=open('/home/richard/outhome/spike%s%d%d.txt' %(date,c,z),"r")
# x,y=[],[]
# for k in file:
# row=k.split()
# x.append(float(row[0]))
# y.append(float(row[1]))
# ax=np.array(x)
# ay=np.array(y)
# param=open('/home/richard/outhome/param%s%d%d.txt' %(date,c,z),"r")
# ll=0
# name,value=[],[]
# for k in param:
# row=k.split()
# lp=len(row)
# if ll<1:
# for jj in range(0,lp):
# name.append(row[jj])
# else:
# for kk in range(0,lp):
# value.append(float(row[kk]))
# ll=ll+1
# dt=value[name.index('dt')]
# N=value[name.index('N')]-value[name.index('Neq')]
# repetitions=value[name.index('repetitions')]
# epsilon=value[name.index('epsilon')]
# omega=value[name.index('omega')]
# T=N*repetitions*dt
# scale[ii][z-1]=epsilon**2*T
# omegaind=round(omega*T)
# SNR[ii][z-1]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
# ii=ii+1
#
#for c1 in D1:
# for z in range(1,21):
# file=open('/home/richard/outhome/spike%s%d%d.txt' %(date1,c1,z),"r")
# x,y=[],[]
# for k in file:
# row=k.split()
# x.append(float(row[0]))
# y.append(float(row[1]))
# ax=np.array(x)
# ay=np.array(y)
# param=open('/home/richard/outhome/param%s%d%d.txt' %(date1,c1,z),"r")
# ll=0
# name,value=[],[]
# for k in param:
# row=k.split()
# lp=len(row)
# if ll<1:
# for jj in range(0,lp):
# name.append(row[jj])
# else:
# for kk in range(0,lp):
# value.append(float(row[kk]))
# ll=ll+1
# dt=value[name.index('dt')]
# N=value[name.index('N')]-value[name.index('Neq')]
# repetitions=value[name.index('repetitions')]
# epsilon=value[name.index('epsilon')]
# omega=value[name.index('omega')]
# T=N*repetitions*dt
# scale[ii][z-1]=epsilon**2*T
# omegaind=round(omega*T)
# SNR[ii][z-1]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
# ii=ii+1
D0=[200,300,500]
D3=[]
D2=[]
Dvar=[]
D=D0+Dvar+D3+D2
Da=np.array(D)
l0=len(D0)
l2=len(D2)
l3=len(D3)
lvar=len(Dvar)
l=l2+l3+lvar+l0
date3='realfast11jjem2sh'
date2='realfast19jjem2st'
datevar=['realfast11jjem2','realfast11jjem2sh','realfast11jjem2']
yvar=[4,13,3]
yvalues=len(yvar)
ii=0
istart0=1
ivalues0=10
istart2=1
ivalues2=10
vec=np.zeros((l,ivalues))
for x in D0:
col0,colx0=[],[]
for y in range(istart0,istart0+ivalues0):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx0.append(float(row[0]))
col0.append(float(row[1]))
colxa0=np.array(colx0)
cola0=np.array(col0)
for z in range(0,ivalues0):
vec[ii][z]=cola0[z]
ii=ii+1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/d%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
vec[ii][z]=colavar[z]
ii=ii+1
istart3=1
ivalues3=20
for x in D3:
col3,colx3=[],[]
for y in range(istart3,istart3+ivalues3):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx3.append(float(row[0]))
col3.append(float(row[1]))
colxa3=np.array(colx3)
cola3=np.array(col3)
for z in range(0,ivalues3):
vec[ii][z]=cola3[z]
ii=ii+1
for x in D2:
col2,colx2=[],[]
for y in range(istart2,istart2+ivalues2):
file=open('/home/richard/outhome/d%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx2.append(float(row[0]))
col2.append(float(row[1]))
colxa2=np.array(colx2)
cola2=np.array(col2)
for z in range(0,ivalues2):
vec[ii][z]=cola2[z]
ii=ii+1
istep=0.8
ii=0
gvec=np.zeros((l,ivalues))
#drdr=np.zeros((l,ivalues-2))
D0,D2,D3,Dvar=[],[],[],[]
for x in D0:
col0,colx0=[],[]
for y in range(istart0,istart0+ivalues0):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date,x,y),"r")
for k in file:
row=k.split()
colx0.append(float(row[0]))
col0.append(float(row[1]))
colxa0=np.array(colx0)
cola0=np.array(col0)
for z in range(0,ivalues0):
gvec[ii][z]=cola0[z]
for z in range(0,8):
drdr[ii][z]=(cola0[z+2]-cola0[z])/(2*istep)
ii=ii+1
for x in Dvar:
colvar,colxvar=[],[]
for kk in range(0,yvalues):
ystart=1
jj=0
while jj < kk:
ystart=ystart+yvar[jj]
jj=jj+1
for y in range(ystart,ystart+yvar[kk]):
file=open('/home/richard/outhome/g%s%d%d.txt' % (datevar[kk],x,y),"r")
for k in file:
row=k.split()
colxvar.append(float(row[0]))
colvar.append(float(row[1]))
colxavar=np.array(colxvar)
colavar=np.array(colvar)
for z in range(0,20):
gvec[ii][z]=colavar[z]
for z in range(0,18):
drdr[ii][z]=(colavar[z+2]-colavar[z])/(2*istep)
ii=ii+1
for x in D3:
col3,colx3=[],[]
for y in range(istart3,istart3+ivalues3):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date3,x,y),"r")
for k in file:
row=k.split()
colx3.append(float(row[0]))
col3.append(float(row[1]))
colxa3=np.array(colx3)
cola3=np.array(col3)
for z in range(0,ivalues3):
gvec[ii][z]=cola3[z]
for z in range(0,18):
drdr[ii][z]=(cola3[z+2]-cola3[z])/(2*istep)
ii=ii+1
for x in D2:
col2,colx2=[],[]
for y in range(istart2,istart2+ivalues2):
file=open('/home/richard/outhome/g%s%d%d.txt' % (date2,x,y),"r")
for k in file:
row=k.split()
colx2.append(float(row[0]))
col2.append(float(row[1]))
colxa2=np.array(colx2)
cola2=np.array(col2)
for z in range(0,ivalues2):
gvec[ii][z]=cola2[z]
for z in range(0,18):
drdr[ii][z]=(cola2[z+2]-cola2[z])/(2*istep)
ii=ii+1
istep=0.3
drdr=np.zeros((l,10))
drdrlong=np.zeros((l,50))
d2z,d3z,d5z=[],[],[]
filerate=open('/home/richard/outhome/countrinzelrate.txt',"r")
for k in filerate:
row=k.split()
d2z.append(float(row[2]))
d3z.append(float(row[4]))
d5z.append(float(row[6]))
d2=np.array(d2z)/10000000
d3=np.array(d3z)/10000000
d5=np.array(d5z)/10000000
for z in range(0,10):
drdr[0][z]=abs((d2[round(9.5+(8/3)*(z+1))+1]-d2[round(9.5+(8/3)*(z+1))])/istep)
drdr[1][z]=abs((d3[round(9.5+(8/3)*(z+1))+1]-d3[round(9.5+(8/3)*(z+1))])/istep)
drdr[2][z]=abs((d5[round(9.5+(8/3)*(z+1))+1]-d5[round(9.5+(8/3)*(z+1))])/istep)
for z in range(0,50):
drdrlong[0][z]=abs((d2[z+1]-d2[z])/istep)
drdrlong[1][z]=abs((d3[z+1]-d3[z])/istep)
drdrlong[2][z]=abs((d5[z+1]-d5[z])/istep)
xsold=np.arange(-69.5+1,-69.5+51)*0.3
plt.figure()
plt.xlabel('bias current I')
plt.ylabel('derivative of firing rate')
plt.yscale('log')
colorv=['y','g','b','r','c']
for n in range(0,l):
plt.plot(xsold,drdrlong[n,:],colorv[n],label='D=%.0f' %Da[n])
plt.legend()
plt.savefig('drdirinzellong.pdf')
date='realrinzel20ninv0'
date2='realrinzel20ninv1'
date1='realrinzel15ninv0'
date3='realrinzel15ninv1'
D=[200,300]
D1=[500]
D2=[]
D3=[]
Dtot=D+D1+D2+D3
l=len(D)+len(D1)+len(D2)+len(D3)
points=1000000
length=500000
istart=1
ivalues=10
SNR=np.zeros((l,ivalues))
scale=np.zeros((l,ivalues))
ii=0
for c in D:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date,c,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date,c,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart]=epsilon**2*T
omegaind=round(omega*T)
if c==200 and z==9:
omegaind=2105
SNR[ii][z-istart]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
for c1 in D1:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date1,c1,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date1,c1,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart]=epsilon**2*T
omegaind=round(omega*T)
SNR[ii][z-istart]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
for c2 in D2:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date2,c2,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
if len(x)==0:
SNR[ii][z-istart]=SNR[ii][z-istart-1]
scale[ii][z-istart]=scale[ii][z-istart-1]
else:
param=open('/home/richard/outhome/param%s%d%d.txt' %(date2,c2,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart]=epsilon**2*T
omegaind=round(omega*T)
SNR[ii][z-istart]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
for c3 in D3:
for z in range(istart,istart+ivalues):
file=open('/home/richard/outhome/spike%s%d%d.txt' %(date3,c3,z),"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
param=open('/home/richard/outhome/param%s%d%d.txt' %(date3,c3,z),"r")
ll=0
name,value=[],[]
for k in param:
row=k.split()
lp=len(row)
if ll<1:
for jj in range(0,lp):
name.append(row[jj])
else:
for kk in range(0,lp):
value.append(float(row[kk]))
ll=ll+1
dt=value[name.index('dt')]
N=value[name.index('N')]-value[name.index('Neq')]
repetitions=value[name.index('repetitions')]
epsilon=value[name.index('epsilon')]
omega=value[name.index('omega')]
T=N*repetitions*dt
scale[ii][z-istart]=epsilon**2*T
omegaind=round(omega*T)
SNR[ii][z-istart]=ay[omegaind]/np.mean([ay[omegaind-1],ay[omegaind-2],ay[omegaind+1],ay[omegaind+2],ay[omegaind-3]])
ii=ii+1
#files=open('/home/richard/NetBeansProjects/oup/xtraje6newwcav2.txt',"r")
#sx,sy=[],[]
#for ks in files:
# rows=ks.split()
# sx.append(float(rows[0]))
# sy.append(float(rows[1]))
#sax=np.array(sx)
#say=np.array(sy)
#sax2=np.zeros(length)
#say2=np.zeros(length)
#for l in range(0,length):
# sax2[l]=sax[l]
# say2[l]=say[l]
#plt.figure()
#plt.xlabel('time')
#plt.ylabel('position')
#plt.xlim(0,10)
#plt.plot(ax,ay)
#plt.plot(ax,aa)
#plt.savefig('oub.pdf')
#ys = fft(ay)
#for l in range(0,length):
# S[l]=abs(ys[l])*abs(ys[l])/T
#omega=np.arange(0,length)*2*np.pi/T
plt.figure()
plt.xlabel('bias current I $[\mu A/cm^2]$')
plt.ylabel('SNR')
t=np.arange(-0.1,0.3,0.01)
xs=np.arange(-16.2,-9,0.8)
xsh=np.arange(-17.2,-9.2,0.8)
plt.yscale('log')
#plt.xscale('log')
#plt.xlim(4*10**(-3),5*10**3)
plt.ylim(10**(-8),10**(-3))
colorv=['y','g','b','r','c']
for n in range(0,l):
plt.plot(xsh,snrmeas(drdr[n,:],f)/vec[n,:],colorv[n],label='D=%.2f' %(Dtot[n]/10))
for n in range(0,l):
plt.plot(xs,abs((SNR[n,0:9]-1)/scale[n,0:9]),colorv[n]+'o')
#plt.plot([0.163, 0.163], [2*10**(-5), 6*10**(-2)], color='black', linestyle='-')
#plt.plot([-0.02, -0.02], [2*10**(-5), 6*10**(-2)], color='black', linestyle='-',label='$I_{crit}$')
#plt.plot(xs,SNR[2,:],label='D=3')
#plt.plot(xs,SNR[1,:],label='D=2.5')
#handles, labels = plt.gca().get_legend_handles_labels()
#order = [0,2,1]
#plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
#plt.plot(sax2,say2/T2,label='e6')
plt.legend()
plt.savefig('snrangerealrinzelcomplong.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
col,colx=[],[]
for y in range(1,11):
file=open('/home/richard/outhome/dgl%d.txt' % (y),"r")
for k in file:
row=k.split()
col.append(float(row[1]))
colx.append(float(row[0]))
cola=np.array(col)
colxa=np.array(colx)
plt.xlabel('gating variable $g_L$')
plt.ylabel('$D_{eff}$')
plt.yscale('log')
plt.plot(colxa,cola)
plt.savefig('dneurglvar.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
t=np.arange(-70,-30,0.001)
vnc=65/(2*(t+80))-20/((1+np.exp((-80-t)/(-12)))*2)
nnc=1/(1+np.exp((-40-t)/5))
plt.figure()
plt.xlabel('membrane voltage V')
plt.ylabel('gating variable n')
plt.plot(t,vnc,label='v-nullcline')
plt.plot(t,nnc,label='n-nullcline')
plt.legend()
plt.savefig('ikikirnc.pdf')
<file_sep>#!usr/bin/python3
import matplotlib
matplotlib.use("agg")
import numpy as np
import matplotlib.pyplot as plt
file=open('/home/richard/mastergit/NetBeansProjects/realbursting/countI2.txt',"r")
x,y=[],[]
for k in file:
row=k.split()
x.append(float(row[0]))
y.append(float(row[1]))
ax=np.array(x)
ay=np.array(y)
#az=40*np.array(z)-65
#aa=-np.array(a)
#area=(np.sum(ay)-min(ay)*points)*0.003/360
plt.figure()
plt.xlabel('time')
plt.ylabel('membrane voltage')
plt.xlim(200000,250000)
plt.plot(ax,ay)
#plt.plot(ax,az)
#plt.plot(ax,aa)
plt.legend()
plt.savefig('realburst2.pdf')
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: richard
*
* Created on January 17, 2019, 12:14 AM
*/
#include <cstdlib>
#include <random>
#include <cmath>
#include <fstream>
#include <ios>
#include <iomanip>
#include <fftw3.h>
#include <math.h>
#include <complex>
#define REAL 0
#define IMAG 1
void fft(fftw_complex *in, fftw_complex *out, int N)
{
// create a DFT plan
fftw_plan plan = fftw_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
// execute the plan
fftw_execute(plan);
// do some cleaning
fftw_destroy_plan(plan);
fftw_cleanup();
}
double average(double x[],int n);
void square(long long int x[],int n);
double ninf(double V, double k, double Vh);
void initd(double x[],int n);
int main(int argc, char** argv) {
double d=atof(argv[1]);
double D=d*0.01;
double nr=atof(argv[2]);
double I=-0.1+0.02*nr;
std::ostringstream d_convert;
std::ostringstream nr_convert;
d_convert << d;
nr_convert << nr;
std:: string date="realfast11jjem2st";
std:: string d_str = d_convert.str();
std:: string nr_str = nr_convert.str();
std:: string filenamef="f"+date+d_str+nr_str+".txt";
std:: string filenamed="d"+date+d_str+nr_str+".txt";
std:: string filenameg="g"+date+d_str+nr_str+".txt";
std:: string filenametime="time"+date+d_str+nr_str+".txt";
std:: string filenametimenew="timenew"+date+d_str+nr_str+".txt";
std:: string filenameparam="param"+date+d_str+nr_str+".txt";
std:: string filenameft="ft"+date+d_str+nr_str+".txt";
std:: string filenamesp="spike"+date+d_str+nr_str+".txt";
std::ofstream myfile;
std::ofstream myfile2;
std::ofstream myfile3;
std::ofstream myfile4;
std::ofstream myfile5;
std::ofstream myfile6;
std::ofstream myfile7;
std::ofstream myfile8;
myfile.open (filenamed);
myfile2.open (filenameg);
myfile3.open (filenamef);
myfile4.open (filenametime);
myfile5.open (filenametimenew);
myfile6.open (filenameparam);
myfile7.open (filenameft);
myfile8.open (filenamesp);
std::random_device rd;
std::mt19937_64 gen(rd());
std::normal_distribution<> n(0,1);
const double pi = 3.14159265358979323846;
std::uniform_real_distribution<> dis(0, 2*pi);
//double I0=-1; // 0
//double dI=0.2;
double gL=0.3; // 8
double EL=-80; // -80
double gNa=1; // 20
double ENa=60; // 60
double gK=0.4; // 9
double EK=-90; // -90
double gM=5; // 5
//Na current
double km=14; // 15
double vm=-18; // -20
//fast K+ current
double kn=5; // 5
double vn=-25; // -20
double tau=3; // 0.152
int N=120000000; //12*10⁷
int Neq=20000000; //2*10⁷
int points=100000;
int timepoints=10000;
int j;
double dt=0.0005;//0.01;
//int spikes=100;
//double* spike=new double[spikes];
double th,thn;
int runs=500; //250
int repetitions=20; // 20
int sampling=((N-Neq)/points)*repetitions;
double epsilon=0.01;//0.001
double omega=0.001;
int fpoints=1000000;
int fsampling=((N-Neq)/fpoints)*repetitions;
double Tf=(N-Neq)*repetitions*dt;
double dtint=fsampling*dt;
double deltapeak=1/dtint;
double *sqout=new double[fpoints];
int spikecount;
double *spikeout=new double[fpoints];
initd(sqout,fpoints);
int q;
double tf,phi;
//fftw_complex in[points], out[points];
fftw_complex* in = new fftw_complex[fpoints];
fftw_complex* out = new fftw_complex[fpoints];
fftw_complex* inspike = new fftw_complex[fpoints];
fftw_complex* outspike = new fftw_complex[fpoints];
// simulate equilibrium point
int Nsim=5000000;
double vsim,nfsim,nfsims,vsims,neq,veq;
nfsims=0.4;
vsims=-70;
for(int jsim=0;jsim<Nsim;jsim++){
vsim=I*dt+vsims-gL*(vsims-EL)*dt-gNa*ninf(vsims,km,vm)*(vsims-ENa)*dt-gK*nfsims*(vsims-EK)*dt;
nfsim=nfsims+(ninf(vsims,kn,vn)-nfsims)*dt/tau;
vsims=vsim;
nfsims=nfsim;
}
veq=vsims;
neq=nfsims;
//simulate instable focus
int Nfoc=20000000;
double dtfoc,vfoc,nffoc,nffocs,vfocs;
dtfoc=-dt;
nffocs=0.5;
vfocs=-25;
for(int jfoc=0;jfoc<Nfoc;jfoc++){
vfoc=I*dtfoc+vfocs-gL*(vfocs-EL)*dtfoc-gNa*ninf(vfocs,km,vm)*(vfocs-ENa)*dtfoc-gK*nffocs*(vfocs-EK)*dtfoc;
nffoc=nffocs+(ninf(vfocs,kn,vn)-nffocs)*dtfoc/tau;
vfocs=vfoc;
nffocs=nffoc;
}
if(vfocs<=0 && vfocs >=-100 && nffocs <= 1 && nffocs >=0){
th=vfocs;
thn=nffocs;
}
else{
th=-25;
thn=0.7;
}
long long int count;
double Nav,Nava,Nava2,Navaalt[points],N2av[points],N2ava,T;
double mx,nx,nx2,v,nf,nfs,vs,Deff,vav,vavalt,sigmav,Fano,Navz[points],sqNavz[points],state[timepoints],state2[timepoints];
int avalue[timepoints],avalue2[timepoints],lasta,tvcount,j2value[timepoints],j2value2[timepoints],lastj2,jrvalue[timepoints],jrvalue2[timepoints],lastjr;
avalue[0]=0;
j2value[0]=0;
jrvalue[0]=0;
avalue2[0]=0;
j2value2[0]=0;
jrvalue2[0]=0;
lasta=0;lastjr=0;lastj2=0;tvcount=0;
initd(Navz,points);
initd(N2av,points);
initd(Navaalt,points);
int bv,bv2,lastbv,lastbv2,sv,svlocked,t,t2,p,qvar,pvar;
Nava=0;Nava2=0;sv=0;t=0;t2=0;nfs=0;vs=0;svlocked=0;
mx=0.0309-0.0047*I;
nx=1.714+0.01*I;
nx2=mx*63;
for(int a=0;a<runs;a++){
for(j=0;j<Neq;j++){
tf=dt*a*Neq+j*dt;
v=I*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt+sqrt(2*D*dt)*n(gen)+epsilon*cos(2*pi*omega*tf+phi)*dt;
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
vs=v;
nfs=nf;
}
}
if(nfs>mx*vs+nx2){
bv=0;
bv2=0;
}
else{
bv=1;
bv2=1;
}
state[0]=bv;state2[0]=bv2;lastbv=bv;lastbv2=bv2;
for(int a=0;a<runs;a++){
count=0;
spikecount=0;
q=0;
qvar=0;
p=0;
pvar=0;
phi=dis(gen);
for(int jr=0;jr<repetitions;jr++){
for(int j2=0;j2<N-Neq;j2++){
tvcount=tvcount+1;
pvar=pvar+1;
qvar=qvar+1;
tf=dt*(N-Neq)*(a*repetitions+jr)+dt*j2;
v=I*dt+vs-gL*(vs-EL)*dt-gNa*ninf(vs,km,vm)*(vs-ENa)*dt-gK*nfs*(vs-EK)*dt+sqrt(2*D*dt)*n(gen)+epsilon*cos(2*pi*omega*tf+phi)*dt;
nf=nfs+(ninf(vs,kn,vn)-nfs)*dt/tau;
if(v > th && vs < th){
sv=1;
}
if(sv==1 && nf > thn && nfs < thn){
count=count+1;
sv=0;
bv2=1;
svlocked=0;
lasta=a;
lastjr=jr;
lastj2=j2;
}
if(bv2==1 && v<veq+5 && nf<neq+0.1){
if(svlocked==0){
if(v < veq && vs > veq){
svlocked=1;
}}
if(svlocked==0){
if(nf < neq && nfs > neq){
svlocked=-1;
}
}
if(svlocked==1){
if(nf < neq && nfs > neq){
bv2=0;
svlocked=2;
}
}
if(svlocked==-1){
if(v < veq && vs > veq){
bv2=0;
svlocked=2;
}
}
}
if((bv==1 && nf>mx*v+nx2) || (bv==1 && (((a-lasta)*repetitions+(jr-lastjr))*dt*(N-Neq)+(j2-lastj2)*dt)>20)){
bv=0;
}
if(bv==0 && nf<mx*v+nx){
bv=1;
}
if(tvcount==40000){
tvcount=0;
if((t<timepoints) && (0.5<bv+lastbv) && (1.5>bv+lastbv)){
state[t]=bv;
avalue[t]=a;
jrvalue[t]=jr;
j2value[t]=j2;
t=t+1;
}
lastbv=bv;
}
if((t2<timepoints) && (0.5<bv2+lastbv2) && (1.5>bv2+lastbv2)){
state2[t2]=bv2;
avalue2[t2]=a;
jrvalue2[t2]=jr;
j2value2[t2]=j2;
t2=t2+1;
lastbv2=bv2;
}
vs=v;
nfs=nf;
T=2*(jr*dt*(N-Neq)+j2*dt)+dt;
if(pvar==sampling){
Navaalt[p]=(a*Navaalt[p]+2*count/T)/(a+1);
Navz[p]=(a*Navz[p]+count/sqrt(T))/(a+1);
N2av[p]=(N2av[p]*a+(count*count)/T)/(a+1);
p=p+1;
pvar=0;
}
if(qvar==fsampling){
qvar=0;
in[q][REAL]=v;
in[q][IMAG]=0;
if(count>spikecount+0.5){
inspike[q][REAL]=deltapeak*(count-spikecount);
inspike[q][IMAG]=0;
spikecount=count;
}
else{
inspike[q][REAL]=0;
inspike[q][IMAG]=0;
}
q=q+1;
}
}
}
Nava=(a*Nava+2*count/T)/(a+1);
Nava2=(a*Nava2+(2*count/T)*(2*count/T))/(a+1);
fft(in, out,fpoints);
for(int ind=0;ind<fpoints;ind++){
sqout[ind]=(a*sqout[ind]+(out[ind][REAL]*out[ind][REAL]+out[ind][IMAG]*out[ind][IMAG])*dtint*dtint)/(a+1);
}
fft(inspike, outspike,fpoints);
for(int ind=0;ind<fpoints;ind++){
spikeout[ind]=(a*spikeout[ind]+(outspike[ind][REAL]*outspike[ind][REAL]+outspike[ind][IMAG]*outspike[ind][IMAG])*dtint*dtint)/(a+1);
}
}
for(int qua=0;qua<points;qua++){
sqNavz[qua]=Navz[qua]*Navz[qua];
}
N2ava=average(N2av,points);
Nav=average(sqNavz,points);
Deff=(N2ava-Nav);
vav=Nava;
vavalt=average(Navaalt,points);
sigmav=(Nava2-Nava*Nava);
Fano=2*Deff/vav;
//}
myfile << I << " " << Deff << "\n";
myfile.close();
myfile2 << I << " " << vav << " " << vavalt << " "<< sigmav << "\n";
myfile2.close();
myfile3 << I << " " << Fano << "\n";
myfile3.close();
for(int rv=0;rv<timepoints;rv++){
myfile4 << avalue[rv] << " " << jrvalue[rv] << " " << j2value[rv] <<" " <<state[rv] << "\n";
}
myfile4.close();
for(int rv=0;rv<timepoints;rv++){
myfile5 << avalue2[rv] << " " << jrvalue2[rv] << " " << j2value2[rv] <<" " <<state2[rv] << "\n";
}
myfile5.close();
myfile6 << "N" << " " << "Neq" << " " << "dt" <<" " << "runs" << " "<< "repetitions" << " " << "neq" << " " << "veq" << " "<< "thn" << " " << "th" << " "<< "epsilon" << " " << "omega" << "\n";
myfile6 << N <<" " << Neq << " "<< dt << " " << runs << " " << repetitions << " " << neq << " " << veq << " " << thn << " " << th << " "<< epsilon << " "<< omega << "\n";
myfile6.close();
for(int rv=0;rv<fpoints;rv++){
myfile7 << rv/Tf << " " << sqout[rv] <<"\n";
}
myfile7.close();
for(int rv2=0;rv2<fpoints;rv2++){
myfile8 << rv2/Tf << " " << spikeout[rv2] <<"\n";
}
myfile8.close();
delete [] in;
delete [] out;
delete [] sqout;
delete [] inspike;
delete [] outspike;
delete [] spikeout;
return 0;
}
double ninf(double V, double k, double Vh){
double f=1/(1+exp((Vh-V)/k));
return f;
}
double average(double x[],int n){
int i;
double sum=0;
int e2=0;
for(i=0;i<n;i++){
sum=(sum*e2+x[i])/(e2+1);
e2=e2+1;
}
return sum;
}
void square(long long int x[],int n){
int j;
for(j=0;j<n;j++){
x[j]=x[j]*x[j];
}
}
void initd(double x[],int n){
for(int k2=0;k2<n;k2++){
x[k2]=0;
}
}
| 54c95eb01f63d349b4ff24ee8674cb302f1dd4e3 | [
"Python",
"Makefile",
"C++"
]
| 140 | Python | RichardKul/thesis | 88217953f416bbe3c7c7616179755c83de416592 | 4b77129fe9ab87fda0a346dbfa0aa4053a628e39 |
refs/heads/master | <repo_name>uehara1414/ansible-subprocess<file_sep>/tests/playbook_test.py
import unittest
from ansible_subprocess.main import construct_playbook_command
class CommandTest(unittest.TestCase):
def test_construct_playbook_command(self):
command = construct_playbook_command('tests/playbooks/simple-playbook.yml', ['127.0.0.1'])
self.assertEqual(
command,
[
'ansible-playbook',
'tests/playbooks/simple-playbook.yml',
'-i',
'127.0.0.1,'
]
)
def test_construct_playbook_command_with_host_name(self):
command = construct_playbook_command('tests/playbooks/simple-playbook.yml', 'hosts')
self.assertEqual(
command,
[
'ansible-playbook',
'tests/playbooks/simple-playbook.yml',
'-i',
'hosts'
]
)
def test_construct_playbook_command_with_specific_ansible_command(self):
command = construct_playbook_command('tests/playbooks/simple-playbook.yml', ['127.0.0.1'], playbook_command='/bin/ansible-playbook')
self.assertEqual(
command,
[
'/bin/ansible-playbook',
'tests/playbooks/simple-playbook.yml',
'-i',
'127.0.0.1,'
]
)
def test_construct_playbook_command_with_two_hosts(self):
command = construct_playbook_command('tests/playbooks/simple-playbook.yml', ['127.0.0.1', '127.0.0.2'])
self.assertEqual(
command,
[
'ansible-playbook',
'tests/playbooks/simple-playbook.yml',
'-i',
'127.0.0.1,127.0.0.2,'
]
)
def test_construct_playbook_command_with_extra_vars(self):
command = construct_playbook_command('tests/playbooks/simple-playbook.yml', ['127.0.0.1', '127.0.0.2'], extra_vars={"extra1": "var1", "extra2": "var2"})
print(command)
self.assertEqual(
command,
[
'ansible-playbook',
'tests/playbooks/simple-playbook.yml',
'-i',
'127.0.0.1,127.0.0.2,',
'--extra-vars',
'"extra1=var1 extra2=var2"'
]
)
def test_construct_playbook_command_with_private_key(self):
command = construct_playbook_command('tests/playbooks/simple-playbook.yml', ['127.0.0.1'], private_key='/home/foo/id_rsa')
self.assertEqual(
command,
[
'ansible-playbook',
'tests/playbooks/simple-playbook.yml',
'-i',
'127.0.0.1,',
'--private-key=/home/foo/id_rsa'
]
)
def test_construct_playbook_command_with_extra_options(self):
command = construct_playbook_command('tests/playbooks/simple-playbook.yml', ['127.0.0.1'], private_key='/home/foo/id_rsa', extra_options='--syntax-check')
self.assertEqual(
command,
[
'ansible-playbook',
'tests/playbooks/simple-playbook.yml',
'-i',
'127.0.0.1,',
'--private-key=/home/foo/id_rsa',
'--syntax-check'
]
)
<file_sep>/setup.py
import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.md"):
longDesc = open("README.md").read().strip()
setup(
name="ansible-subprocess",
version="0.3.0",
author="uehara1414",
author_email="",
description=("Using Ansible from python subprocess."),
long_description=longDesc,
license="MIT License",
keywords="python Ansible subprocess",
url="https://github.com/uehara1414/ansible-subprocess",
packages=['ansible_subprocess'],
package_dir={'ansible_subprocess': 'ansible_subprocess'},
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3',
]
)
<file_sep>/ansible_subprocess/main.py
import subprocess
def run_playbook(playbook_filename, hosts, playbook_command='ansible-playbook', private_key=None, extra_options=None, extra_vars=None):
command = construct_playbook_command(playbook_filename, hosts, playbook_command=playbook_command, private_key=private_key,extra_options=extra_options, extra_vars=extra_vars)
process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return (process.wait(), process.stdout.read(), process.stderr.read())
def get_hosts_str(hosts):
if isinstance(hosts, list):
hosts = ",".join(hosts) + ","
if not isinstance(hosts, str):
raise TypeError('hosts must be a str or list object')
return hosts
def construct_playbook_command(playbook_filename, hosts, playbook_command='ansible-playbook', private_key=None, extra_options=None, extra_vars=None):
hosts = get_hosts_str(hosts)
command = [
playbook_command,
playbook_filename,
'-i',
hosts,
]
if private_key:
command.append('--private-key={}'.format(private_key))
if extra_vars:
vars = '"' + ' '.join("{}={}".format(key, value) for (key, value) in sorted(extra_vars.items())) + '"'
command += ['--extra-vars', vars]
if not extra_options:
return command
if isinstance(extra_options, str):
command.append(extra_options)
elif isinstance(extra_options, list):
command += extra_options
else:
raise TypeError("extra_options must be str or list.")
return command
def run_ping(host, ansible_command='ansible'):
command = construct_ping_command(host, ansible_command=ansible_command)
process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return (process.wait(), process.stdout.read(), process.stderr.read())
def construct_ping_command(host, ansible_command='ansible'):
host = get_hosts_str(host)
command = [
ansible_command,
'all',
'-i',
host,
'-m',
'ping'
]
return command
<file_sep>/tests/general_test.py
import unittest
class GenericTest(unittest.TestCase):
def test_import(self):
import ansible_subprocess
def test_accessible(self):
import ansible_subprocess
ansible_subprocess.run_playbook
ansible_subprocess.run_ping
<file_sep>/README.md
# ansible-subprocess
[](https://travis-ci.org/uehara1414/ansible-subprocess)
[Not maintained!]ansible-subprocess run Ansible dynamically via the subprocess module.
## Demo
```python
from ansible_subprocess import run_playbook, run_ping
status, stdout, stderr = run_playbook('playbooks/sample.yml', 'web')
status, stdout, stderr = run_playbook('playbooks/sample2.yml',
['127.0.0.1', '127.0.0.2'],
extra_vars={'var1': 'hoge', 'var2': 'fuga'},
extra_options=['--syntax-check'])
status, stdout, stderr = run_ping(['8.8.8.8'])
```
## Installation
```bash
pip install ansible-subprocess
```
## License
[MIT](https://github.com/uehara1414/ansible-subprocess/blob/master/LICENSE)
<file_sep>/tests/ping_test.py
import unittest
from ansible_subprocess.main import construct_ping_command, run_ping
class PingCommandTest(unittest.TestCase):
def test_construct_ping_command(self):
command = construct_ping_command('8.8.8.8')
self.assertEqual(
command,
[
'ansible',
'all',
'8.8.8.8',
'-m',
'ping'
]
)
def test_construct_ping_command_with_specific_ansible_command(self):
command = construct_ping_command('8.8.8.8', ansible_command='/bin/ansible')
self.assertEqual(
command,
[
'/bin/ansible',
'all',
'8.8.8.8',
'-m',
'ping'
]
)
<file_sep>/ansible_subprocess/__init__.py
from .main import run_playbook, run_ping | d5e713903266f2748501d614653168f40616667b | [
"Markdown",
"Python"
]
| 7 | Python | uehara1414/ansible-subprocess | 0333166b35a718281925e428947e90891104ab7d | 9e77c657d4e93624428838f9780211410bb9aa9d |
refs/heads/master | <file_sep>import Info from './info'
import UpdatePassword from './updatePassword'
export {
Info,
UpdatePassword
}<file_sep>const staticHost2ApiHost = () => {
var mHost = window.location.hostname
return {
'localhost':'https://symy.powerionics.cn',
'symy.powerionics.cn':'https://symy.powerionics.cn',
'www.powerionics.vip':'https://www.powerionics.vip'
}[mHost] || 'https://www.powerionics.vip'
}
const config = {
server: staticHost2ApiHost(),
appType:1
}
export default config<file_sep>import userAction from './user'
import menuAction from './menu'
export default {
...userAction,
...menuAction,
}<file_sep>export default {
setUser(data) {
console.log(data)
return {
type: 'SET_USER',
payload:{
data
}
}
}
}<file_sep>/**
*请保证一级菜单key和路径同名
*/
import Index from '../views/index'
import Login from '../views/user/login'
import NotFound from '../views/common/404'
import Signup from '../views/user/signup'
/**
* 首页 数据中心
*/
import dataCenter from '../views/dataCenter/dataCenter'
//编辑
import editor from '../views/editor/editor'
/**
* 用户中心
*/
import UserCenter from '../views/user/center'
//账号管理
import userControl from '../views/control/user/userControl'
const staticRoutes = [{
path: '/login',
component: Login,
menu: false
}, {
path: '/signup',
component: Signup,
menu: false
}, {
path: '/404',
component: NotFound,
menu: false
}, {
path: '/',
component: Index,
key: 'index',
redirect:'/dataCenter'
}]
const asyncRoutes = [{
path: '/dataCenter',
component: dataCenter,
menu: true,
key: 'data_center',
meta: {
title: '数据中心',
icon: 'database'
}
},{
path: '/editor',
component: editor,
menu: true,
key: 'editor',
meta: {
title: '编辑设计',
icon: 'block'
}
},{
path: "/user",
component: UserCenter,
menu: true,
key: "personal_center",
meta: {
title: "个人中心",
icon: "user"
}
},{
path: "/userControl",
component: userControl,
menu: true,
key: "user_control",
meta: {
title: "账号管理",
icon: "user-add"
}
}, ]
let routes = staticRoutes.concat(asyncRoutes)
export default routes;<file_sep>import React, { Component } from 'react';
import { Form, Button, Input } from 'antd';
import PicturesWall from '@/components/imageUpload'
import '../styles/form.scss'
const FormItem = Form.Item;
class Module extends Component {
constructor() {
super()
this.state = {
}
}
handleSubmit(e) {
if (this.props.disabled) {
this.props.onEdit()
} else {
e && e.preventDefault();
this.props.form.validateFields((err, data) => {
if (err) return;
//数据校验通过后,传递到上级提交
data.src = this.state.fileList && this.state.fileList.length>0?(this.state.fileList[0].url?this.state.fileList[0].url:'http://www.baidu.com/img/baidu_jgylogo3.gif'):''
this.props.onSubmit(data)
});
}
}
componentWillMount() {
let { src } = this.props.formData
let fileList = []
fileList.push({
uid: '-1',
status: 'done',
url: src
})
this.setState({
fileList
})
}
handleUpload = (fileList) => {
fileList.splice(0,fileList.length-1)
this.setState({
fileList
})
}
render() {
let {
name,
mobile,
} = this.props.formData;
let { fileList } = this.state
let { disabled } = this.props
const { getFieldDecorator } = this.props.form;
const formItemLayout = {
labelCol: {
span: 4
},
wrapperCol: {
span: 20
},
};
return (
<div className="_form-wrap">
<Form labelalign="left" {...formItemLayout} onSubmit={this.handleSubmit.bind(this)} >
<FormItem label="联系电话">
{
getFieldDecorator('mobile', {
initialValue: mobile
})(
<Input type="phone" disabled={disabled}></Input>
)
}
</FormItem>
<FormItem label="名称">
{
getFieldDecorator('name', {
initialValue: name,
})(
<Input disabled={disabled}></Input>
)
}
</FormItem>
<FormItem label="相关资料">
{
getFieldDecorator('src', {
initialValue: '',
})(
<PicturesWall disabled={disabled} fileList={fileList} change={this.handleUpload} />
)
}
</FormItem>
<FormItem label=" " colon={false}>
<div className="btn-wrap">
<Button type="primary" onClick={this.handleSubmit.bind(this)}>{disabled ? '编辑' : '保存'}</Button>
<Button type="danger" onClick={this.props.onDelete}>删除</Button>
</div>
</FormItem>
</Form>
</div >
)
}
}
const ThisForm = Form.create({
onValuesChange: (props, changedValues, allValues) => {
// if (!props.canSave) {
// props.setCanSave(true)
// }
}
})(Module);
export default ThisForm<file_sep>/**
* 设置根元素字体
*/
const setHtmlFonts = () => {
var deviceWidth = document.documentElement.clientWidth || document.body.clientWidth;
if (deviceWidth > 640) deviceWidth = 640;
document.documentElement.style.fontSize = deviceWidth / 7.5 + 'px';
}
/**
* 展开注册路由
* @param {*} routesArray
* @param {*} parent
* @param {*} routes
*/
const extendRoutes = (routesArray, parent = '', routes = []) => {
for (let i in routesArray) {
let parentPath = ""
if (routesArray[i].children) {
parentPath += routesArray[i].path
extendRoutes(routesArray[i].children, parentPath, routes)
}
routes.push({
path: parent + routesArray[i].path,
component: routesArray[i].component
})
}
return routes
}
/**
* 获取queryString
* @param {*} name
*/
const getQueryString = (name, search) => {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var r = search.substr(1).match(reg);
if (r != null) return (r[2]);
return null;
}
/**
* 获取queryString 对象
* @param {*} objStr //?id=1&name=1
*/
const getQueryObject = (objStr) => {
let obj = {};
if (objStr) {
objStr.slice(1).split('&').forEach(item => {
let arr = item.split('=');
obj[arr[0]] = arr[1]
})
}
return obj;
}
/**
* 组装queryString
* @param {*} queryObj
* @param {*} hash
*/
const makeQueryString = (queryObj, hash = '') => {
let queryString = ''
for (let item in queryObj) {
if (queryObj[item]) {
queryString += `${item}=${queryObj[item]}&`
}
}
queryString = "?" + queryString.replace(/(&*$)/g, "") + hash
return queryString
}
/**
* 本地储存
* @param {*} key
* @param {*} value
*/
const setLocal = (key, value) => {
return window.localStorage.setItem(key, value)
}
/**
* 获取本地储存
* @param {*} key
*/
const getLocal = (key) => {
return window.localStorage.getItem(key)
}
/**
* 移除某个本地储存
* @param {*} key
*/
const removeLocal = (key) => {
return window.localStorage.removeItem(key)
}
/**
* 设置cookie
* @param {*} name
* @param {*} value
* @param {*} domain
* @param {*} path
*/
const setCookie = (name, value, domain, path) => {
var expire = new Date();
var hour = 24;
if (hour) {
expire.setTime(expire.getTime() + 3600000 * hour);
}
document.cookie = name + "=" + value + "; " + (hour ? ("expires=" + expire.toGMTString() + "; ") : "") + (path ? ("path=" + path + "; ") : "path=/; ") + (domain ? ("domain=" + domain + ";") : ("domain=" + document.location.hostname + ";"));
return true;
}
/**
* 获取cookie
* @param {*} name
*/
const getCookie = (name) => {
var r = new RegExp("(?:^|;+|\\s+)" + name + "=([^;]*)"),
m = document.cookie.match(r);
return (!m ? "" : m[1]);
}
/**
* 删除cookie
* @param {*} name
* @param {*} domain
* @param {*} path
*/
const delCookie = (name, domain, path) => {
document.cookie = name + "=; expires=Mon, 26 Jul 1997 05:00:00 GMT; " + (path ? ("path=" + path + "; ") : "path=/; ") + (domain ? ("domain=" + domain + ";") : ("domain=" + document.location.hostname + ";"));
}
/**
* 格式化节点树
* @param {*} children
* @param {*} options
*/
const formatTree = (children, options = []) => {
for (let i in children) {
let child = {}
if (children[i].children) {
let innerChildren = []
formatTree(children[i].children, innerChildren)
child.children = innerChildren
}
child.label = children[i].name
child.value = children[i].id
options.push(child)
}
return options
}
/**
* 展开节点keys
* @param {*} children
* @param {*} keys
*/
const extendsNodeKeys = (children, keys = []) => {
for (let i in children) {
keys.push(children[i].id)
if (children[i].children) {
extendsNodeKeys(children[i].children, keys)
}
}
return keys
}
/**
* 路由鉴权
* @param {*} accessRouter 服务端返回的可用菜单
* @param {*} localRouter 本地注册的菜单
*/
const filteRouter = (accessRouter, localRouter) => {
let extendsTree = (treeArray = [], menuKey = []) => {
treeArray.forEach(item => {
menuKey.push(item.text)
if (item.children && item.children.length > 0) {
extendsTree(item.children, menuKey)
}
})
return menuKey
}
let accessKeys = extendsTree(accessRouter)
let filteTree = (localTree = [], newTree = []) => {
localTree.forEach(item => {
if (accessKeys.indexOf(item.key) >= 0) {
if (item.children && item.children.length > 0) {
filteTree(item.children)
}
newTree.push(item)
}
})
return newTree
}
return filteTree(localRouter)
}
/**
* 检查数组的某一项全为真
* @param {*} array
* @param {*} key
* @param {*} value
*/
const checkValuesAllTrue = (array, key, value) => {
let result = true
if (array instanceof Array && array.length > 0) {
array.forEach(item => {
if (item[key] !== value) result = false;
})
}
return result
}
const parseTime = (time, fmt = 'YYYY-MM-DD HH:mm:ss') => {
let date = time;
if (typeof time != "object") {
date = new Date(time)
}
var o = {
'M+': date.getMonth() + 1,
'D+': date.getDate(),
'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
'H+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
'q+': Math.floor((date.getMonth() + 3) / 3),
'S': date.getMilliseconds()
}
var week = {
'0': '\u65e5',
'1': '\u4e00',
'2': '\u4e8c',
'3': '\u4e09',
'4': '\u56db',
'5': '\u4e94',
'6': '\u516d'
}
if (/(Y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
if (/(E+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
}
return fmt
}
/**
* 获取路由key
* @param {*} pathname
*/
const getRouterKey = (pathname, routers) => {
let pathKey = ''
for (let i in routers) {
if (routers[i].path === pathname) {
pathKey = routers[i].key
}
}
return pathKey
}
/**
* 输入某行数据
* @param {*} array
* @param {*} num
* @param {*} name
* @param {*} value
*/
const setArrayItem = (array, num, name, value) => {
for (let i in array) {
if (array[i].num === num) {
array[i][name] = value
}
}
return array;
}
//随机字符串(字母/数字/特殊符号)
const randomWord = (randomFlag = true, min = 6, max = 12) => {
let str = "",
range = min,
arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'-', '.', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', ':', '<', '>', '?'
];
if (randomFlag) {
range = Math.round(Math.random() * (max - min)) + min; // 任意长度
}
for (let i = 0; i < range; i++) {
let pos = Math.round(Math.random() * (arr.length - 1));
str += arr[pos];
}
return str;
}
/**
* 删除数组某项
* @param {array} table
* @param {string} id
*/
const deleteTableItem = (table, num) => {
for (let i in table) {
if (table[i].num === num) {
table.splice(i, 1)
}
}
for (let i = 0; i < table.length; i++) {
table[i].num = i + 1
}
return table
}
/**
* 倒计时
* @param {*} time
* @param {*} cb
*/
const countDown = (time, cb) => {
var timer = null
function _countDown() {
if (time > 0) {
cb(time--)
} else {
clearInterval(timer)
cb(0)
}
}
timer = setInterval(_countDown, 1000);
}
/**
* 节流函数
* @param {*} func
* @param {*} wait
* @param {*} options
*/
const throttle = (func, wait, options) => {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function () {
previous = options.leading === false ? 0 : new Date().getTime();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function () {
var now = new Date().getTime();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
/**
* 页面按钮权限
* @param {*} buttonKeys
* @param {*} key
*/
const buttonAuth = (buttonKeys, key, ele) => {
let results = null;
if (buttonKeys.indexOf(key) >= 0) {
results = ele
}
return results
}
const filterMenu = (asyncRoutes) => {
// let menus = JSON.parse(getLocal('menus')) || []
// let routes = []
// let menukey = menus.map(item => item.key)
// for (let i in asyncRoutes) {
// if (!asyncRoutes[i].menu) {
// routes.push(asyncRoutes[i])
// } else {
// if (menukey.indexOf(asyncRoutes[i].key) >= 0) {
// routes.push(asyncRoutes[i])
// }
// }
// }
// return routes
return asyncRoutes
}
const getBase64 = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
export {
setHtmlFonts,
extendRoutes,
getQueryString,
getQueryObject,
makeQueryString,
setLocal,
getLocal,
removeLocal,
setCookie,
getCookie,
delCookie,
formatTree,
extendsNodeKeys,
filteRouter,
checkValuesAllTrue,
parseTime,
getRouterKey,
setArrayItem,
randomWord,
deleteTableItem,
countDown,
throttle,
buttonAuth,
filterMenu,
getBase64
}<file_sep>import React from 'react'
import { message, Icon } from 'antd'
import '../assets/styles/imageviewer.scss'
export default class ImgPreview extends React.Component {
constructor(props) {
super(props)
this.state = {
imgArr: [],
imgIndex: 0,
screenHeight: 0,
screenWidth: 0,
ratio: 1,
angle: 0,
defaultWidth: 'auto',
defaultHeight: 'auto',
imgSrc: '',
posTop: 0,
posLeft: 0,
isAlwaysCenterZoom: false, // 是否总是中心缩放
isAlwaysShowRatioTips: false, // 是否总是显示缩放倍数信息,默认点击按钮缩放时才显示
flags: false,
isDraged: false,
position: {
x: 0,
y: 0
},
nx: '',
ny: '',
dx: '',
dy: '',
xPum: '',
yPum: ''
}
this.percent = 100
}
componentDidMount() {
this.setState({
screenWidth: window.screen.availWidth,
screenHeight: window.screen.availHeight,
ratio: 1,
angle: 0
}, () => {
// this.getImgSize()
})
}
componentWillReceiveProps(nextProps) {
this.setState({
imgIndex: nextProps.imgIndex,
imgArr: nextProps.imgArr,
// imgSrc: nextProps.imgSrc,
isAlwaysCenterZoom: nextProps.isAlwaysCenterZoom,
isAlwaysShowRatioTips: nextProps.isAlwaysShowRatioTips
})
}
// 获取预览图片的默认宽高和位置
getImgSize = () => {
let { ratio, isDraged, isAlwaysCenterZoom } = this.state
let {maxWidth,maxHeight} = this.props
let posTop = 0
let posLeft = 0
// 图片原始宽高
let originWidth = this.originImgEl ? this.originImgEl.width : 0
let originHeight = this.originImgEl ? this.originImgEl.height : 0
// 默认最大宽高540/320
let maxDefaultWidth = maxWidth?maxWidth:540
let maxDefaultHeight = maxHeight?maxHeight:320
// 默认展示宽高
let defaultWidth = 0
let defaultHeight = 0
if (originWidth > maxDefaultWidth || originHeight > maxDefaultHeight) {
if (originWidth / originHeight > maxDefaultWidth / maxDefaultHeight) {
defaultWidth = maxDefaultWidth
defaultHeight = Math.round(originHeight * (maxDefaultHeight / maxDefaultWidth))
posTop = (defaultHeight * ratio / 2) * -1
posLeft = (defaultWidth * ratio / 2) * -1
} else {
defaultWidth = Math.round(maxDefaultHeight * (originWidth / originHeight))
defaultHeight = maxDefaultHeight
posTop = (defaultHeight * ratio / 2) * -1
posLeft = (defaultWidth * ratio / 2) * -1
}
} else {
defaultWidth = originWidth
defaultHeight = originHeight
posTop = (defaultWidth * ratio / 2) * -1
posLeft = (defaultHeight * ratio / 2) * -1
}
if (isAlwaysCenterZoom) {
this.setState({
posTop: posTop,
posLeft: posLeft,
defaultWidth: defaultWidth * ratio,
defaultHeight: defaultHeight * ratio
})
} else {
// 若拖拽改变过位置,则在缩放操作时不改变当前位置
if (isDraged) {
this.setState({
defaultWidth: defaultWidth * ratio,
defaultHeight: defaultHeight * ratio
})
} else {
this.setState({
posTop: posTop,
posLeft: posLeft,
defaultWidth: defaultWidth * ratio,
defaultHeight: defaultHeight * ratio
})
}
}
}
// 下载
download = () => {
let src = this.state.imgArr[this.state.imgIndex][1];
var image = new Image()
// 解决跨域 Canvas 污染问题
image.setAttribute('crossOrigin', 'anonymous')
image.onload = function () {
var canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
var context = canvas.getContext('2d')
context.drawImage(image, 0, 0, image.width, image.height)
var url = canvas.toDataURL('image/png')
// 生成一个a元素
var a = document.createElement('a')
// 创建一个单击事件
var event = new MouseEvent('click')
// 将a的download属性设置为我们想要下载的图片名称,若name不存在则使用‘下载图片名称’作为默认名称
a.download = src.slice(src.lastIndexOf('/') + 1)
// 将生成的URL设置为a.href属性
a.href = url
// 触发a的单击事件
a.dispatchEvent(event)
}
image.src = src
}
// 放大
scaleBig = (type = 'click') => {
let { ratio, isAlwaysShowRatioTips } = this.state
ratio += 0.15
this.percent += 15
this.setState({
ratio: ratio
}, () => {
this.getImgSize()
})
if (isAlwaysShowRatioTips) {
message.info(`缩放比例:${this.percent}%`, 0.2)
} else {
if (type === 'click') {
message.info(`缩放比例:${this.percent}%`, 0.2)
}
}
}
// 缩小
scaleSmall = (type = 'click') => {
let { ratio, isAlwaysShowRatioTips } = this.state
ratio -= 0.15
if (ratio <= 0.1) {
ratio = 0.1
}
if (this.percent - 15 > 0) {
this.percent -= 15
}
this.setState({
ratio: ratio
}, () => {
this.getImgSize()
})
if (isAlwaysShowRatioTips) {
message.info(`缩放比例:${this.percent}%`, 0.2)
} else {
if (type === 'click') {
message.info(`缩放比例:${this.percent}%`, 0.2)
}
}
}
// 滚轮缩放
wheelScale = (e) => {
e.preventDefault()
if (e.deltaY > 0) {
this.scaleBig('wheel')
} else {
this.scaleSmall('wheel')
}
}
// 旋转
retate = () => {
let { angle } = this.state
angle += 90
this.setState({
angle: angle
})
}
// 按下获取当前数据
mouseDown = (event) => {
let touch
if (event.touches) {
touch = event.touches[0]
} else {
touch = event
}
let position = {
x: touch.clientX,
y: touch.clientY
}
this.setState({
flags: true,
position: position,
dx: this.originImgEl.offsetLeft,
dy: this.originImgEl.offsetTop
})
}
mouseMove = (event) => {
let { dx, dy, position, flags } = this.state
if (flags) {
event.preventDefault()
let touch
if (event.touches) {
touch = event.touches[0]
} else {
touch = event
}
this.setState({
isDraged: true,
nx: touch.clientX - position.x,
ny: touch.clientY - position.y,
xPum: dx + touch.clientX - position.x,
yPum: dy + touch.clientY - position.y
}, () => {
this.imgEl.style.left = this.state.xPum + 'px'
this.imgEl.style.top = this.state.yPum + 'px'
})
}
}
mouseUp = () => {
this.setState({
flags: false
})
}
mouseOut = () => {
this.setState({
flags: false
})
}
// 关闭预览
closePreview = () => {
let { onClose } = this.props
this.setState({
ratio: 1,
angle: 0,
defaultWidth: 'auto',
defaultHeight: 'auto',
imgSrc: '',
posTop: 0,
posLeft: 0,
flags: false,
isDraged: false,
position: {
x: 0,
y: 0
},
nx: '',
ny: '',
dx: '',
dy: '',
xPum: '',
yPum: ''
}, () => {
this.getImgSize()
this.percent = 100
typeof onClose == 'function' && onClose()
})
}
changePic(index) {
if (index == -1) {
//上一张
if (this.state.imgIndex <= 0) {
return;
}
// this.getImgSize();
this.setState({
angle: 0,
imgIndex: this.state.imgIndex - 1
})
} else {
//下一张
if (this.state.imgIndex >= this.state.imgArr.length - 1) {
return;
}
// this.getImgSize();
this.setState({
angle: 0,
imgIndex: this.state.imgIndex + 1
})
}
}
del = (e) => {
e.stopPropagation()
this.props.del(this.state.imgIndex)
}
render() {
const close_transform_style = {
transform: `translate(${this.state.defaultWidth / 2}px,${-this.state.defaultHeight / 2}px)`
}
let { screenWidth, screenHeight, posLeft, posTop, angle, imgArr, imgIndex } = this.state
let { visible,canDownload,canRepo,canDel } = this.props
return imgArr.length > 0 ? (
<div className={'preview-wrapper' + (visible ? ' show' : ' hide')} style={{ width: screenWidth, height: screenHeight }}>
<div className='img-container'>
<div className="img-wrap" ref={(imgEl) => { this.imgEl = imgEl }} style={{ 'width':this.state.defaultWidth,'height':this.state.defaultHeight }}>
<Icon onClick={() => { this.closePreview() }} type="close" />
<img className='image'
onWheel={this.wheelScale}
style={{ transform: `rotate(${angle}deg)` }}
// onMouseDown={this.mouseDown}
// onMouseMove={this.mouseMove}
// onMouseUp={this.mouseUp}
// onMouseOut={this.mouseOut}
// draggable='false'
src={imgArr[imgIndex][1]} alt="预览图片" />
</div>
</div>
<img className='origin-image' src={imgArr[imgIndex][1]} onLoad={this.getImgSize} ref={(originImg) => { this.originImgEl = originImg }} alt="预览图片" />
<div className='operate-con'>
<div onClick={this.changePic.bind(this, -1)} className={imgIndex==0?'operate-btn done':'operate-btn'}>
<Icon type="arrow-left" />
</div>
{
canDownload?<div onClick={this.download} className='operate-btn'>
<Icon type="download" />
</div>:null
}
{
canDel?<div onClick={this.del} className='operate-btn'>
<Icon type="delete" />
</div>:null
}
{/* <a href={imgArr[imgIndex]} download className='operate-btn'>
<i className='iconfont icon-icon-test10'></i>
<span>下载</span>
</a> */}
{/* <div onClick={() => { this.scaleBig('click') }} className='operate-btn'>
<i className='iconfont icon-icon-test33'></i>
<span>放大</span>
</div> */}
{
canRepo?<div onClick={this.retate} className='operate-btn'>
<Icon type="redo" />
</div>:null
}
{/* <div onClick={() => { this.scaleSmall('click') }} className='operate-btn'>
<i className='iconfont icon-icon-test35'></i>
<span>缩小</span>
</div> */}
<div onClick={this.changePic.bind(this, 0)} className={imgIndex==imgArr.length-1?'operate-btn done':'operate-btn'}>
<Icon type="arrow-right" />
</div>
</div>
</div>
) : null
}
}<file_sep>export default {
user: null,
menu: null
}<file_sep>import request from '../utils/request'
const SERVICE_NAME = ''
/**
* 上传图片
* @param {*} data
*/
const uploadImage = (file) => {
return request({
url: SERVICE_NAME + '/static/ueditor/1.4.3.3/php/controller.php?action=uploadimage',
method: 'post',
headers: {'Content-Type':'multipart/form-data'},
data: file
})
}
/**
* 上传语音
* @param {*} data
*/
const uploadAudio = (file) => {
return request({
url: SERVICE_NAME + '/static/ueditor/1.4.3.3/php/controller.php?action=uploadvideo',
method: 'post',
headers: {'Content-Type':'multipart/form-data'},
data: file
})
}
export {
uploadImage,
uploadAudio
}<file_sep>/**
* 验证手机号码
* @param {*} phone
*/
const isPhoneNumber = phone => {
let result = false;
let reg = new RegExp(/^([1][2,3,4,5,6,7,8,9])\d{9}$/);
let r = phone.match(reg);
r ? (result = true) : (result = false);
return result;
};
/**
* 校验用户名
* @param {*} name
*/
const isPersonName = name => {
let result = false;
if (name && name.length < 20) {
result = true;
}
return result;
};
/**
* 校验密码
* @param {*} password
*/
const isPassword = password => {
let result = false;
if (password.length >= 6 && password.length < 16) {
result = true;
}
return result;
};
/**
* 是否包含全部的测量类型
*
*/
const isMeasureTypeFull = tableData => {
let results = true;
let type = null;
let typeArray = [];
for (let i in tableData) {
if (tableData[i].type !== type) {
typeArray.push(tableData[i].type);
}
}
if (typeArray.length < 3) {
return false;
}
return results;
};
const isTwoNumber = number => {
let results = false;
if (!isNaN(number) && number.length <= 2) {
results = true;
}
return results;
};
export {
isPhoneNumber,
isPersonName,
isPassword,
isMeasureTypeFull,
isTwoNumber
};<file_sep>export default function menu(state={},action){
switch(action.type){
case "CHANGE_MENU":
state.key = action.payload.pathname
return state
default:
return state
}
}<file_sep>// import React, { Component } from 'react';
// import {Button,Form,Input,Alert} from 'antd'
// import {formItemLayout,tailFormItemLayout} from '../../../utils/formItemLayout'
// import {updateUserPassword,userInfo} from '../../../apis/user';
// import {isPassword} from '../../../utils/validate';
// import {delCookie} from '../../../utils/index';
// import md5 from 'md5';
// import '../styles/center.scss'
// const FormItem = Form.Item
// class UserCenter extends Component{
// state = {
// userInfo:{},
// errorMessage:null,
// successMessage:null,
// changePasswordLoading:false,
// editLoading:false,
// disabled:true
// }
// componentWillMount(){
// this.actionGetUserInfo();
// }
// handleGetCode(){
// }
// //检验密码
// handleCheckPassword(e){
// let value = e.target.value;
// if(!isPassword(value)){
// this.setState({errorMessage:"请输入6-16位密码"})
// }
// }
// handleFocusInput(){
// this.setState({errorMessage:null})
// }
// //校验新密码
// handleCheckPasswordTwice(e){
// let {newPassword} = this.state
// let newPassword2 = e.target.value
// if(newPassword !== newPassword2){
// this.setState({errorMessage:"两次输入的密码不一致"})
// }
// }
// //修改密码输入框
// handlePasswordInput(name,e){
// let value = e.target.value;
// this.setState({[name]:value})
// }
// //修改密码
// handleUpdatePassword(){
// let {oldPassword,newPassword,userInfo} = this.state;
// if(oldPassword && isPassword(oldPassword) && newPassword && isPassword(newPassword)){
// this.actionUpdateUserPassword({
// newPassword:md5(<PASSWORD>),
// oldPassword:md5(<PASSWORD>),
// username:userInfo.mobile
// })
// return
// }
// this.setState({errorMessage:"请输入6-16位密码"})
// }
// handleEdit(){
// this.setState({disabled:false})
// }
// handleCancel(){
// this.setState({disabled:true,errorMessage:null})
// }
// /**
// * 用户信息
// */
// async actionGetUserInfo(){
// let info = await userInfo();
// this.setState({userInfo:info.data || {}})
// }
// /**
// * 修改密码
// * @param {*} data
// */
// async actionUpdateUserPassword(data){
// let self = this;
// this.setState({changePasswordLoading:true})
// let updatePassword = await updateUserPassword(data).catch(err=>{
// self.setState({changePasswordLoading:false,errorMessage:err.msg})
// })
// if(updatePassword && updatePassword.code === 200){
// self.setState({changePasswordLoading:false,successMessage:"修改密码成功,请使用新密码登录",disabled:true})
// setTimeout(()=>{
// delCookie("accessToken")
// delCookie("session")
// window.location.href = '/rpm/#/login'
// },2000)
// }
// }
// render(){
// const {userInfo,errorMessage,changePasswordLoading,successMessage,disabled} = this.state
// return(
// <Form className="user-center">
// <FormItem {...formItemLayout} label="帐号">
// <span>{userInfo.mobile}</span>
// </FormItem>
// <FormItem {...formItemLayout} label="原密码">
// <Input
// placeholder='请输入原密码'
// type="password"
// onChange={this.handlePasswordInput.bind(this,'oldPassword')}
// onBlur={this.handleCheckPassword.bind(this)}
// onFocus={this.handleFocusInput.bind(this)}
// disabled={disabled}
// />
// </FormItem>
// <FormItem {...formItemLayout} label="新密码">
// <Input
// placeholder="请输入新密码"
// type="password"
// onBlur={this.handleCheckPassword.bind(this)}
// onFocus={this.handleFocusInput.bind(this)}
// onChange={this.handlePasswordInput.bind(this,'newPassword')}
// disabled={disabled}
// />
// </FormItem>
// <FormItem {...formItemLayout} label="确认新密码">
// <Input
// placeholder="请再次输入新密码"
// type="password"
// onBlur={this.handleCheckPasswordTwice.bind(this)}
// onFocus={this.handleFocusInput.bind(this)}
// onChange={this.handlePasswordInput.bind(this,'<PASSWORD>')}
// disabled={disabled}
// />
// </FormItem>
// <FormItem {...tailFormItemLayout}>
// {errorMessage ? <Alert message={errorMessage} type="error" /> : null}
// {successMessage ? <Alert message={successMessage} type="success" /> : null}
// </FormItem>
// <FormItem {...tailFormItemLayout}>
// {disabled?<Button type="primary" onClick={this.handleEdit.bind(this)}>编辑</Button>:<Button loading={changePasswordLoading} type="primary" onClick={this.handleUpdatePassword.bind(this)}>提交</Button>}
// {disabled?null:<Button onClick={this.handleCancel.bind(this)} type="default" style={{marginLeft:"20px"}}>取消</Button>}
// </FormItem>
// </Form>
// )
// }
// }
// export default UserCenter<file_sep>import React, { Component } from 'react';
import { Upload, Icon } from 'antd';
import configs from '@/configs/index'
import uuid from 'uuid'
// import ImgPreview from './imageViewer';
import Viewer from 'react-viewer';
import 'react-viewer/dist/index.css';
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
class PicturesWall extends React.Component {
state = {
previewImgArray: [],
imgPreviewVisible: false,
currentPreviewImgIndex: 0,
};
handleCancel = () => {
document.body.style.overflow = 'auto'
this.setState({ previewVisible: false })
};
handlePreview = async file => {
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj);
}
let currentPreviewImgIndex = 0;
let previewImgArray = [];
console.log(this.props.fileList)
this.props.fileList.map((item, index) => {
let url = item.url?item.url:configs.server+item.response.url
previewImgArray.push({
src:url
})
if (item.uid == file.uid) {
currentPreviewImgIndex = index;
}
})
this.setState({
imgPreviewVisible: true,
previewImgArray,
currentPreviewImgIndex
});
};
handleChange = ({ fileList }) => {
if (!this.props.disabled) {
this.props.change(fileList)
}
};
checkBefore(e) {
e.stopPropagation()
if (this.state.checkIndex) {
this.setState({
checkIndex: this.state.checkIndex - 1
})
}
}
checkAfter(e) {
e.stopPropagation()
if (this.state.checkIndex < this.props.fileList.length - 1) {
this.setState({
checkIndex: this.state.checkIndex + 1
})
}
}
del = (index) => {
let checkIndex = index >= this.props.fileList.length - 1 ? 0 : index;
this.props.fileList.splice(index, 1)
if (this.props.fileList.length == 0) {
this.handleCancel()
} else {
this.setState({
checkIndex
});
}
this.props.change({
fileList: this.props.fileList
})
};
render() {
let { fileList, action } = this.props;
let previewImgArr = [];
fileList.map(item => {
let src = item.url || item.thumbUrl;
previewImgArr.push([src, src])
})
const { imgPreviewVisible, currentPreviewImgIndex, previewImgArray } = this.state;
return (
<div className="clearfix">
<Upload
name="upfile"
action={action}
listType="picture-card"
fileList={fileList}
onPreview={this.handlePreview}
onChange={this.handleChange}
>
{
!this.props.disabled ? <div>
<Icon type="plus" />
<div className="ant-upload-text">Upload</div>
</div> : null
}
</Upload>
<Viewer
visible={imgPreviewVisible}
onClose={() => { this.setState({ imgPreviewVisible: false }); }}
images={previewImgArray}
activeIndex={currentPreviewImgIndex}
/>
</div>
);
}
}
const styles = {
optWrap: {
display: "flex",
justifyContent: 'space-around',
alignItems: 'center',
alignContents: 'center',
width: '400px',
height: '60px',
borderRadius: '20px',
position: 'absolute',
left: '50%',
transform: 'translateX(-50%)',
bottom: '10px',
background: 'rgba(0,0,0,0.8)'
},
btn: {
display: 'block',
cursor: 'pointer',
textAlgin: 'center'
},
iconDone: {
fontSize: '20px',
color: '#ccc'
},
icon: {
fontSize: '20px',
color: '#fff'
},
imgWrap: {
position: 'absolute',
left: "50%",
top: '50%',
transform: 'translate(-50%,-50%)',
width: '100%',
height: '600px',
overflow: 'hidden'
},
img: {
maxWidth: '90%',
position: 'absolute',
left: "50%",
top: '50%',
transform: 'translate(-50%,-50%)'
},
previewWrap: {
position: 'fixed',
width: '100%',
height: '100%',
left: '0',
top: '0',
background: 'rgba(0,0,0,0.3)',
zIndex: '100'
},
// mask:{
// position:'fixed',
// width:'100%',
// height:'100%',
// left:'0',
// top:'0'
// }
}
export default PicturesWall<file_sep>import request from '../utils/request'
import config from '../configs/index'
const SERVICE_NAME = ''
/**
* 登录
* @param {*} data
*/
const login = ({username,password}) => {
return request({
url: SERVICE_NAME + '/admin/auth',
method: 'post',
data: {
username,
password
}
})
}
/**
* 登出
*/
const logout = () => {
return request({
url: SERVICE_NAME + '/admin/logout'
})
}
const getMenu = (data) => {
return request({
url: SERVICE_NAME + '/common/login',
method: 'post',
data: {
appType: config.appType,
...data
}
})
}
/**
* 获取账号列表
*/
const getUsertList = () => {
return request({
url: SERVICE_NAME + '/admin/account',
method: 'get'
})
}
/**
* 获取账号详情
*/
const getUserById = (id) => {
return request({
url:SERVICE_NAME + '/admin/account/'+id,
method: 'get'
})
}
/**
* 添加账号
* @param {*} data
*/
const addUser = (data) => {
return request({
url: SERVICE_NAME + '/admin/account',
method: 'post',
data
})
}
/**
* 更新账号
* @param {*} id
* @param {*} data
*/
const updateUser = (id,data) => {
return request({
url: SERVICE_NAME + '/admin/account/'+id,
method: 'put',
data
})
}
/**
* 删除账号
* @param {*} id
*/
const deleteUser = (id) => {
return request({
url: SERVICE_NAME + '/admin/account/'+id,
method: 'delete'
})
}
export {
login,
logout,
getMenu,
getUsertList,
getUserById,
addUser,
updateUser,
deleteUser
}<file_sep>import React, { Component } from 'react';
import { Form, Icon, Input, Button } from 'antd';
import { setLocal,setCookie } from '@/utils/index'
import { isPhoneNumber } from '@/utils/validate'
import { withRouter } from 'react-router-dom';
import { login,getMenu } from '@/apis/user'
import { connect } from 'react-redux'
import actions from '../../redux/actions'
import './styles/login.scss'
const FormItem = Form.Item;
class FormWrap extends Component {
state = {
username: '',
password: '',
passwordType: true,
errorMessage: '',
submitLoading: false
}
handleSubmit() {
let self = this;
let { username, password } = this.state
if (username && password) {
self.setState({ submitLoading: true })
login({ username, password }).then(res => {
self.setState({ submitLoading: false });
self.loginSuccessHanlder(res.data)
}).catch(err => {
self.setState({ errorMessage: err.msg, submitLoading: false })
})
} else {
this.setState({ errorMessage: '请输入帐号和密码' })
}
}
//输入框监听
handleInput(keyName, e) {
this.setState({
[keyName]: e.target.value
})
}
//清空输入框
handleEmpty() {
this.setState({ username: null })
}
handleClearPassword() {
this.setState({
password: null
})
}
//显示密码
handleShowPassword() {
let { passwordType } = this.state
this.setState({ passwordType: !passwordType })
}
//密码框获取焦点是校验手机号码
handleFocus() {
let { username } = this.state;
if (username && !isPhoneNumber(username)) {
// this.setState({ errorMessage: '输入的手机号有误' })
} else {
this.setState({ errorMessage: null })
}
}
//获取焦点,隐藏errorMessage
handleInputFocus() {
this.setState({ errorMessage: null })
}
loginSuccessHanlder = (loginData) => {
setCookie('_secret_token',loginData.token);
setLocal('_secret_user', JSON.stringify(loginData));
// this.actionGetMenu()
console.log('....')
this.props.setUser(loginData)
setTimeout(() => {
this.props.history.push('/')
},100)
}
/**
* 获取菜单
*/
async actionGetMenu() {
let getmenu = await getMenu()
let menus = getmenu.data.menus || []
setLocal("menus", JSON.stringify(menus))
let firstMenu = menus[0].pageUrl;
window.location.href = '/secretManage/#' + firstMenu
}
render() {
const { username, password, passwordType, errorMessage, submitLoading } = this.state;
const suffix = username ? <Icon type='close-circle' onClick={this.handleEmpty.bind(this)} /> : null;
const passwordSuffix = <span>{password ? <Icon type='close-circle' onClick={this.handleClearPassword.bind(this)} style={{ marginRight: "10px" }} /> : null}{passwordType ? <Icon type='eye' onClick={this.handleShowPassword.bind(this)} /> : <Icon type='eye-invisible' onClick={this.handleShowPassword.bind(this)} />}</span>
const showErrorMsg = errorMessage ? errorMessage : null
const pageStepOne = () => {
return (
<div>
<div className='login-title'>管理平台</div>
<Form className='login-form'>
<FormItem>
<Input
prefix={<Icon type='user' style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder='请输入帐号'
suffix={suffix}
onChange={this.handleInput.bind(this, 'username')}
onFocus={this.handleInputFocus.bind(this)}
value={username}
/>
</FormItem>
<FormItem>
<Input
prefix={<Icon type='lock' style={{ color: 'rgba(0,0,0,.25)' }} />}
suffix={passwordSuffix}
type={passwordType ? 'password' : 'text'}
placeholder='请输入密码'
onChange={this.handleInput.bind(this, 'password')}
onFocus={this.handleFocus.bind(this)}
value={password}
/>
</FormItem>
<p className='err-msg'>{showErrorMsg}</p>
<FormItem>
<Button
type='primary'
className='login-form-button'
onClick={this.handleSubmit.bind(this)}
loading={submitLoading}
>登录</Button>
</FormItem>
<div className='bottom-btn'>
{/* <span onClick={this.handleChangePage.bind(this,1)}>忘记密码</span> */}
{/* <span onClick={this.handleChangePage.bind(this,1)}>注册用户</span> */}
</div>
</Form>
</div>
)
}
return (
<div className='login-wrap'>
<div className='login-center'>
{pageStepOne()}
</div>
</div>
)
}
}
const Login = Form.create()(FormWrap);
export default withRouter(connect(null,{
setUser:actions.setUser
})(Login))
<file_sep>import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { Table, Pagination, Button, Input, Upload, Icon, Modal, Select, Dropdown, Menu,Tag } from 'antd';
import Viewer from 'react-viewer';
import 'react-viewer/dist/index.css';
import Excel from '@/utils/excel'
import { getCookie } from '@/utils/index'
import AddForm from './components/addForm'
import EditForm from './components/editForm'
import {
getSecretList,
getSecretListByPhone,
addSecret,
updateSecret,
deleteSecret
} from '@/apis/dataCenter'
import { connect } from 'react-redux'
import configs from '@/configs'
import './styles/dataCenter.scss'
import { Base64 } from 'js-base64';
const InputSearch = Input.Search
const excel = new Excel()
const { Option } = Select
class DataCenter extends Component {
constructor(props) {
super(props)
this.state = {
disabled: true,
scroll: {},//待录入列表的滚动条设置{x,y}
// patientNum: '',
// errorTip: '',
list: [
// {
// audio: 'test',
// say_to_you: 'test',
// thumb: 'http://www.baidu.com/img/[email protected]',
// username: 'test',
// order_code: '1111111',
// mobile: '111111111'
// }
],//列表数据
page: 1,//当前页数
total: 0,//总条数
pageSize: 15,//每页10条
modalAddFlag: false,
modalEditFlag: false,
previewImgArray: [],
currentPreviewImgIndex: 0,
imgPrviewVisible: false,
secret_edit_modal_height: 'auto'
}
}
componentDidMount() {
let height = document.body.clientHeight * 80 / 100
height = height > 700 ? 700 : height
this.setState({
secret_edit_modal_height: height
})
this.setState({
scroll: {
x: 2000,//横向滚动最小范围
// y: document.body.clientHeight - 482//一屏展示
}
})
this.getSecretList()
}
getSecretList(mobile) {
getSecretList({
page: this.state.page,
mobile
}).then(res => {
let data = res.data;
if(data.data){
data.data.map(item => {
if(item.username){
try{
item.username = Base64.encode(item.username); // ZGFua29nYWk=
}catch(e){
}
item.username = Base64.decode(item.username);
}
if(item.say_to_you){
try{
item.say_to_you = Base64.encode(item.say_to_you);
}catch(e){
}
item.say_to_you = Base64.decode(item.say_to_you);
}
return item
})
}
this.setState({
total: data.total,
list: data.data
})
})
}
// searchPatient = () => {
// if (this.state.patientNum.toString().trim() != '') {
// } else {
// this.setState({
// errorTip: '请输入患者手机号码/患者编号'
// })
// return
// }
// searchCrf({
// searchText: this.state.patientNum
// }).then(res => {
// if (!res.data) {
// this.setState({
// errorTip: '输入患者编号或手机号有误'
// })
// } else {
// this.props.history.push('/crf/patient?id=' + this.state.patientNum)
// }
// })
// }
/**
* 页码改变
* @params {*} page 当前页码
* @params {*} pageSize 页码条数
*/
onPageChange = (page, pageSize) => {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.setState({
page
}, () => {
this.getSecretList()
})
}, 200)
}
postOut = () => {
excel.exportExcel(this.state.list, { 名称: 'name', test: 'mobile' }, '公共')
}
openDetail = (record, index, type, e) => {
e.stopPropagation()
this.setState({
disabled: type == 'edit' ? false : true,
modalEditFlag: true,
editIndex: index
})
}
openAddModal = () => {
this.setState({
modalAddFlag: true
})
}
handleModalAddCancel = () => {
this.setState({
modalAddFlag: false,
})
}
handleModalEditCancel = () => {
this.setState({
modalEditFlag: false,
disabled: true
})
}
handleEdit = () => {
this.setState({
disabled: false
})
}
handleEditSubmit = (values) => {
let { list, editIndex } = this.state;
let { id } = list[editIndex]
console.log(".../")
updateSecret(id, values).then(res => {
list[editIndex] = { ...list[editIndex], ...values }
this.setState({
disabled: true,
modalEditFlag: false,
list
})
})
}
handleAddSubmit = (values) => {
addSecret(values).then(res => {
this.setState({
modalAddFlag: false
})
this.getSecretList()
})
}
//批量删除
handleBitchDelete = () => {
console.log(this.state.selectedRows)
}
handleDelete = (id, e) => {
e.stopPropagation()
Modal.confirm({
title: '确定删除',
onOk: () => {
if (!id) {
id = this.state.list[this.state.editIndex].id
}
deleteSecret(id).then(res => {
this.getSecretList()
this.setState({
modalEditFlag: false
})
})
}
})
}
previewImg = (currentPreviewImgIndex, e) => {
e.stopPropagation();
let { list } = this.state;
let previewImgArray = [];
list.map(item => {
if (item.rel_thumb && item.rel_thumb.path) {
previewImgArray.push({
src: configs.server + item.rel_thumb.path
})
}
})
this.setState({
imgPrviewVisible: true,
previewImgArray,
currentPreviewImgIndex
})
}
handleStatusChange = (value) => {
console.log(value)
}
handleStatusMenuClick = (e, index) => {
let { list, editIndex } = this.state;
let id = ''
let item = {}
if (index != undefined) {
item = list[index]
} else {
item = list[editIndex]
}
if (item.flag != e.key) {
item.flag = e.key ? e.key : '';
updateSecret(item.id, item).then(res => {
this.setState({
list
})
})
}
}
search = (value) => {
this.getSecretList(value)
}
render() {
let { list, selectedRows, editIndex, disabled, previewImgArray, currentPreviewImgIndex, secret_edit_modal_height } = this.state
let formData = list && list.length > 0 && editIndex >= 0 ? list[editIndex] : {}
let statusStyles = {
color: formData.flag == 1 ? 'red' : (formData.flag == 2 ? 'blue' : '')
}
const renderContent = (text, row, index, type, style) => {
statusStyles = {
color: row.flag == 1 ? 'red' : (row.flag == 2 ? 'blue' : '')
}
if (type == 'rel_thumb') {
return text && text.path ? <img className="td-img" onClick={(e) => this.previewImg(index, e)} src={configs.server + text.path}></img> : null
} else if (type == 'tags') {
return <div className="opt-td" onClick={(e) => e.stopPropagation()}>
<Icon title="编辑" type="form" onClick={e => this.openDetail(row, index, 'edit', e)} />
<Icon title="删除" type="delete" onClick={this.handleDelete.bind(this, row.id)} />
{/* <Button size="small" type="danger" onClick={this.handleDelete.bind(this, row.id)}>删除</Button> */}
<Dropdown title="标记" className="status-dropdown" overlay={<Menu onClick={(e) => this.handleStatusMenuClick(e, index)}>
<Menu.Item key="1" className="red-item">红色</Menu.Item>
<Menu.Item key="2" className="blue-item">蓝色</Menu.Item>
<Menu.Item className="gray-item">删除标记</Menu.Item>
</Menu>} trigger={['click']}>
<Icon type="tag" style={statusStyles} />
</Dropdown>
</div>
} else if (type == 'rel_audio') {
return text && text.path ? <a onClick={e => e.stopPropagation()} title={configs.server + text.path} className="audio_url" style={style} href={configs.server + text.path} download>{configs.server + text.path}</a> : null
} else if (type.indexOf('wx') == 0) {
type = type.slice(3);
let str = ''
if (text) {
str = text[type]
if (type == 'sex') {
str = str == 1 ? '男' : (str == 2 ? '女' : '')
return <div title={str} className="no-wrap" style={style}>{str}</div>
} else if (type == 'nickname') {
str = <div><img className="wx_headimg" src={text.headimgurl}></img>{text[type]}</div>
return <div title={text[type]} className="no-wrap" style={style}>{str}</div>
} else if (type == 'province') {
str = str + ' ' + text.city
return <div title={str} className="no-wrap" style={style}>{str}</div>
} else if(type=='audio'){
let color = row.wx_audio_link?'':row.over_three_day == 'yes'?'red':(row.over_one_hour == 'yes'?'volcano':'')
return text&&text!=0?<div title={text} className="no-wrap" style={style}><Tag color={color}>{text}</Tag></div>:null
}
}
return null
} else {
return text?<div title={text} className="no-wrap" style={style}>{text}</div>:null
}
}
const getColumnSearchProps = dataIndex => ({
filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
<div className="opt-group">
<Button onClick={this.openAddModal}>添加数据</Button>
{/* <Button onClick={this.handleBitchDelete}>批量删除</Button> */}
{/* <Upload className="upload" {...uploadProps}>
<Button><Icon type="import" /> 导入数据</Button>
</Upload>
<Button onClick={this.postOut}><Icon type="export" />导出数据</Button> */}
</div>
),
filterIcon: filtered => (
<Icon type="down-square" style={{ color: filtered ? '#1890ff' : undefined }} />
)
});
const columns = [{
title: '序号',
key: "idx",
width: 50,
render: (text, record, index) => {
return index + 1
}
}, {
title: '提交时间',
dataIndex: 'created_at',
key: 'created_at',
render: (text, row, index) => renderContent(text, row, index, 'created_at', { width: '140px' })
}, {
title: '查询次数',
dataIndex: 'view',
key: 'view',
},{
title: '录音',
dataIndex: 'wx_audio',
key: 'wx_audio',
render: (text, row, index) => renderContent(text, row, index, 'wx_audio', { width: '100px' })
}, {
title: '我想对您说',
dataIndex: 'say_to_you',
key: 'say_to_you',
// width: 160,
render: (text, row, index) => renderContent(text, row, index, 'say_to_you', { width: '160px' })
}, {
title: '永恒一刻',
dataIndex: 'rel_thumb',
key: 'rel_thumb',
width: 150,
render: (text, row, index) => renderContent(text, row, index, 'rel_thumb')
}, {
title: '送卡人姓名/昵称',
dataIndex: 'username',
key: 'username',
render: (text, row, index) => renderContent(text, row, index, 'username', { width: '150px' })
}, {
title: 'powerionics淘宝或京东订单编号',
dataIndex: 'order_code',
key: 'order_code',
render: (text, row, index) => renderContent(text, row, index, 'order_code', { width: '250px' })
}, {
title: '手机号码',
dataIndex: 'mobile',
key: 'mobile',
render: (text, row, index) => renderContent(text, row, index, 'mobile', { width: '100px' })
}, {
title: '微信昵称',
dataIndex: 'rel_wechat',
key: 'rel_wechat_nickname',
render: (text, row, index) => renderContent(text, row, index, 'wx_nickname', { width: '80px' })
}, {
title: '微信性别',
dataIndex: 'rel_wechat',
key: 'rel_wechat_sex',
render: (text, row, index) => renderContent(text, row, index, 'wx_sex', { width: '80px' })
}, {
title: '微信省市',
dataIndex: 'rel_wechat',
key: 'rel_wechat_province',
render: (text, row, index) => renderContent(text, row, index, 'wx_province', { width: '120px' })
}, {
title: '操作',
dataIndex: 'tags',
key: 'tags',
fixed: 'right',
width: 140,
render: (text, row, index) => renderContent(text, row, index, 'tags'),
...getColumnSearchProps('tags')
}]
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
this.setState({
selectedRows
})
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
getCheckboxProps: record => ({
name: record.name,
}),
};
const uploadProps = {
name: 'file',
action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
headers: {
authorization: 'authorization-text',
},
onChange(info) {
if (info.file.status == 'done') {
excel.importExcel(info.file.originFileObj, { 名称: 'test1', 型号: 'test2' }).then(data => {
console.log(data)
})
}
},
};
return (
<div className="crf-wrap">
<div className="opt-bar">
{/* <div className="flex-wrap">
<Select disabled={!selectedRows || selectedRows.length == 0} value="状态修改" style={{ width: 120 }} onChange={this.handleStatusChange}>
<Option value="1">红色</Option>
<Option value="2">蓝色</Option>
<Option value="2">删除标记</Option>
</Select>
</div> */}
<div className="search-wrap">
{/* <InputSearch className="search-input"></InputSearch> */}
<InputSearch className="search-input" placeholder="输入手机号码查询" onSearch={this.search} enterButton />
</div>
</div>
<div className="list-wrap">
<div className="list">
<Table rowKey="id" rowClassName={(record, index) => record.flag == 1 ? 'red-row' : (record.flag == 2 ? 'blue-row' : '')} className="secret-table" size="small" bordered ref="table" onRow={(record, index) => {
return {
onClick: (e) => this.openDetail(record, index, '', e), // 点击行
};
}} columns={columns} dataSource={this.state.list} pagination={false} scroll={this.state.scroll} />
<Pagination pageSize={this.state.pageSize} onChange={this.onPageChange} total={this.state.total} />
</div>
</div>
<Viewer
visible={this.state.imgPrviewVisible}
onClose={() => { this.setState({ imgPrviewVisible: false }); }}
images={previewImgArray}
activeIndex={currentPreviewImgIndex}
/>
<Modal
className="my_modal"
style={{ height: secret_edit_modal_height }}
title={
<div className="top">
<p>编辑密语</p>
<div className="opt-wrap">
<Dropdown className="status-dropdown" overlay={<Menu onClick={this.handleStatusMenuClick}>
<Menu.Item key="1" className="red-item">红色</Menu.Item>
<Menu.Item key="2" className="blue-item">蓝色</Menu.Item>
<Menu.Item className="gray-item">删除标记</Menu.Item>
</Menu>} trigger={['click']}>
<Icon type="tag" style={statusStyles} />
</Dropdown>
<Icon onClick={this.handleModalEditCancel} className="close-btn" type="close" />
</div>
</div>
}
closable={false}
centered
visible={this.state.modalEditFlag}
footer={null}
onCancel={this.handleModalEditCancel}
destroyOnClose={true}
width={900}
>
<EditForm disabled={disabled} formData={formData} onEdit={this.handleEdit} onSubmit={this.handleEditSubmit} onDelete={(e) => this.handleDelete('', e)}></EditForm>
</Modal>
<Modal
className="my_modal"
style={{ height: secret_edit_modal_height }}
title="添加密语"
centered
visible={this.state.modalAddFlag}
footer={null}
onCancel={this.handleModalAddCancel}
destroyOnClose={true}
width={700}
>
<AddForm onCancel={this.handleModalAddCancel} onSubmit={this.handleAddSubmit}></AddForm>
</Modal>
</div>
);
}
}
export default withRouter(connect(state => {
return {
user:state.user
}
},null)(DataCenter))<file_sep>export default {
changeMenu(pathname) {
return {
type: "CHANGE_MENU",
payload: {
pathname
}
}
}
}<file_sep>import React, { Component } from 'react';
import {HashRouter as Router,Switch} from "react-router-dom";
import routes from './routes/index';
import RouteWithSubRoutes from './components/RouteWithSubRoutes.jsx'
class App extends Component {
render() {
return (
<Router>
<Switch>
{routes.map((route, i) => <RouteWithSubRoutes key={i} {...route}/>)}
</Switch>
</Router>
);
}
}
export default App;
<file_sep>import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { getCookie } from '../utils/index';
//不需要登录态的页面
const pageWithoutAnth = ['/login', '/signup']
const RouteWithSubRoutes = (route) => {
let access_token = getCookie('_secret_token');
if (pageWithoutAnth.indexOf(route.path) >= 0) {
//路由白名单
return (
<Route
path={route.path}
render={props => (
<route.component {...props} routes={route.children} />
)}
/>
);
} else {
if (access_token) {
//已经登陆过
if (route.location.pathname == '/') {
return <Redirect to="/dataCenter" />
}
return (
<Route
path={route.path}
render={props => (
<route.component {...props} routes={route.children} />
)}
/>
);
} else {
//未登录 重定向登陆页面
return (<Redirect to="/login" />)
}
}
}
export default RouteWithSubRoutes
<file_sep>import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import Viewer from 'react-viewer';
import QRCode from 'qrcode.react';
import { Upload, Icon, Form, Button, message } from 'antd';
import { getBase64 } from '@/utils'
import './styles/editor.scss'
import 'react-viewer/dist/index.css';
import { getCookie } from '../../utils';
import configs from '@/configs'
import {saveBg,getBgUrl} from '@/apis/dataCenter'
const FormItem = Form.Item;
class Editor extends React.Component {
state = {
visible: false,
currentImgArray: [],
currentImgIndex: 0,
bgFileList: [],
};
componentWillMount() {
this.getInfo()
}
getInfo() {
getBgUrl().then(res => {
let data = res.data;
if (data && data.length != 0) {
console.log(data)
let url = configs.server + data[0].rel_image.path;
let bgFileList = [
{
uid: '-1',
name: 'xxx.png',
status: 'done',
url,
id:data[0].image_id
}
]
this.setState({
bgFileList,
origin_image_id:data[0].id
})
}
})
}
handlePreview = async file => {
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj);
}
let src = file.url || file.preview;
this.setState({ currentImgArray: [{ src }], currentImgIndex: 0, isOpen: true, visible: true })
}
handleChange = ({ fileList }) => {
fileList.splice(0, fileList.length - 1)
this.setState({ bgFileList: fileList })
}
handleSubmit = (e) => {
e && e.preventDefault();
this.props.form.validateFields((err, values) => {
if (err) return;
//数据校验通过后,传递到上级提交
let {bgFileList,origin_image_id} = this.state;
if (bgFileList.length == 0) {
message.warn('请上传图片')
} else {
let image_id = bgFileList[0].id?bgFileList[0].id:bgFileList[0].response.id
saveBg({
image_id
},origin_image_id).then(res => {
if(res.code==0){
message.info('上传成功')
}
})
}
});
}
handleCancel = () => {
this.setState({
bgFileList: []
})
}
render() {
const { getFieldDecorator, getFieldValue } = this.props.form;
const { currentImgArray, currentImgIndex, bgFileList } = this.state;
let qrCodeUrl = ''
if (bgFileList && bgFileList.length != 0) {
if (bgFileList[0].url) {
qrCodeUrl = bgFileList[0].url
} else if (bgFileList[0].response && bgFileList[0].response.url) {
qrCodeUrl = configs.server + bgFileList[0].response.url
}
}
if (qrCodeUrl) {
qrCodeUrl = configs.server+'/secret/#/powerionics/write?bg=' + qrCodeUrl
}
const formItemLayout2 = {
labelCol: {
xs: { span: 24 },
sm: { span: 3 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 12 },
},
};
return (
<div className="clearfix">
<Form labelalign="left">
<FormItem label="背景图片上传" {...formItemLayout2}>
{
getFieldDecorator('imageList', {
initialValue: '',
})(
<Upload
name="upfile"
action={configs.server + "/static/ueditor/1.4.3.3/php/controller.php?action=uploadimage"}
listType="picture-card"
fileList={bgFileList}
onPreview={this.handlePreview}
onChange={this.handleChange}
// headers={headers}
>
{/* {fileList.length >= 1 ? null : uploadButton} */}
<div>
<Icon type="plus" />
<div className="ant-upload-text">Upload</div>
</div>
</Upload>
)
}
</FormItem>
{
qrCodeUrl ?
<FormItem label="二维码链接" {...formItemLayout2}>
<QRCode value={qrCodeUrl} />
</FormItem> : null
}
<FormItem label=" " colon={false} {...formItemLayout2}>
<div className="btn-wrap">
<Button id="form-submit-btn" type="primary" disabled={this.props.disabled} onClick={this.handleSubmit}>保存</Button>
<Button onClick={this.handleCancel}>取消</Button>
</div>
</FormItem>
</Form>
<Viewer
visible={this.state.visible}
onClose={() => { this.setState({ visible: false }); }}
images={currentImgArray}
activeIndex={currentImgIndex}
/>
</div>
);
}
}
export default withRouter(Form.create({
onValuesChange: (props, changedValues, allValues) => {
}
})(Editor))<file_sep>import React, { Component } from 'react';
import {Form,Input} from 'antd'
import {getLocal} from '@/utils';
const FormItem = Form.Item
class Info extends Component{
state = {
userInfo:{}
}
componentWillMount(){
// this.actionGetUserInfo();
let user = getLocal('_secret_user')
if(user){
user = JSON.parse(user);
this.setState({
userInfo:user
})
}
}
/**
* 用户信息
*/
// async actionGetUserInfo(){
// let info = await userInfo();
// this.setState({userInfo:info.data || {}})
// }
render(){
const {
userInfo
} = this.state
return(
<Form className="user-center">
<FormItem label="账号" >
<Input disabled={true} value={userInfo.username} />
</FormItem>
</Form>
)
}
}
export default Info<file_sep>import XLSX from 'xlsx';
export default class Excel {
constructor() {//constructor是一个构造方法,用来接收参数
}
importExcel(file,keysObj) {
return new Promise((resolve,reject) => {
if (!file) reject({msg:'file is null'});
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (e) {
const data = this.result;
const wb = XLSX.read(data, {
type: 'buffer'
})
const params = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
if(keysObj){
params.map(item => {
for(let x in item){
item[keysObj[x]] = item[x]
delete item[x]
}
return item;
})
}
resolve(params)
}
})
}
exportExcel(dataArr,keysObj,fileName) {
console.log(this)
const datas = dataArr;
const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };//这里的数据是用来定义导出的格式类型
const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
const data = datas.map((item,index) => {
let _item = {}
for(let x in keysObj){
_item[x] = item[keysObj[x]]
}
return _item
})
wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data);//通过json_to_sheet转成单页(Sheet)数据
this.saveAs(new Blob([this.s2ab(XLSX.write(wb, wopts))], { type: "application/octet-stream" }), (fileName?fileName:"demo") + '.' + (wopts.bookType == "biff2" ? "xls" : wopts.bookType));
}
// 导出excel
saveAs(obj, fileName) {
var tmpa = document.createElement("a");
tmpa.download = fileName || "下载";
tmpa.href = URL.createObjectURL(obj); //绑定a标签
tmpa.click(); //模拟点击实现下载
setTimeout(function () { //延时释放
URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
}, 100);
}
s2ab(s) {
if (typeof ArrayBuffer !== 'undefined') {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
} else {
var buf = new Array(s.length);
for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
}
}
<file_sep>import React, { Component } from 'react';
import {Tabs} from 'antd'
import {Info} from './components/index'
const TabPane = Tabs.TabPane;
class UserCenter extends Component{
state = {
}
componentWillMount(){
}
render(){
return(
<div>
<Tabs defaultActiveKey="1" animated={false} type="card" >
<TabPane tab="基本信息" key="1">
<Info />
</TabPane>
{/* <TabPane tab="修改密码" key="3">
<UpdatePassword />
</TabPane> */}
</Tabs>
</div>
)
}
}
export default UserCenter<file_sep>import request from '../utils/request'
const SERVICE_NAME = ''
/**
* 获取密语列表
*/
const getSecretList = ({page=1,pageSize=10,mobile} = {}) => {
return request({
url: SERVICE_NAME + '/admin/speech',
method: 'get',
params:{
page,
pageSize,
mobile
}
})
}
/**
* 获取密语详情
*/
const getSecretById = (id) => {
return request({
url:SERVICE_NAME + '/admin/speech/'+id,
method: 'get'
})
}
/**
* 获取密语列表
* @param {*} data
*/
const getSecretListByPhone = (data) => {
return request({
url: SERVICE_NAME + '/common/speech',
method: 'post',
data: {
...data
}
})
}
/**
* 添加密语
* @param {*} data
*/
const addSecret = (data) => {
return request({
url: SERVICE_NAME + '/api/speech',
method: 'post',
data
})
}
/**
* 更新密语
* @param {*} id
* @param {*} data
*/
const updateSecret = (id,data) => {
return request({
url: SERVICE_NAME + '/admin/speech/'+id,
method: 'put',
data
})
}
/**
* 删除密语
* @param {*} id
*/
const deleteSecret = (id) => {
return request({
url: SERVICE_NAME + '/admin/speech/'+id,
method: 'delete'
})
}
/**
* 获取背景图片
*/
const getBgUrl = () => {
return request({
url: '/api/back-image',
method: 'get'
})
}
/**
* 保存背景图片
* @param {*} id
*/
const saveBg = ({image_id,remark},origin_id) => {
let url = origin_id?SERVICE_NAME + '/admin/back-image/'+origin_id:SERVICE_NAME + '/admin/back-image';
let method = origin_id?'put':'post'
return request({
url,
method,
data:{
image_id,
remark
}
})
}
/**
* 获取验证码
*/
const getCodeUrl = () => {
return request({
url: '/captcha/api',
method: 'get'
})
}
export {
getSecretById,
getSecretList,
getSecretListByPhone,
addSecret,
updateSecret,
deleteSecret,
saveBg,
getBgUrl,
getCodeUrl
} | 0ef22eecfb973b62efe41a9aba3664ff3a74e1be | [
"JavaScript"
]
| 25 | JavaScript | Docwzm/secret-ms | 375431be8c5f15a18f7385677f6487ab887a6585 | fc344839a4c96e4413fc073153a11060f899150d |
refs/heads/master | <repo_name>deltatree/easyfin<file_sep>/README.md
# easyfin
Threadsafe HBCI4JAVA Wrapper for easily accessing your financial accounts. Easyfin uses https://github.com/hbci4j/hbci4java/ as library.
Usage:
See [example](https://github.com/deltatree/easyfin/blob/master/src/test/java/de/deltatree/pub/apis/easyfin/UsageExample.java)
Gradle:
```gradle
dependencies {
implementation 'com.github.hbci4j:hbci4j-core:3.1.58'
implementation 'de.deltatree.pub.apis:easyfin:1.0.13'
}
```
Maven:
```maven
...
<dependencies>
<dependency>
<groupId>com.github.hbci4j</groupId>
<artifactId>hbci4j-core</artifactId>
<version>3.1.58</version>
</dependency>
<dependency>
<groupId>de.deltatree.pub.apis</groupId>
<artifactId>easyfin</artifactId>
<version>1.0.13</version>
</dependency>
</dependencies>
...
```
<file_sep>/src/main/java/de/deltatree/pub/apis/easyfin/HBCICallable.java
package de.deltatree.pub.apis.easyfin;
import java.util.Properties;
import java.util.concurrent.Callable;
import org.kapott.hbci.callback.HBCICallback;
import org.kapott.hbci.concurrent.HBCIPassportFactory;
import org.kapott.hbci.manager.HBCIHandler;
import org.kapott.hbci.manager.HBCIUtils;
import org.kapott.hbci.passport.HBCIPassport;
public abstract class HBCICallable<A extends HBCICommandResult> implements Callable<A> {
private final Properties properties;
private final HBCICallback callback;
private HBCIPassportFactory passportFactory;
protected HBCIPassport passport = null;
protected HBCIHandler handler = null;
public HBCICallable(Properties properties, HBCICallback callback, HBCIPassportFactory passportFactory) {
this.properties = properties;
this.callback = callback;
this.passportFactory = passportFactory;
}
@Override
public A call() throws Exception {
init();
try {
prepare();
return execute(this.passport, this.handler);
} catch (Exception e) {
throw e;
} finally {
done();
}
}
private void init() {
HBCIUtils.initThread(properties, callback);
}
private void prepare() throws Exception {
passport = passportFactory.createPassport();
if (passport != null) {
handler = new HBCIHandler(this.properties.getProperty("default.hbciversion"), passport);
}
}
protected abstract A execute(HBCIPassport passport, HBCIHandler handler) throws Exception;
private void done() {
if (handler != null) {
handler.close();
}
if (passport != null) {
passport.close();
}
HBCIUtils.doneThread();
}
}
<file_sep>/src/main/java/de/deltatree/pub/apis/easyfin/BankData.java
package de.deltatree.pub.apis.easyfin;
public interface BankData {
String getBlz();
String getName();
String getLocation();
String getBic();
String getChecksumMethod();
String getRdhAddress();
String getPinTanAddress();
String getRdhVersion();
String getPinTanVersion();
}
<file_sep>/build.gradle
plugins {
id "java"
id "eclipse"
id "io.freefair.lombok" version "6.4.1"
id("io.hkhc.jarbird") version "0.7.0"
}
repositories {
mavenLocal()
mavenCentral()
jcenter()
}
jarbird {
mavenCentral()
pub {}
}
sourceCompatibility = 1.8
dependencies {
compileOnly 'com.github.hbci4j:hbci4j-core:3.1.58'
testImplementation 'junit:junit:4.12'
testImplementation 'com.github.hbci4j:hbci4j-core:3.1.58'
}
<file_sep>/src/main/java/de/deltatree/pub/apis/easyfin/EasyFinFactory.java
package de.deltatree.pub.apis.easyfin;
import org.kapott.hbci.manager.HBCIUtils;
public class EasyFinFactory {
public static EasyFinBuilder builder() {
return new DefaultEasyFinBuilder();
}
public static void clean() {
HBCIUtils.done();
}
}
<file_sep>/src/test/java/de/deltatree/pub/apis/easyfin/UsageExample.java
package de.deltatree.pub.apis.easyfin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import org.kapott.hbci.structures.Konto;
public class UsageExample {
public static void main(String[] args) {
try {
for (int i = 1; i <= 1; i++) {
EasyFin ef = initEasyfin();
try {
for (Konto k : ef.getAccounts()) {
System.out.println("############################################");
System.out.println(k);
System.out.println("############################################");
ef.getTurnoversAsStream(k, daysInThePast(10))
.forEach(t -> System.out.println(k.number + " " + t.value + " " + t.usage));
}
} finally {
ef.clean();
}
}
} finally {
EasyFinFactory.clean();
}
}
private static Date daysInThePast(int days) {
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DATE, -days);
return instance.getTime();
}
private static EasyFin initEasyfin() {
return EasyFinFactory.builder() //
.customerId("VRNetKey Alias/ID") // Bei Volksbanken (agree21) und Sparkassen
.userId("VRNetKey Alias/ID") // haben CustomerId und UserId den gleichen Wert
.pin("Pin") //
.tanCallback((i) -> exampleTanCallback(i)) // Callback bei TAN-Abfrage
.bankData("Name / BIC / BLZ der Zielbank") //
.proxy("proxy.intern.domain.com:3128") // optional
.additionalHBCIConfiguration("key1", "value1") // optional
.additionalHBCIConfiguration("keyN", "valueN") // optional
.build();
}
private static String exampleTanCallback(Map<String, String> in) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Bitte TAN eingeben: ");
return reader.readLine();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
<file_sep>/src/main/java/de/deltatree/pub/apis/easyfin/DefaultEasyFin.java
package de.deltatree.pub.apis.easyfin;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.kapott.hbci.GV.HBCIJob;
import org.kapott.hbci.GV_Result.GVRKUms;
import org.kapott.hbci.GV_Result.GVRKUms.UmsLine;
import org.kapott.hbci.callback.HBCICallback;
import org.kapott.hbci.callback.HBCICallbackUnsupported;
import org.kapott.hbci.concurrent.DefaultHBCIPassportFactory;
import org.kapott.hbci.concurrent.HBCIPassportFactory;
import org.kapott.hbci.concurrent.HBCIThreadFactory;
import org.kapott.hbci.manager.HBCIHandler;
import org.kapott.hbci.manager.HBCIUtils;
import org.kapott.hbci.passport.HBCIPassport;
import org.kapott.hbci.status.HBCIExecStatus;
import org.kapott.hbci.structures.Konto;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@Data
public class DefaultEasyFin implements EasyFin {
private static final String YYYY_MM_DD = "yyyy-MM-dd";
static {
HBCIUtils.init(new Properties(), new HBCICallbackUnsupported());
}
private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(new HBCIThreadFactory());
private final static HBCIPassportFactory PASSPORT_FACTORY = new DefaultHBCIPassportFactory((Object) "Passports");
private Properties props;
private HBCICallback callback;
private String pin;
private String customerId;
private String userId;
private File passportFile;
private Function<Map<String, String>, String> tanCallback;
public DefaultEasyFin(BankData bankData, Map<String, String> additionalHBCIConfiguration) {
this.passportFile = new File("hbci---" + UUID.randomUUID().toString() + ".passport");
this.passportFile.deleteOnExit();
this.props = initProperties(bankData, additionalHBCIConfiguration, this.passportFile);
this.callback = new MyHBCICallback(new MyHBCICallbackAnswers() {
@Override
public String getPin() {
return DefaultEasyFin.this.pin;
}
@Override
public String getUserId() {
return DefaultEasyFin.this.userId;
}
@Override
public BankData getBankData() {
return bankData;
}
@Override
public String getCustomerId() {
return DefaultEasyFin.this.customerId;
}
@Override
public Function<Map<String, String>, String> getTanCallback() {
return DefaultEasyFin.this.tanCallback;
}
});
}
@Override
public Stream<UmsLine> getTurnoversAsStream(Konto account) {
return getTurnoversAsStream(account, GetTurnoversModeEnum.KUmsAll);
}
@Override
public Stream<UmsLine> getTurnoversAsStream(Konto account, GetTurnoversModeEnum mode) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
return getTurnoversAsStream(account, sdf.parse("1970-01-01"), mode);
} catch (ParseException e) {
throw new IllegalStateException(e);
}
}
@Override
public Stream<UmsLine> getTurnoversAsStream(Konto account, Date from) {
return getTurnoversAsStream(account, from, GetTurnoversModeEnum.KUmsAll);
}
@Override
public Stream<UmsLine> getTurnoversAsStream(Konto account, Date from, GetTurnoversModeEnum mode) {
Callable<TurnoversResult> callable = new HBCICallable<TurnoversResult>(this.props, this.callback,
PASSPORT_FACTORY) {
@Override
protected TurnoversResult execute(HBCIPassport passport, HBCIHandler handler) throws Exception {
HBCIJob job = handler.newJob(mode.name());
job.setParam("my", account);
job.setParam("startdate", new SimpleDateFormat(YYYY_MM_DD).format(from));
job.addToQueue();
HBCIExecStatus ret = handler.execute();
checkForFailure(ret);
GVRKUms result = (GVRKUms) job.getJobResult();
checkForFailure(result);
List<UmsLine> lines = result.getFlatData();
return new TurnoversResult(lines);
}
private void checkForFailure(GVRKUms result) {
if (!result.isOK()) {
throw new IllegalStateException("Fetching turnovers failed: "
+ result.getJobStatus().getErrorString() + " / " + result.getGlobStatus().getErrorString());
}
}
private void checkForFailure(HBCIExecStatus result) {
if (!result.isOK()) {
throw new IllegalStateException(
"Fetching turnovers failed: " + result.getErrorString() + " / " + result.getErrorString());
}
}
};
Future<TurnoversResult> submit = EXECUTOR.submit(callable);
try {
List<UmsLine> result = submit.get().getTurnovers();
return result.stream();
} catch (InterruptedException | ExecutionException e) {
throw new IllegalStateException(e);
}
}
@Override
public List<Konto> getAccounts() {
Callable<AccountsResult> callable = new HBCICallable<AccountsResult>(this.props, this.callback,
PASSPORT_FACTORY) {
@Override
protected AccountsResult execute(HBCIPassport passport, HBCIHandler handler) throws Exception {
Konto[] accounts = passport.getAccounts();
List<Konto> result = new ArrayList<Konto>();
for (Konto account : accounts) {
result.add(account);
}
return new AccountsResult(result);
}
};
Future<AccountsResult> submit = EXECUTOR.submit(callable);
try {
return submit.get().getAccounts();
} catch (InterruptedException | ExecutionException e) {
throw new IllegalStateException(e);
}
}
public void clean() {
EXECUTOR.shutdown();
while (!EXECUTOR.isTerminated()) {
try {
EXECUTOR.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
this.passportFile.delete();
}
private static Properties initProperties(BankData bankData, Map<String, String> additionalHBCIConfiguration,
File passportFile) {
Properties p = new Properties();
// Set basic parameters
p.setProperty("default.hbciversion", bankData.getPinTanVersion());
p.setProperty("log.loglevel.default", "1");
p.setProperty("client.passport.default", "PinTan");
// Configure for PinTan
p.setProperty("client.passport.hbciversion.default", bankData.getPinTanVersion());
p.setProperty("client.passport.PinTan.checkcert", "1");
p.setProperty("client.passport.PinTan.init", "1");
p.setProperty("client.passport.PinTan.filename", passportFile.getName());
for (String key : additionalHBCIConfiguration.keySet()) {
p.setProperty(key, additionalHBCIConfiguration.get(key));
}
return p;
}
public void setTanCallback(Function<Map<String, String>, String> tanCallback) {
this.tanCallback = tanCallback;
}
@Override
public Konto getAccount(String search) {
List<Konto> list = getAccounts().stream().filter(k -> k.toString().contains(search))
.collect(Collectors.toList());
if (list.size() == 1) {
return list.get(0);
} else if (list.size() < 1) {
throw new IllegalStateException("search with " + search + " gives no results");
} else {
throw new IllegalStateException(
"Multiple results: " + list.stream().map(k -> k.toString()).collect(Collectors.joining(",")));
}
}
}
<file_sep>/src/main/java/de/deltatree/pub/apis/easyfin/TurnoversResult.java
package de.deltatree.pub.apis.easyfin;
import java.util.List;
import org.kapott.hbci.GV_Result.GVRKUms.UmsLine;
import lombok.Data;
@Data
public class TurnoversResult implements HBCICommandResult {
private final List<UmsLine> turnovers;
}
| f1e475f0262a13a4a012b91324a247b7ca408abf | [
"Markdown",
"Java",
"Gradle"
]
| 8 | Markdown | deltatree/easyfin | abb2735f5d1632d3a18a7d2178ed3c4d2037cebb | 91c7abe57d59a3d16282f9d85c3f8a71a7f97d5c |
refs/heads/main | <file_sep>// import Example from './../src/example.js';<file_sep>
//ORIGINAL FUNCTION
function randomMonsterGenerator(){
let randomLevel = Math.floor(Math.random() * (6-1) + 1);
let monsterType = Math.floor(Math.random() * (4-1) + 1);
let monsterHp = randomLevel * 5;
monsterName = namePrefix = nameSuffix = "";
if (randomLevel == 1){
namePrefix = "Weak ";
}
if (randomLevel == 2){
namePrefix = "Small ";
}
if (randomLevel == 3){
namePrefix = "";
}
if (randomLevel == 4){
namePrefix = "Large ";
}
if (randomLevel == 5){
namePrefix = "Huge ";
}
if (monsterType == 1){
nameSuffix = "Troll";
}
if (monsterType == 2){
nameSuffix = "Goblin";
}
if (monsterType == 3){
nameSuffix = "Beast";
}
monsterName = namePrefix + nameSuffix;
const randomMonster = {
name: monsterName,
hp: monsterHp,
level: randomLevel
}
console.log(randomMonster);
};
//////SAME FUNCTION JUST USING SWITCH STATEMENTS
function randomMonsterGenerator(){
let randomLevel = Math.floor(Math.random() * (6-1) + 1);
let monsterType = Math.floor(Math.random() * (4-1) + 1);
let monsterHp = randomLevel * 5;
monsterName = namePrefix = nameSuffix = "";
switch (randomLevel){
case 1:
namePrefix = "Weak "
break
case 2:
namePrefix = "Small "
break
case 3:
namePrefix = ""
break
case 4:
namePrefix = "Large "
break
case 5:
namePrefix = "Huge "
break
}
switch (monsterType){
case 1:
nameSuffix = "Troll"
break
case 2:
nameSuffix = "Goblin"
break
case 3:
nameSuffix = "Beast"
break
}
monsterName = namePrefix + nameSuffix;
const randomMonster = {
name: monsterName,
hp: monsterHp,
level: randomLevel
}
return randomMonster;
};
//DRY UP FUNCTION USING AN ARRAY TO HOLD VALUES LIKE A DICTIONARY
function randomMonsterGenerator(){
let randomLevel = Math.floor(Math.random() * (6-1) + 1);
let monsterType = Math.floor(Math.random() * (4-1) + 1);
let monsterHp = randomLevel * 5;
monsterName = "";
prefixDictionary = {
1:"Weak ",
2:"Small ",
3:"",
4:"Large ",
5:"Huge "
}
suffixDictionary = {
1:"Troll",
2:"Goblin",
3:"Beast"
}
monsterName = prefixDictionary[randomLevel] + suffixDictionary[monsterType];
const randomMonster = {
name: monsterName,
hp: monsterHp,
level: randomLevel
}
return randomMonster;
};
//Updated. trying to get the function to assign the new monster object to a var called randomMonster declared outside of the scope of this function.
function randomMonsterGenerator(randomMonster){
let randomLevel = Math.floor(Math.random() * (6-1) + 1);
let monsterType = Math.floor(Math.random() * (4-1) + 1);
let monsterHp = randomLevel * 5;
let monsterName = "";
let prefixDictionary = {
1:"Weak ",
2:"Small ",
3:"",
4:"Large ",
5:"Huge "
};
let suffixDictionary = {
1:"Troll",
2:"Goblin",
3:"Beast"
};
monsterName = prefixDictionary[randomLevel] + suffixDictionary[monsterType];
let newMonster = {
name: monsterName,
hp: monsterHp,
level: randomLevel
};
randomMonster = newMonster;
}
//REDESIGNING COMBAT TO USE DIFFERENT MONSTERS, AND INCORPORATE TURN SYSTEMS
$('#attack').click(function(){
function playerDies(){
$(".page").hide();
$('.playerDeath').fadeIn('slow');
$('.ripText').append(" " + charName);
setTimeout(window.location.reload.bind(window.location), 4500);
}
function checkPlayer(){
if(player().hp <= 0){
setTimeout(playerDies, 1100);
}
}
function checkMonster(){
if (monster1().hp <= 0){
$('.actionOutput').html("You beheaded your enemy! They no longer pose a threat and you can continue advancing.");
refreshMonsterStats(monster1);
$('.enemy').fadeOut('slow');
showWalk();
player(gainExp);
rattle('playerExpRattle','classname2');
checkExp(player);
refreshPlayerStats(player);
}
else {
return;
}
}
$('.actionOutput').fadeOut();
function attackRandomizer(player,monster){
checkMonster();
let attackRoll = Math.floor(Math.random() * (4-1) + 1);
if (attackRoll === 1){
monster(simpleDamage);
$('.actionOutput').html("You knicked the enemy with your sword!");
$('.actionOutput').fadeIn('slow');
checkMonster();
rattle('enemyDamageRattle','classname');
refreshMonsterStats(monster);
refreshPlayerStats(player);
}
if(attackRoll === 2){
player(simpleDamage);
$('.actionOutput').html("You slipped while attacking, and the enemy took a swing at you! Oh no!");
$('.actionOutput').fadeIn('slow');
checkPlayer();
rattle('playerDamageRattle','classname');
refreshPlayerStats(player);
}
else {
monster(maxDamage(player()));
$('.actionOutput').html("Critical hit! Nice shot!");
$('.actionOutput').fadeIn('slow');
checkMonster();
rattle('enemyDamageRattle','classname');
refreshMonsterStats(monster);
refreshPlayerStats(player);
}
refreshMonsterStats(monster);
refreshPlayerStats(player);
}
checkPlayer();
//Below if statement checks players level, and gives them a premade easy monster ONLY the first round of combat
if (player().level == 0){
attackRandomizer(player,monster1);
}
else{
attackRandomizer(player,randomMonster);
}
// player(simpleDamage);
// monster1(maxDamage(player()));
});<file_sep>const storeState = (inputState) => {
let currentState = inputState;
return (stateChangeFunction = state => state) => {
const newState = stateChangeFunction(currentState);
currentState = {...newState};
return newState;
};
};
// const player = storeState({ name: '<NAME>', hp: 10, level: 1, exp: 0, progress: 0});
// const player2 = storeState({ name: '<NAME>', hp: 10, level: 1, exp: 20, progress: 0});
// const monster = storeState({ name: 'lowLevelMonster', hp: 1, level: 1});
// const weakMonster = monster();
//changes the given property of the object
const changeState = (prop) => {
return (value) => {
return (state) => ({
...state,
[prop] : (state[prop] || 0) + value
})
}
}
// these all work
const levelUp = changeState("level")(1);
const gainExp = changeState("exp")(5);
const advance = changeState("progress")(+1);
const resetExp = changeState("exp")(-10);
const heal = (player) => {
return changeState("hp")(player.level * +5);
};
const removeOneHeal = changeState("heals")(-1);
const addOneHeal = changeState("heals")(+1);
//attacking
const simpleDamage = changeState("hp")(-1);
const maxDamage = (player) => {
return changeState("hp")(player.level * -2);
}
// const heal = changeState("hp")(player()["level"]*5);
const healthChange = (value) => {
return changeState("hp")(value);
};
// // change level of player
// player(levelUp)
// // add experience
// player(gainExp)
// // add progress to player
// player(advance)
// // change player health
// player(healthChange(2));
export {
storeState, changeState, levelUp, gainExp, resetExp, heal, removeOneHeal, addOneHeal, advance, simpleDamage, maxDamage
}
<file_sep>// //CSS RATTLE
// function rattle(prop, classname){
// var div = document.getElementById(prop);
// div.classList.remove(classname);
// void div.offsetWidth;
// div.classList.add(classname);
// }
// function getStats(player){
// $('.character').html(`${player().name}`);
// $('#playerHp').html(`Hit Points: ${player().hp}`);
// $('#playerHeals').html(`Available heals: ${player().heals}`);
// $('#playerLevel').html(`Level: ${player().level}`);
// $('#playerExp').html(`Experience: ${player().exp}`);
// $('#playerProgress').html(`Progress: ${player().progress}`);
// }
// function getMonsterStats(monster){
// $('#enemyHp').html(`Hit Points: ${monster().hp}`);
// $('#enemyLevel').html(`Level: ${monster().level}`);
// }
// //GET UPDATED MONSTER FUNCTION
// function refreshMonsterStats(monster){
// $('.enemyName').html(monster().name);
// $('.enemyStats').html(getMonsterStats(monster));
// }
// //GET UPDATED PLAYER FUNCTION
// function refreshPlayerStats(player){
// $(".charStats").html(getStats(player));
// }
// export {
// rattle, getStats, getMonsterStats, refreshMonsterStats, refreshPlayerStats
// }
<file_sep>Things I've currently changed to try and get rattle() to work:
1) commented out the working code, simplified it (so that the buttons aren't up to chance; it saves time clicking)
2)added the rattleDiv around the entire enemy box in index.html for testing
3)changed the getMonsterStats method to append to the html instead of returning a list
4) swapped (in the test code) all the 'refreshMonsterStats' with 'getMonsterStats'.
To do next: incorporate old code to test code, add rattle function when player takes damage.
changed my mind about these below lol
3) changed form group (under header in index.html) visibility in styles.css so i dont have to enter a name and submit every time i refresh for testing
4) hard-coded the player name in main.js to 'Paul' so it doesn't throw compiler error for the change I made (see '3)', directly above). | 9e878a2c63b4b1e3a8669bfa45229f4fa4039635 | [
"JavaScript",
"Text"
]
| 5 | JavaScript | tlpackus/MoonScapeRPG | 195072df548602b0a9d37f6a6f794df080cb30c9 | d5569ec22d5135f775aac86a7a7251b3b8445253 |
refs/heads/master | <repo_name>cgarciahdez/review-me<file_sep>/frontEnd/src/components/proyecto/proyectos.js
import React, {Component} from 'react';
import Proyecto from './proyecto';
import {chunk} from 'lodash'
class Proyectos extends Component{
organize(){
var arr=[]
this.props.proyectos.map((proyecto)=>{
arr.push(<div className="col-md-4"><Proyecto key={proyecto.id} proyecto={proyecto}/></div>);
})
var chu = chunk(arr,3);
return chu;
}
render(){
if (this.props.proyectos){
return(
<div>
<div className="tit text-center">
<h1>
Current projects
</h1>
<hr></hr>
</div>
{this.organize().map((grupo,index)=>{
console.log(grupo);
return(
<div className="row">
{grupo}
</div>
)
})}
</div>
)
}
else{
return(<div></div>);
}
}
}
export default Proyectos;
<file_sep>/backEnd/models/rating.js
'use strict';
const mongo = require('../db');
var collection = 'ratings';
exports.publish = (req, res) => {
res.setHeader('Content-Type', 'application/json');
var body = req.body;
var query = {id: body.id};
mongo.find('ratings', query, (doc) => {
console.log(doc);
var pastAvg, N;
if(doc.length === 0)
{
N = 0;
pastAvg = 0;
}
else
{
var val = doc[0];
N = val.n;
pastAvg = val.avgRating;
}
console.log(N);
console.log(pastAvg);
var avg = (pastAvg*N + body.rating)/(N+1);
var upd = {"id": body.id, "n": N+1, "avgRating": avg};
mongo.update('ratings', query, upd, {upsert:true}, (misc) => {
mongo.find('ratings', query, (doc) => {
res.send(JSON.stringify({ rating: doc }));
})
});
});
}
<file_sep>/frontEnd/src/components/proyecto/comments/comment.js
import React, { PropTypes } from 'react';
import { Well } from 'react-bootstrap';
class Comment extends React.Component {
render () {
return(
<div>
<Well bsSize="small">
{this.props.text}
</Well>
</div>
)
}
}
export default Comment;
<file_sep>/backEnd/models/comment.js
'use strict';
const mongo = require('../db');
var collection = 'comments';
exports.comment = (req, res) => {
res.setHeader('Content-Type', 'application/json');
mongo.insert('comments', req.body, (doc) => {
mongo.find('comments', {'project': req.body.project}, (docs) => {
res.send(JSON.stringify(docs));
})
});
}<file_sep>/README.md
# review-me
The Internet Project Database - A system to review and rate FOSS projects hosted on Github
<file_sep>/frontEnd/src/components/proyecto/proyModal.js
import React, { PropTypes } from 'react';
import { Button, Modal } from 'react-bootstrap';
import Comments from './comments/comments';
import ReactStars from 'react-stars';
class PModal extends React.Component {
constructor(props){
super(props);
console.log(props.comments);
this.state={
showModal:false
}
}
modalClose() {
this.setState({ showModal: false });
}
modalOpen() {
this.setState({ showModal: true });
}
render () {
return(
<div>
<Button bsSize="sm" onClick={this.modalOpen.bind(this)}>
Learn more
</Button>
<Modal show={this.state.showModal} onHide={this.modalClose.bind(this)}>
<Modal.Header closeButton>
<Modal.Title><h2>{this.props.proyecto.name} <small><a href={"https://github.com/"+this.props.proyecto.owner}>{this.props.proyecto.owner}</a></small></h2></Modal.Title>
</Modal.Header>
<Modal.Body>
<h3>Description</h3>
<p>{this.props.proyecto.description}</p>
<hr />
<h3>Open source information</h3>
<div className="row">
<div className ="col-md-3">
<h6><i className="fa fa-code-fork fa-lg" aria-hidden="true"></i> Forks: {this.props.proyecto.repo.forks}</h6>
</div>
<div className ="col-md-3">
<h6><i className="fa fa-star fa-lg" aria-hidden="true"></i> Stars: {this.props.proyecto.repo.stars}</h6>
</div>
<div className ="col-md-3">
<h6><i className="fa fa-eye fa-lg" aria-hidden="true"></i> Watches: {this.props.proyecto.repo.watchers}</h6>
</div>
<div className ="col-md-3">
<h6><i className="fa fa-exclamation-circle fa-lg" aria-hidden="true"></i> Issues: {this.props.proyecto.repo.issues}</h6>
</div>
</div>
<div className="row">
<div className="col-md-12">
<h4>Primary language: <small>{this.props.proyecto.repo.language}</small></h4>
</div>
</div>
{this.props.proyecto.webpage &&
<div className="row">
<div className="col-md-12">
<h4>Webpage: <a href={this.props.proyecto.webpage}><small>{this.props.proyecto.webpage}</small></a></h4>
</div>
</div>
}
<hr/>
{this.props.proyecto.collaborator &&<div>
<h3>Owner's prefered collaborator profile</h3>
<p>{this.props.proyecto.collaborator}</p>
<a href={this.props.proyecto.url}>Start collaborating!</a>
</div>
}
<h3>Rate this project</h3>
<ReactStars count={5} onChange={this.props.addRating} size={24} color2={'#93c54b'} value={this.props.avgRating} />
<h4>Past reviews</h4>
<div className="row">
<Comments alert={this.props.alert} comments={this.props.comments} saveComment={this.props.saveComment}/>
</div>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.modalClose.bind(this)}>Close</Button>
</Modal.Footer>
</Modal>
</div>
)
}
}
export default PModal;
<file_sep>/backEnd/models/project.js
'use strict';
const mongo = require('../db');
const request = require('request');
var assert = require('assert');
var urljoin = require('url-join');
var url = require('url');
var sha3 = require('sha3');
var async = require('async');
var collection = 'projects';
exports.list = (req, res) => {
res.setHeader('Content-Type', 'application/json');
var id = req.params.id;
var search_term = req.query.term;
console.log(search_term);
var query = [];
if(id) query.push({$match: {"id": id}});
query.push(
{
$lookup: {
from: "ratings",
localField: "id",
foreignField: "id",
as: "ratings"
}
}
);
query.push({
$lookup: {
from: "comments",
localField: "id",
foreignField: "project",
as: "comments"
}
});
query.push({
$addFields: {
ratings: "$ratings.avgRating"
}
});
if(search_term)
{
// search_term = search_term.toLowerCase();
query.push({
$match: {
$or: [
{name:{'$regex':'\X*'+search_term+'\X*'}},
{summary:{'$regex':'\X*'+search_term+'\X*'}},
{owner:{'$regex':'\X*'+search_term+'\X*'}}
]
}
});
}
mongo.aggregate('projects', query, (docs) => {
res.send(JSON.stringify({ projects: docs }));
});
}
exports.create = (req, res) => {
res.setHeader('Content-Type', 'application/json');
console.log(req.body);
// See docs/project.json to see example body
var project = req.body;
// Expected: https://github.com/owner/repo
var githubUrl = project.url;
var urlObj = url.parse(githubUrl, false, true);
var path = urlObj.pathname;
console.log(path);
var routes = path.split('/');
var owner = routes[1];
var repo = routes[2];
//Github Processing goes here.
var apiEndpoint = 'https://api.github.com/repos/';
var apiUrl = urljoin(apiEndpoint, owner, repo);
console.log(apiUrl);
var options = {
url: apiUrl,
headers: {
'User-Agent': 'request'
}
};
request.get(options, (error, resp, body) => {
// Body should comply with the JSON form present on docs/repo.json
if(error) throw error;
body = JSON.parse(body);
// console.log(body);
if(resp.statusCode !== 200) {
res.status(resp.statusCode).send();
}
else {
var owner = body.owner;
project.id = body.id;
project.name = body.name;
project.owner = owner.login;
project.summary = body.description;
project.webpage = body.homepage;
project.repo = {
url: body.html_url,
fork: body.fork
};
var info = body;
project.parent_repo = "";
if(body.fork) {
info = body.parent;
project.parent_repo = body.parent.owner.html_url;
}
project.repo.watchers = info.watchers_count;
project.repo.forks = info.forks_count;
project.repo.stars = info.stargazers_count;
project.repo.language = info.language;
project.repo.issues = info.open_issues;
console.log(project);
mongo.insert('projects', project, (doc) => {
res.send(JSON.stringify({ project: doc }));
});
}
});
}
<file_sep>/backEnd/routes/index.js
'use strict';
// Declare more modules here.
const Project = require('../models/project');
const Rating = require('../models/rating');
const Comment = require('../models/comment');
// HTTP endpoints declaration.
module.exports = function(app) {
app.get('/projects', Project.list);
app.get('/projects/:id', Project.list);
app.post('/projects', Project.create);
app.post('/ratings', Rating.publish);
app.post('/comments', Comment.comment);
}
<file_sep>/frontEnd/src/components/navbar.js
import React, { PropTypes } from 'react';
import { Navbar, NavItem, NavDropdown, MenuItem, Nav, FormGroup, FormControl, Button } from 'react-bootstrap';
import PForm from './proyForm'
class Navib extends React.Component {
buscar(term){
this.props.buscar(term);
//aqui se llama para atras a lo que llame a la db
}
constructor(props){
super(props);
this.state={
showModal:false
}
}
modalClose() {
this.setState({ showModal: false });
}
modalOpen() {
this.setState({ showModal: true });
}
render () {
return(
<div>
<Navbar collapseOnSelect className="navbar-fixed-top">
<Navbar.Header>
<Navbar.Brand>
<a href="#"><img src="https://68.media.tumblr.com/024cf54439d1a61124ce6ab1436174c2/tumblr_omb3fcuptx1qh8q8mo1_400.png" width="10px" style={{float:"left","marginRight":"5px"}}></img> Review Me</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem className="newProj" onClick={this.modalOpen.bind(this)}>
<i className="fa fa-plus fa-lg fa-inverse "></i> Add new project
</NavItem>
</Nav>
<Navbar.Form pullLeft>
<FormGroup>
<FormControl type="text" placeholder="Search" onChange={(event) => this.buscar(event.target.value)}/>
</FormGroup>
{' '}
<Button type="submit">Submit</Button>
</Navbar.Form>
</Navbar.Collapse>
</Navbar>
<PForm show={this.state.showModal} modalClose={this.modalClose.bind(this)}></PForm>
</div>
)
}
}
export default Navib;
<file_sep>/frontEnd/src/components/app.js
import React, {Component} from 'react';
import Proyectos from './proyecto/proyectos';
import Navib from './navbar';
import About from './about';
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.state = {
proyectos: []
}
this.getProyectos();
}
buscarProyectos(term){
axios.get(process.env.BACK_URL+ "/projects",{
params:{
"term":term
}
})
.then(response => {
console.log(response);
this.setState({
proyectos: response.data.projects
})
})
}
getProyectos(){
axios.get(process.env.BACK_URL+ "/projects")
.then(response => {
console.log(response);
this.setState({
proyectos: response.data.projects
})
})
}
render(){
return(
<div>
<Navib buscar={this.buscarProyectos.bind(this)}/>
<About/>
<Proyectos proyectos={this.state.proyectos}/>
</div>
)
}
}
export default App;
/*
{
id:1,
name: "Mi primer proyecto",
summary: "soy lo mega max",
description: "Me gustaria que todos me ayudaran en mi proyecto que busca ser un proyecto chevere e innorvador",
collaborator:"que sepa coser que sepa cantar",
img: null,
repo: {
url:"http://github.com/cgarciahdez/cgarciahdez.github.io",
stars:3,
watches:5,
forks:2,
issues:1,
language: "JavaScript"
},
webpage: "http://example.com",
comments:[{text:"wash me encata"},{text:"que es esto tan play"},{text:"wow esta pesimo"}],
author: "YO",
ratings:[3.5]
},
{
id:2,
name: "Mi segundo proyecto",
summary: "soy lo mega max",
description: "Me gustaria que todos me ayudaran en mi proyecto que busca ser un proyecto chevere e innorvador",
img: null,
repo: {
url:"http://github.com/cgarciahdez/cgarciahdez.github.io",
stars:8,
watches:5,
forks:4,
language: "Python"
},
webpage: "",
comments:[{text:"wash me encata"},{text:"que es esto tan play"},{text:"wow esta pesimo"}],
author: "Camis",
ratings:[4.5]
},
{
id:3,
name: "Mi segundo proyecto",
summary: "soy lo mega max",
description: "Me gustaria que todos me ayudaran en mi proyecto que busca ser un proyecto chevere e innorvador",
img: null,
repo: {
url:"http://github.com/cgarciahdez/cgarciahdez.github.io",
stars:8,
watches:5,
forks:4,
language: "Python"
},
webpage: "http://example.com",
comments:[{text:"wash me encata"},{text:"que es esto tan play"},{text:"wow esta pesimo"}],
author: "Camis",
ratings:[3.5]
},
{
id:4,
name: "Mi segundo proyecto",
summary: "soy lo mega max",
description: "Me gustaria que todos me ayudaran en mi proyecto que busca ser un proyecto chevere e innorvador",
img: null,
repo: {
url:"http://github.com/cgarciahdez/cgarciahdez.github.io",
stars:8,
watches:5,
forks:4,
language: "Python"
},
webpage: "http://example.com",
comments:[{text:"wash me encata"},{text:"que es esto tan play"},{text:"wow esta pesimo"}],
author: "Cami",
ratings:[2]
}*/
| 12560a9782a84169e646ef85d9fd5954f7a9c0b4 | [
"JavaScript",
"Markdown"
]
| 10 | JavaScript | cgarciahdez/review-me | 63a1bfcbaa5d8809c7de1d6486de32444ea04cfe | 84ed160294936be23687e877fd88695e5ea4af78 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.